lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
JavaScript
agpl-3.0
4a4a461eea795f47a712a066373d7f11ade1490e
0
asgdf/Pokemon-Showdown-Client,QuiteQuiet/Pokemon-Showdown-Client,asgdf/Pokemon-Showdown-Client,asgdf/Pokemon-Showdown-Client,submindraikou/Pokemon-Showdown-Client,panpawn/Gold-Client,submindraikou/Pokemon-Showdown-Client,Zarel/Pokemon-Showdown-Client,sirDonovan/Pokemon-Showdown-Client,QuiteQuiet/Pokemon-Showdown-Client,submindraikou/Pokemon-Showdown-Client,panpawn/Gold-Client,Zarel/Pokemon-Showdown-Client,asgdf/Pokemon-Showdown-Client,sirDonovan/Pokemon-Showdown-Client,sirDonovan/Pokemon-Showdown-Client,Zarel/Pokemon-Showdown-Client,Zarel/Pokemon-Showdown-Client,sirDonovan/Pokemon-Showdown-Client,panpawn/Gold-Client,QuiteQuiet/Pokemon-Showdown-Client,QuiteQuiet/Pokemon-Showdown-Client
(function (exports, $) { // this is a useful global var teams; var TeambuilderRoom = exports.TeambuilderRoom = exports.Room.extend({ type: 'teambuilder', title: 'Teambuilder', initialize: function () { teams = Storage.teams; // left menu this.$el.addClass('ps-room-light').addClass('scrollable'); if (!Storage.whenTeamsLoaded.isLoaded) { Storage.whenTeamsLoaded(this.update, this); } this.update(); }, focus: function () { if (this.curTeam) { this.curTeam.iconCache = '!'; this.curTeam.gen = this.getGen(this.curTeam.format); Storage.activeSetList = this.curSetList; } }, blur: function () { if (this.saveFlag) { this.saveFlag = false; app.user.trigger('saveteams'); } }, events: { // team changes 'change input.teamnameedit': 'teamNameChange', 'click button.formatselect': 'selectFormat', 'change input[name=nickname]': 'nicknameChange', // details 'change .detailsform input': 'detailsChange', // stats 'keyup .statform input.numform': 'statChange', 'input .statform input[type=number].numform': 'statChange', 'change select[name=nature]': 'natureChange', 'change select[name=ivspread]': 'ivSpreadChange', // teambuilder events 'click .utilichart a': 'chartClick', 'keydown .chartinput': 'chartKeydown', 'keyup .chartinput': 'chartKeyup', 'focus .chartinput': 'chartFocus', 'blur .chartinput': 'chartChange', // drag/drop 'click .team': 'edit', 'click .selectFolder': 'selectFolder', 'mouseover .team': 'mouseOverTeam', 'mouseout .team': 'mouseOutTeam', 'dragstart .team': 'dragStartTeam', 'dragend .team': 'dragEndTeam', 'dragenter .team': 'dragEnterTeam', 'dragenter .folder .selectFolder': 'dragEnterFolder', 'dragleave .folder .selectFolder': 'dragLeaveFolder', 'dragexit .folder .selectFolder': 'dragExitFolder', // clipboard 'click .teambuilder-clipboard-data .result': 'clipboardResultSelect', 'click .teambuilder-clipboard-data': 'clipboardExpand', 'blur .teambuilder-clipboard-data': 'clipboardShrink' }, dispatchClick: function (e) { e.preventDefault(); e.stopPropagation(); if (this[e.currentTarget.value]) this[e.currentTarget.value](e); }, back: function () { if (this.exportMode) { if (this.curTeam) { this.curTeam.team = Storage.packTeam(this.curSetList); Storage.saveTeam(this.curTeam); } this.exportMode = false; } else if (this.curSet) { app.clearGlobalListeners(); this.curSet = null; Storage.saveTeam(this.curTeam); } else if (this.curTeam) { this.curTeam.team = Storage.packTeam(this.curSetList); this.curTeam.iconCache = ''; var team = this.curTeam; this.curTeam = null; Storage.activeSetList = this.curSetList = null; Storage.saveTeam(team); } else { return; } app.user.trigger('saveteams'); this.update(); }, // the teambuilder has three views: // - team list (curTeam falsy) // - team view (curTeam exists, curSet falsy) // - set view (curTeam exists, curSet exists) curTeam: null, curTeamLoc: 0, curSet: null, curSetLoc: 0, // curFolder will have '/' at the end if it's a folder, but // it will be alphanumeric (so guaranteed no '/') if it's a // format // Special values: // '' - show all // 'gen6' - show teams with no format // '/' - show teams with no folder curFolder: '', curFolderKeep: '', exportMode: false, update: function () { teams = Storage.teams; if (this.curTeam) { this.ignoreEVLimits = (this.curTeam.gen < 3); if (this.curSet) { return this.updateSetView(); } return this.updateTeamView(); } return this.updateTeamInterface(); }, /********************************************************* * Team list view *********************************************************/ deletedTeam: null, deletedTeamLoc: -1, updateTeamInterface: function () { this.deletedSet = null; this.deletedSetLoc = -1; var buf = ''; if (this.exportMode) { buf = '<div class="pad"><button name="back"><i class="fa fa-chevron-left"></i> List</button> <button name="saveBackup" class="savebutton"><i class="fa fa-floppy-o"></i> Save</button></div>'; buf += '<div class="teamedit"><textarea class="textbox" rows="17">' + Tools.escapeHTML(Storage.exportAllTeams()) + '</textarea></div>'; this.$el.html(buf); this.$('.teamedit textarea').focus().select(); return; } if (!Storage.whenTeamsLoaded.isLoaded) { if (!Storage.whenTeamsLoaded.isStalled) { buf = '<div class="pad"><p>lol zarel this is a horrible teambuilder</p>'; buf += '<p>that\'s because we\'re not done loading it...</p></div>'; } else { buf = '<div class="pad"><p>We\'re having some trouble loading teams securely.</p>'; buf += '<p>This is sometimes caused by antiviruses like Avast and BitDefender.</p>'; buf += '<p><strong>If you\'re using Firefox and an antivirus:</strong> Your antivirus is trying to scan your teams, and a recent Firefox update doesn\'t let it. Turn off HTTPS scanning in your antivirus or uninstall your antivirus, and your teams will come back.</p>'; buf += '<p>You can use the teambuilder insecurely, but any teams you\'ve saved securely won\'t be there.</p>'; buf += '<p><button class="button" name="insecureUse">Use teambuilder insecurely</button></p></div>'; } this.$el.html(buf); return; } // folderpane buf = '<div class="folderpane">'; buf += '</div>'; // teampane buf += '<div class="teampane">'; buf += '</div>'; this.$el.html(buf); this.updateFolderList(); this.updateTeamList(); }, insecureUse: function () { Storage.whenTeamsLoaded.load(); this.updateTeamInterface(); }, updateFolderList: function () { var buf = '<div class="folderlist"><div class="folderlistbefore"></div>'; buf += '<div class="folder' + (!this.curFolder ? ' cur"><div class="folderhack3"><div class="folderhack1"></div><div class="folderhack2"></div>' : '">') + '<div class="selectFolder" data-value="all"><em>(all)</em></div></div>' + (!this.curFolder ? '</div>' : ''); var folderTable = {}; var folders = []; if (Storage.teams) for (var i = -2; i < Storage.teams.length; i++) { if (i >= 0) { var folder = Storage.teams[i].folder; if (folder && !((folder + '/') in folderTable)) { folders.push('Z' + folder); folderTable[folder + '/'] = 1; if (!('/' in folderTable)) { folders.push('Z~'); folderTable['/'] = 1; } } } var format; if (i === -2) { format = this.curFolderKeep; } else if (i === -1) { format = this.curFolder; } else { format = Storage.teams[i].format; if (!format) format = 'gen6'; } if (!format) continue; if (format in folderTable) continue; folderTable[format] = 1; if (format.slice(-1) === '/') { folders.push('Z' + (format.slice(0, -1) || '~')); if (!('/' in folderTable)) { folders.push('Z~'); folderTable['/'] = 1; } continue; } if (format === 'gen6') { folders.push('A~'); continue; } switch (format.slice(0, 4)) { case 'gen1': format = 'F' + format.slice(4); break; case 'gen2': format = 'E' + format.slice(4); break; case 'gen3': format = 'D' + format.slice(4); break; case 'gen4': format = 'C' + format.slice(4); break; case 'gen5': format = 'B' + format.slice(4); break; default: format = 'A' + format; break; } folders.push(format); } folders.sort(); var gen = ''; var formatFolderBuf = '<div class="foldersep"></div>'; formatFolderBuf += '<div class="folder"><div class="selectFolder" data-value="+"><i class="fa fa-plus"></i><em>(add format folder)</em></div></div>'; for (var i = 0; i < folders.length; i++) { var format = folders[i]; var newGen; switch (format.charAt(0)) { case 'F': newGen = '1'; break; case 'E': newGen = '2'; break; case 'D': newGen = '3'; break; case 'C': newGen = '4'; break; case 'B': newGen = '5'; break; case 'A': newGen = '6'; break; case 'Z': newGen = '/'; break; } if (gen !== newGen) { gen = newGen; if (gen === '/') { buf += formatFolderBuf; formatFolderBuf = ''; buf += '<div class="foldersep"></div>'; buf += '<div class="folder"><h3>Folders</h3></div>'; } else { buf += '<div class="folder"><h3>Gen ' + gen + '</h3></div>'; } } if (gen === '/') { formatName = format.slice(1); format = formatName + '/'; if (formatName === '~') { formatName = '(uncategorized)'; format = '/'; } else { formatName = Tools.escapeHTML(formatName); } buf += '<div class="folder' + (this.curFolder === format ? ' cur"><div class="folderhack3"><div class="folderhack1"></div><div class="folderhack2"></div>' : '">') + '<div class="selectFolder" data-value="' + format + '"><i class="fa ' + (this.curFolder === format ? 'fa-folder-open' : 'fa-folder') + (format === '/' ? '-o' : '') + '"></i>' + formatName + '</div></div>' + (this.curFolder === format ? '</div>' : ''); continue; } var formatName = format.slice(1); if (formatName === '~') formatName = ''; if (newGen === '6' && formatName) { format = formatName; } else { format = 'gen' + newGen + formatName; } if (format === 'gen6') formatName = '(uncategorized)'; // folders are <div>s rather than <button>s because in theory it has // less weird interactions with HTML5 drag-and-drop buf += '<div class="folder' + (this.curFolder === format ? ' cur"><div class="folderhack3"><div class="folderhack1"></div><div class="folderhack2"></div>' : '">') + '<div class="selectFolder" data-value="' + format + '"><i class="fa ' + (this.curFolder === format ? 'fa-folder-open-o' : 'fa-folder-o') + '"></i>' + formatName + '</div></div>' + (this.curFolder === format ? '</div>' : ''); } buf += formatFolderBuf; buf += '<div class="foldersep"></div>'; buf += '<div class="folder"><div class="selectFolder" data-value="++"><i class="fa fa-plus"></i><em>(add folder)</em></div></div>'; buf += '<div class="folderlistafter"></div></div>'; this.$('.folderpane').html(buf); }, updateTeamList: function (resetScroll) { var teams = Storage.teams; var buf = ''; // teampane buf += this.clipboardHTML(); var filterFormat = ''; var filterFolder = undefined; if (!this.curFolder) { buf += '<h2>Hi</h2>'; buf += '<p>Did you have a good day?</p>'; buf += '<p><button class="button" name="greeting" value="Y"><i class="fa fa-smile-o"></i> Yes, my day was pretty good</button> <button class="button" name="greeting" value="N"><i class="fa fa-frown-o"></i> No, it wasn\'t great</button></p>'; buf += '<h2>All teams</h2>'; } else { if (this.curFolder.slice(-1) === '/') { filterFolder = this.curFolder.slice(0, -1); if (filterFolder) { buf += '<h2><i class="fa fa-folder-open"></i> ' + filterFolder + ' <button class="button small" style="margin-left:5px" name="renameFolder"><i class="fa fa-pencil"></i> Rename</button> <button class="button small" style="margin-left:5px" name="promptDeleteFolder"><i class="fa fa-times"></i> Remove</button></h2>'; } else { buf += '<h2><i class="fa fa-folder-open-o"></i> Teams not in any folders</h2>'; } } else { filterFormat = this.curFolder; buf += '<h2><i class="fa fa-folder-open-o"></i> ' + filterFormat + '</h2>'; } } var newButtonText = "New Team"; if (filterFolder) newButtonText = "New Team in folder"; if (filterFormat && filterFormat !== 'gen6') { newButtonText = "New " + Tools.escapeFormat(filterFormat) + " Team"; } buf += '<p><button name="newTop" class="button big"><i class="fa fa-plus-circle"></i> ' + newButtonText + '</button></p>'; buf += '<ul class="teamlist">'; var atLeastOne = false; try { if (!window.localStorage && !window.nodewebkit) buf += '<li>== CAN\'T SAVE ==<br /><small>Your browser doesn\'t support <code>localStorage</code> and can\'t save teams! Update to a newer browser.</small></li>'; } catch (e) { buf += '<li>== CAN\'T SAVE ==<br /><small><code>Cookies</code> are disabled so you can\'t save teams! Enable them in your browser settings.</small></li>'; } if (Storage.cantSave) buf += '<li>== CAN\'T SAVE ==<br /><small>You hit your browser\'s limit for team storage! Please backup them and delete some of them. Your teams won\'t be saved until you\'re under the limit again.</small></li>'; if (!teams.length) { if (this.deletedTeamLoc >= 0) { buf += '<li><button name="undoDelete"><i class="fa fa-undo"></i> Undo Delete</button></li>'; } buf += '<li><p><em>you don\'t have any teams lol</em></p></li>'; } else { for (var i = 0; i < teams.length + 1; i++) { if (i === this.deletedTeamLoc) { if (!atLeastOne) atLeastOne = true; buf += '<li><button name="undoDelete"><i class="fa fa-undo"></i> Undo Delete</button></li>'; } if (i >= teams.length) break; var team = teams[i]; if (team && !team.team && team.team !== '') { team = null; } if (!team) { buf += '<li>Error: A corrupted team was dropped</li>'; teams.splice(i, 1); i--; if (this.deletedTeamLoc && this.deletedTeamLoc > i) this.deletedTeamLoc--; continue; } if (filterFormat && filterFormat !== (team.format || 'gen6')) continue; if (filterFolder !== undefined && filterFolder !== team.folder) continue; if (!atLeastOne) atLeastOne = true; var formatText = ''; if (team.format) { formatText = '[' + team.format + '] '; } if (team.folder) formatText += team.folder + '/'; // teams are <div>s rather than <button>s because Firefox doesn't // support dragging and dropping buttons. buf += '<li><div name="edit" data-value="' + i + '" class="team" draggable="true">' + formatText + '<strong>' + Tools.escapeHTML(team.name) + '</strong><br /><small>'; buf += Storage.getTeamIcons(team); buf += '</small></div><button name="edit" value="' + i + '"><i class="fa fa-pencil"></i>Edit</button><button name="delete" value="' + i + '"><i class="fa fa-trash"></i>Delete</button></li>'; } if (!atLeastOne) { if (filterFolder) { buf += '<li><p><em>you don\'t have any teams in this folder lol</em></p></li>'; } else { buf += '<li><p><em>you don\'t have any ' + this.curFolder + ' teams lol</em></p></li>'; } } } buf += '</ul>'; if (atLeastOne) { buf += '<p><button name="new" class="button"><i class="fa fa-plus-circle"></i> ' + newButtonText + '</button></p>'; } if (window.nodewebkit) { buf += '<button name="revealFolder" class="button"><i class="fa fa-folder-open"></i> Reveal teams folder</button> <button name="reloadTeamsFolder" class="button"><i class="fa fa-refresh"></i> Reload teams files</button> <button name="backup" class="button"><i class="fa fa-upload"></i> Backup/Restore all teams</button>'; } else if (atLeastOne) { buf += '<p><strong>Clearing your cookies (specifically, <code>localStorage</code>) will delete your teams.</strong></p>'; buf += '<button name="backup" class="button"><i class="fa fa-upload"></i> Backup/Restore all teams</button>'; buf += '<p>If you want to clear your cookies or <code>localStorage</code>, you can use the Backup/Restore feature to save your teams as text first.</p>'; } else { buf += '<button name="backup" class="button"><i class="fa fa-upload"></i> Restore teams from backup</button>'; } var $pane = this.$('.teampane'); $pane.html(buf); if (resetScroll) { $pane.scrollTop(0); } else if (this.teamScrollPos) { $pane.scrollTop(this.teamScrollPos); this.teamScrollPos = 0; } }, greeting: function (answer, button) { var buf = '<p><strong>' + $(button).html() + '</p></strong>'; if (answer === 'N') { buf += '<p>Aww, that\'s too bad. :( I hope playing on Pok&eacute;mon Showdown today can help cheer you up!</p>'; } else if (answer === 'Y') { buf += '<p>Cool! I just added some pretty cool teambuilder features, so I\'m pretty happy, too. Did you know you can drag and drop teams to different format-folders? You can also drag and drop them to and from your computer (works best in Chrome).</p>'; buf += '<p><button class="button" name="greeting" value="W"><i class="fa fa-question-circle"></i> Wait, who are you? Talking to a teambuilder is weird.</button></p>'; } else if (answer === 'W') { buf += '<p>Oh, I\'m Zarel! I made a Credits button for this...</p>'; buf += '<div class="menugroup"><p><button class="button mainmenu4" name="credits"><i class="fa fa-info-circle"></i> Credits</button></p></div>'; buf += '<p>Isn\'t it pretty? Matches your background and everything. It used to be in the Main Menu but we had to get rid of it to save space.</p>'; buf += '<p>Speaking of, you should try <button class="button" name="background"><i class="fa fa-picture-o"></i> changing your background</button>.'; buf += '<p><button class="button" name="greeting" value="B"><i class="fa fa-hand-pointer-o"></i> You might be having too much fun with these buttons and icons</button></p>'; } else if (answer === 'B') { buf += '<p>I paid good money for those icons! I need to get my money\'s worth!</p>'; buf += '<p><button class="button" name="greeting" value="WR"><i class="fa fa-exclamation-triangle"></i> Wait, really?</button></p>'; } else if (answer === 'WR') { buf += '<p>No, they were free. That just makes it easier to get my money\'s worth. Let\'s play rock paper scissors!</p>'; buf += '<p><button class="button" name="greeting" value="RR"><i class="fa fa-hand-rock-o"></i> Rock</button> <button class="button" name="greeting" value="RP"><i class="fa fa-hand-paper-o"></i> Paper</button> <button class="button" name="greeting" value="RS"><i class="fa fa-hand-scissors-o"></i> Scissors</button> <button class="button" name="greeting" value="RL"><i class="fa fa-hand-lizard-o"></i> Lizard</button> <button class="button" name="greeting" value="RK"><i class="fa fa-hand-spock-o"></i> Spock</button></p>'; } else if (answer[0] === 'R') { buf += '<p>I play laser, I win. <i class="fa fa-hand-o-left"></i></p>'; buf += '<p><button class="button" name="greeting" value="YC"><i class="fa fa-thumbs-o-down"></i> You can\'t do that!</button></p>'; } else if (answer === 'SP') { buf += '<p>Okay, sure. I warn you, I\'m using the same RNG that makes Stone Edge miss for you.</p>'; buf += '<p><button class="button" name="greeting" value="SP3"><i class="fa fa-caret-square-o-right"></i> I want to play Rock Paper Scissors</button> <button class="button" name="greeting" value="SP5"><i class="fa fa-caret-square-o-right"></i> I want to play Rock Paper Scissors Lizard Spock</button></p>'; } else if (answer === 'SP3') { buf += '<p><button class="button" name="greeting" value="PR3"><i class="fa fa-hand-rock-o"></i> Rock</button> <button class="button" name="greeting" value="PP3"><i class="fa fa-hand-paper-o"></i> Paper</button> <button class="button" name="greeting" value="PS3"><i class="fa fa-hand-scissors-o"></i> Scissors</button></p>'; } else if (answer === 'SP5') { buf += '<p><button class="button" name="greeting" value="PR5"><i class="fa fa-hand-rock-o"></i> Rock</button> <button class="button" name="greeting" value="PP5"><i class="fa fa-hand-paper-o"></i> Paper</button> <button class="button" name="greeting" value="PS5"><i class="fa fa-hand-scissors-o"></i> Scissors</button> <button class="button" name="greeting" value="PL5"><i class="fa fa-hand-lizard-o"></i> Lizard</button> <button class="button" name="greeting" value="PK5"><i class="fa fa-hand-spock-o"></i> Spock</button></p>'; } else if (answer[0] === 'P') { var rpsChart = { R: 'rock', P: 'paper', S: 'scissors', L: 'lizard', K: 'spock' }; var rpsWinChart = { SP: 'cuts', SL: 'decapitates', PR: 'covers', PK: 'disproves', RL: 'crushes', RS: 'crushes', LK: 'poisons', LP: 'eats', KS: 'smashes', KR: 'vaporizes' }; var my = ['R', 'P', 'S', 'L', 'K'][Math.floor(Math.random() * Number(answer[2]))]; var your = answer[1]; buf += '<p>I play <i class="fa fa-hand-' + rpsChart[my] + '-o"></i> ' + rpsChart[my] + '!</p>'; if ((my + your) in rpsWinChart) { buf += '<p>And ' + rpsChart[my] + ' ' + rpsWinChart[my + your] + ' ' + rpsChart[your] + ', so I win!</p>'; } else if ((your + my) in rpsWinChart) { buf += '<p>But ' + rpsChart[your] + ' ' + rpsWinChart[your + my] + ' ' + rpsChart[my] + ', so you win...</p>'; } else { buf += '<p>We played the same thing, so it\'s a tie.</p>'; } if (!this.rpsScores || !this.rpsScores.length) { this.rpsScores = ['pi', '$3.50', '9.80665 m/s<sup>2</sup>', '28°C', '百万点', '<i class="fa fa-bitcoin"></i>0.0000174', '<s>priceless</s> <i class="fa fa-cc-mastercard"></i> MasterCard', '127.0.0.1', 'C&minus;, see me after class']; } var score = this.rpsScores.splice(Math.floor(Math.random() * this.rpsScores.length), 1)[0]; buf += '<p>Score: ' + score + '</p>'; buf += '<p><button class="button" name="greeting" value="SP' + answer[2] + '"><i class="fa fa-caret-square-o-right"></i> I demand a rematch!</button></p>'; } else if (answer === 'YC') { buf += '<p>Okay, then I play peace sign <i class="fa fa-hand-peace-o"></i>, everyone signs a peace treaty, ending the war and ushering in a new era of prosperity.</p>'; buf += '<p><button class="button" name="greeting" value="SP"><i class="fa fa-caret-square-o-right"></i> I wanted to play for real...</button></p>'; } $(button).parent().replaceWith(buf); }, credits: function () { app.addPopup(CreditsPopup); }, background: function () { app.addPopup(CustomBackgroundPopup); }, selectFolder: function (format) { if (format && format.currentTarget) { var e = format; format = $(e.currentTarget).data('value'); e.preventDefault(); if (format === '+') { e.stopImmediatePropagation(); var self = this; app.addPopup(FormatPopup, {format: '', sourceEl: e.currentTarget, selectType: 'teambuilder', onselect: function (newFormat) { self.selectFolder(newFormat); }}); return; } if (format === '++') { e.stopImmediatePropagation(); var self = this; // app.addPopupPrompt("Folder name:", "Create folder", function (newFormat) { // self.selectFolder(newFormat + '/'); // }); app.addPopup(PromptPopup, {message: "Folder name:", button: "Create folder", sourceEl: e.currentTarget, callback: function (name) { name = $.trim(name); if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) { app.addPopupMessage("Names can't contain slashes, since they're used as a folder separator."); name = name.replace(/[\\\/]/g, ''); } if (!name) return; self.selectFolder(name + '/'); }}); return; } } else { this.curFolderKeep = format; } this.curFolder = (format === 'all' ? '' : format); this.updateFolderList(); this.updateTeamList(true); }, renameFolder: function () { if (!this.curFolder) return; if (this.curFolder.slice(-1) !== '/') return; var oldFolder = this.curFolder.slice(0, -1); var self = this; app.addPopup(PromptPopup, {message: "Folder name:", button: "Rename folder", value: oldFolder, callback: function (name) { name = $.trim(name); if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) { app.addPopupMessage("Names can't contain slashes, since they're used as a folder separator."); name = name.replace(/[\\\/]/g, ''); } if (!name) return; if (name === oldFolder) return; for (var i = 0; i < Storage.teams.length; i++) { var team = Storage.teams[i]; if (team.folder !== oldFolder) continue; team.folder = name; if (window.nodewebkit) Storage.saveTeam(team); } if (!window.nodewebkit) Storage.saveTeams(); self.selectFolder(name + '/'); }}); }, promptDeleteFolder: function () { app.addPopup(DeleteFolderPopup, {folder: this.curFolder, room: this}); }, deleteFolder: function (format, addName) { if (format.slice(-1) !== '/') return; var oldFolder = format.slice(0, -1); if (this.curFolderKeep === oldFolder) { this.curFolderKeep = ''; } for (var i = 0; i < Storage.teams.length; i++) { var team = Storage.teams[i]; if (team.folder !== oldFolder) continue; team.folder = ''; if (addName) team.name = oldFolder + ' ' + team.name; if (window.nodewebkit) Storage.saveTeam(team); } if (!window.nodewebkit) Storage.saveTeams(); this.selectFolder('/'); }, show: function () { Room.prototype.show.apply(this, arguments); var $teamwrapper = this.$('.teamwrapper'); var width = $(window).width(); if (!$teamwrapper.length) return; if (width < 640) { var scale = (width / 640); $teamwrapper.css('transform', 'scale(' + scale + ')'); $teamwrapper.addClass('scaled'); } else { $teamwrapper.css('transform', 'none'); $teamwrapper.removeClass('scaled'); } }, // button actions revealFolder: function () { Storage.revealFolder(); }, reloadTeamsFolder: function () { Storage.nwLoadTeams(); }, edit: function (i) { this.teamScrollPos = this.$('.teampane').scrollTop(); if (i && i.currentTarget) { i = $(i.currentTarget).data('value'); } i = +i; this.curTeam = teams[i]; this.curTeam.iconCache = '!'; this.curTeam.gen = this.getGen(this.curTeam.format); Storage.activeSetList = this.curSetList = Storage.unpackTeam(this.curTeam.team); this.curTeamIndex = i; this.update(); }, "delete": function (i) { i = +i; this.deletedTeamLoc = i; this.deletedTeam = teams.splice(i, 1)[0]; for (var room in app.rooms) { var selection = app.rooms[room].$('button.teamselect').val(); if (!selection || selection === 'random') continue; var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox; if (i < obj.curTeamIndex) { obj.curTeamIndex--; } else if (i === obj.curTeamIndex) { obj.curTeamIndex = -1; } } Storage.deleteTeam(this.deletedTeam); app.user.trigger('saveteams'); this.updateTeamList(); }, undoDelete: function () { if (this.deletedTeamLoc >= 0) { teams.splice(this.deletedTeamLoc, 0, this.deletedTeam); for (var room in app.rooms) { var selection = app.rooms[room].$('button.teamselect').val(); if (!selection || selection === 'random') continue; var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox; if (this.deletedTeamLoc < obj.curTeamIndex + 1) { obj.curTeamIndex++; } else if (obj.curTeamIndex === -1) { obj.curTeamIndex = this.deletedTeamLoc; } } var undeletedTeam = this.deletedTeam; this.deletedTeam = null; this.deletedTeamLoc = -1; Storage.saveTeam(undeletedTeam); app.user.trigger('saveteams'); this.update(); } }, saveBackup: function () { Storage.deleteAllTeams(); Storage.importTeam(this.$('.teamedit textarea').val(), true); teams = Storage.teams; Storage.saveAllTeams(); for (var room in app.rooms) { var selection = app.rooms[room].$('button.teamselect').val(); if (!selection || selection === 'random') continue; var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox; obj.curTeamIndex = 0; } this.back(); }, "new": function () { var format = this.curFolder; var folder = ''; if (format && format.charAt(format.length - 1) === '/') { folder = format.slice(0, -1); format = ''; } var newTeam = { name: 'Untitled ' + (teams.length + 1), format: format, team: '', folder: folder, iconCache: '' }; teams.push(newTeam); this.edit(teams.length - 1); }, newTop: function () { var format = this.curFolder; var folder = ''; if (format && format.charAt(format.length - 1) === '/') { folder = format.slice(0, -1); format = ''; } var newTeam = { name: 'Untitled ' + (teams.length + 1), format: format, team: '', folder: folder, iconCache: '' }; teams.unshift(newTeam); for (var room in app.rooms) { var selection = app.rooms[room].$('button.teamselect').val(); if (!selection || selection === 'random') continue; var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox; obj.curTeamIndex++; } this.edit(0); }, "import": function () { if (this.exportMode) return this.back(); this.exportMode = true; if (!this.curTeam) { this['new'](); } else { this.update(); } }, backup: function () { this.curTeam = null; this.curSetList = null; this.exportMode = true; this.update(); }, // drag and drop // because of a bug in Chrome and Webkit: // https://code.google.com/p/chromium/issues/detail?id=410328 // we can't use CSS :hover mouseOverTeam: function (e) { e.currentTarget.className = 'team team-hover'; }, mouseOutTeam: function (e) { e.currentTarget.className = 'team'; }, dragStartTeam: function (e) { var target = e.currentTarget; var dataTransfer = e.originalEvent.dataTransfer; dataTransfer.effectAllowed = 'copyMove'; dataTransfer.setData("text/plain", "Team " + e.currentTarget.dataset.value); var team = Storage.teams[e.currentTarget.dataset.value]; var filename = team.name; if (team.format) filename = '[' + team.format + '] ' + filename; filename = $.trim(filename).replace(/[\\\/]+/g, '') + '.txt'; var urlprefix = "data:text/plain;base64,"; if (document.location.protocol === 'https:') { // Chrome is dumb and doesn't support data URLs in HTTPS urlprefix = "https://play.pokemonshowdown.com/action.php?act=dlteam&team="; } var contents = Storage.exportTeam(team.team).replace(/\n/g, '\r\n'); var downloadurl = "text/plain:" + filename + ":" + urlprefix + encodeURIComponent(window.btoa(unescape(encodeURIComponent(contents)))); console.log(downloadurl); dataTransfer.setData("DownloadURL", downloadurl); app.dragging = e.currentTarget; app.draggingRoom = this.id; app.draggingLoc = parseInt(e.currentTarget.dataset.value, 10); var elOffset = $(e.currentTarget).offset(); app.draggingOffsetX = e.originalEvent.pageX - elOffset.left; app.draggingOffsetY = e.originalEvent.pageY - elOffset.top; this.finalOffset = null; setTimeout(function () { $(e.currentTarget).parent().addClass('dragging'); }, 0); }, dragEndTeam: function (e) { this.finishDrop(); }, finishDrop: function () { var teamEl = app.dragging; app.dragging = null; var originalLoc = parseInt(teamEl.dataset.value, 10); if (isNaN(originalLoc)) { throw new Error("drag failed"); } var newLoc = Math.floor(app.draggingLoc); if (app.draggingLoc < originalLoc) newLoc += 1; var team = Storage.teams[originalLoc]; var edited = false; if (newLoc !== originalLoc) { Storage.teams.splice(originalLoc, 1); Storage.teams.splice(newLoc, 0, team); for (var room in app.rooms) { var selection = app.rooms[room].$('button.teamselect').val(); if (!selection || selection === 'random') continue; var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox; if (originalLoc === obj.curTeamIndex) { obj.curTeamIndex = newLoc; } else if (originalLoc > obj.curTeamIndex && newLoc <= obj.curTeamIndex) { obj.curTeamIndex++; } else if (originalLoc < obj.curTeamIndex && newLoc >= obj.curTeamIndex) { obj.curTeamIndex--; } } edited = true; } // possibly half-works-around a hover issue in this.$('.teamlist').css('pointer-events', 'none'); $(teamEl).parent().removeClass('dragging'); var format = this.curFolder; if (app.draggingFolder) { var $folder = $(app.draggingFolder); app.draggingFolder = null; var $plusOneFolder = $folder.find('.plusonefolder'); $folder.removeClass('active'); if (!$plusOneFolder.length) { $folder.prepend('<strong style="float:right;margin-right:3px;padding:0 2px;border-radius:3px;background:#CC8500;color:white" class="plusonefolder">+1</strong>'); } else { var count = Number($plusOneFolder.text().substr(1)) + 1; $plusOneFolder.text('+' + count); } format = $folder.data('value'); if (format.slice(-1) === '/') { team.folder = format.slice(0, -1); } else { team.format = format; } edited = true; this.updateTeamList(); } else { if (format.slice(-1) === '/') { team.folder = format.slice(0, -1); edited = true; } this.updateTeamList(); } if (edited) { Storage.saveTeam(team); app.user.trigger('saveteams'); } // We're going to try to animate the team settling into its new position if (this.finalOffset) { // event.pageY and event.pageX are buggy on literally every browser: // in Chrome: // event.pageX|pageY is the position of the bottom left corner of the draggable, instead // of the mouse position // in Safari: // window.innerHeight * 2 - window.outerHeight - event.pageY is the mouse position // No, I don't understand what's going on, either, but unsurprisingly this fails utterly // if the page is zoomed. // in Firefox: // event.pageX|pageY are straight-up unsupported // if you don't believe me, uncomment and see for yourself: // console.log('x,y = ' + [e.originalEvent.x, e.originalEvent.y]); // console.log('screenX,screenY = ' + [e.originalEvent.screenX, e.originalEvent.screenY]); // console.log('clientX,clientY = ' + [e.originalEvent.clientX, e.originalEvent.clientY]); // console.log('pageX,pageY = ' + [e.originalEvent.pageX, e.originalEvent.pageY]); // Because of this, we're just going to steal the values from the drop event, where // everything is sane. var $newTeamEl = this.$('.team[data-value=' + newLoc + ']'); if (!$newTeamEl.length) return; var finalPos = $newTeamEl.offset(); $newTeamEl.css('transform', 'translate(' + (this.finalOffset[0] - finalPos.left) + 'px, ' + (this.finalOffset[1] - finalPos.top) + 'px)'); setTimeout(function () { $newTeamEl.css('transition', 'transform 0.15s'); // it's 2015 and Safari doesn't support unprefixed transition!!! $newTeamEl.css('-webkit-transition', '-webkit-transform 0.15s'); $newTeamEl.css('transform', 'translate(0px, 0px)'); }); } }, dragEnterTeam: function (e) { if (!app.dragging) return; var $draggingLi = $(app.dragging).parent(); this.dragLeaveFolder(); if (e.currentTarget === app.dragging) { e.preventDefault(); return; } var hoverLoc = parseInt(e.currentTarget.dataset.value, 10); if (app.draggingLoc > hoverLoc) { // dragging up $(e.currentTarget).parent().before($draggingLi); app.draggingLoc = parseInt(e.currentTarget.dataset.value, 10) - 0.5; } else { // dragging down $(e.currentTarget).parent().after($draggingLi); app.draggingLoc = parseInt(e.currentTarget.dataset.value, 10) + 0.5; } }, dragEnterFolder: function (e) { if (!app.dragging) return; this.dragLeaveFolder(); if (e.currentTarget === app.draggingFolder) { return; } var format = e.currentTarget.dataset.value; if (format === '+' || format === '++' || format === 'all' || format === this.curFolder) { return; } if (parseInt(app.dragging.dataset.value, 10) >= Storage.teams.length && format.slice(-1) !== '/') { // dragging a team file, already has a known format return; } app.draggingFolder = e.currentTarget; $(app.draggingFolder).addClass('active'); // amusing note: using .detach() instead of .hide() will make `dragend` not fire $(app.dragging).parent().hide(); }, dragLeaveFolder: function (e) { // sometimes there's a race condition and dragEnter happens before dragLeave if (e && e.currentTarget !== app.draggingFolder) return; if (!app.dragging || !app.draggingFolder) return; $(app.draggingFolder).removeClass('active'); app.draggingFolder = null; $(app.dragging).parent().show(); }, defaultDragEnterTeam: function (e) { var dataTransfer = e.originalEvent.dataTransfer; if (!dataTransfer) return; if (dataTransfer.types.indexOf && dataTransfer.types.indexOf('Files') === -1) return; if (dataTransfer.types.contains && !dataTransfer.types.contains('Files')) return; if (dataTransfer.files[0] && dataTransfer.files[0].name.slice(-4) !== '.txt') return; // We're dragging a file! It might be a team! if (app.curFolder && app.curFolder.slice(-1) !== '/') { this.selectFolder('all'); } this.$('.teamlist').append('<li class="dragging"><div class="team" data-value="' + Storage.teams.length + '"></div></li>'); app.dragging = this.$('.dragging .team')[0]; app.draggingRoom = this.id; app.draggingLoc = Storage.teams.length; app.draggingOffsetX = 180; app.draggingOffsetY = 25; }, defaultDropTeam: function (e) { if (e.originalEvent.dataTransfer.files && e.originalEvent.dataTransfer.files[0]) { var file = e.originalEvent.dataTransfer.files[0]; var name = file.name; if (name.slice(-4) !== '.txt') { app.dragging = null; this.updateTeamList(); app.addPopupMessage("Your file is not a valid team. Team files are .txt files."); return; } var reader = new FileReader(); var self = this; reader.onload = function (e) { var team; try { team = Storage.packTeam(Storage.importTeam(e.target.result)); } catch (err) { app.addPopupMessage("Your file is not a valid team."); self.updateTeamList(); return; } var name = file.name; if (name.slice(name.length - 4).toLowerCase() === '.txt') { name = name.substr(0, name.length - 4); } var format = ''; var bracketIndex = name.indexOf(']'); if (bracketIndex >= 0) { format = name.substr(1, bracketIndex - 1); name = $.trim(name.substr(bracketIndex + 1)); } Storage.teams.push({ name: name, format: format, team: team, folder: '', iconCache: '' }); self.finishDrop(); }; reader.readAsText(file); } this.finalOffset = [e.originalEvent.pageX - app.draggingOffsetX, e.originalEvent.pageY - app.draggingOffsetY]; }, /********************************************************* * Team view *********************************************************/ updateTeamView: function () { this.curChartName = ''; this.curChartType = ''; var buf = ''; if (this.exportMode) { buf = '<div class="pad"><button name="back"><i class="fa fa-chevron-left"></i> List</button> <input class="textbox teamnameedit" type="text" class="teamnameedit" size="30" value="' + Tools.escapeHTML(this.curTeam.name) + '" /> <button name="saveImport"><i class="fa fa-upload"></i> Import/Export</button> <button name="saveImport" class="savebutton"><i class="fa fa-floppy-o"></i> Save</button></div>'; buf += '<div class="teamedit"><textarea class="textbox" rows="17">' + Tools.escapeHTML(Storage.exportTeam(this.curSetList)) + '</textarea></div>'; } else { buf = '<div class="pad"><button name="back"><i class="fa fa-chevron-left"></i> List</button> <input class="textbox teamnameedit" type="text" class="teamnameedit" size="30" value="' + Tools.escapeHTML(this.curTeam.name) + '" /> <button name="import"><i class="fa fa-upload"></i> Import/Export</button></div>'; buf += '<div class="teamchartbox">'; buf += '<ol class="teamchart">'; buf += '<li>' + this.clipboardHTML() + '</li>'; var i = 0; if (this.curSetList.length && !this.curSetList[this.curSetList.length - 1].species) { this.curSetList.splice(this.curSetList.length - 1, 1); } if (exports.BattleFormats) { buf += '<li class="format-select">'; buf += '<label class="label">Format:</label><button class="select formatselect teambuilderformatselect" name="format" value="' + this.curTeam.format + '">' + (Tools.escapeFormat(this.curTeam.format) || '<em>Select a format</em>') + '</button>'; var btnClass = 'button' + (!this.curSetList.length ? ' disabled' : ''); buf += ' <button name="validate" class="' + btnClass + '"><i class="fa fa-check"></i> Validate</button></li>'; } if (!this.curSetList.length) { buf += '<li><em>you have no pokemon lol</em></li>'; } for (i = 0; i < this.curSetList.length; i++) { if (this.curSetList.length < 6 && this.deletedSet && i === this.deletedSetLoc) { buf += '<li><button name="undeleteSet"><i class="fa fa-undo"></i> Undo Delete</button></li>'; } buf += this.renderSet(this.curSetList[i], i); } if (this.deletedSet && i === this.deletedSetLoc) { buf += '<li><button name="undeleteSet"><i class="fa fa-undo"></i> Undo Delete</button></li>'; } if (i === 0) { buf += '<li><button name="import" class="button big"><i class="fa fa-upload"></i> Import from text</button></li>'; } if (i < 6) { buf += '<li><button name="addPokemon" class="button big"><i class="fa fa-plus"></i> Add Pok&eacute;mon</button></li>'; } buf += '</ol>'; buf += '</div>'; } this.$el.html('<div class="teamwrapper">' + buf + '</div>'); this.$(".teamedit textarea").focus().select(); if ($(window).width() < 640) this.show(); }, renderSet: function (set, i) { var template = Tools.getTemplate(set.species); var buf = '<li value="' + i + '">'; if (!set.species) { if (this.deletedSet) { buf += '<div class="setmenu setmenu-left"><button name="undeleteSet"><i class="fa fa-undo"></i> Undo Delete</button></div>'; } buf += '<div class="setmenu"><button name="importSet"><i class="fa fa-upload"></i>Import</button></div>'; buf += '<div class="setchart" style="background-image:url(' + Tools.resourcePrefix + 'sprites/bw/0.png);"><div class="setcol setcol-icon"><span class="itemicon"></span><div class="setcell setcell-pokemon"><label>Pok&eacute;mon</label><input type="text" name="pokemon" class="textbox chartinput" value="" /></div></div></div>'; buf += '</li>'; return buf; } buf += '<div class="setmenu"><button name="copySet"><i class="fa fa-files-o"></i>Copy</button> <button name="importSet"><i class="fa fa-upload"></i>Import/Export</button> <button name="moveSet"><i class="fa fa-arrows"></i>Move</button> <button name="deleteSet"><i class="fa fa-trash"></i>Delete</button></div>'; buf += '<div class="setchart-nickname">'; buf += '<label>Nickname</label><input type="text" name="nickname" class="textbox" value="' + Tools.escapeHTML(set.name || '') + '" placeholder="' + Tools.escapeHTML(template.baseSpecies) + '" />'; buf += '</div>'; buf += '<div class="setchart" style="' + Tools.getTeambuilderSprite(set, this.curTeam.gen) + ';">'; // icon var itemicon = '<span class="itemicon"></span>'; if (set.item) { var item = Tools.getItem(set.item); itemicon = '<span class="itemicon" style="' + Tools.getItemIcon(item) + '"></span>'; } buf += '<div class="setcol setcol-icon">' + itemicon + '<div class="setcell setcell-pokemon"><label>Pok&eacute;mon</label><input type="text" name="pokemon" class="textbox chartinput" value="' + Tools.escapeHTML(set.species) + '" /></div></div>'; // details buf += '<div class="setcol setcol-details"><div class="setrow">'; buf += '<div class="setcell setcell-details"><label>Details</label><button class="textbox setdetails" tabindex="-1" name="details">'; var GenderChart = { 'M': 'Male', 'F': 'Female', 'N': '&mdash;' }; buf += '<span class="detailcell detailcell-first"><label>Level</label>' + (set.level || 100) + '</span>'; if (this.curTeam.gen > 1) { buf += '<span class="detailcell"><label>Gender</label>' + GenderChart[set.gender || template.gender || 'N'] + '</span>'; buf += '<span class="detailcell"><label>Happiness</label>' + (typeof set.happiness === 'number' ? set.happiness : 255) + '</span>'; buf += '<span class="detailcell"><label>Shiny</label>' + (set.shiny ? 'Yes' : 'No') + '</span>'; } buf += '</button></div>'; buf += '</div><div class="setrow">'; if (this.curTeam.gen > 1) buf += '<div class="setcell setcell-item"><label>Item</label><input type="text" name="item" class="textbox chartinput" value="' + Tools.escapeHTML(set.item) + '" /></div>'; if (this.curTeam.gen > 2) buf += '<div class="setcell setcell-ability"><label>Ability</label><input type="text" name="ability" class="textbox chartinput" value="' + Tools.escapeHTML(set.ability) + '" /></div>'; buf += '</div></div>'; // moves if (!set.moves) set.moves = []; buf += '<div class="setcol setcol-moves"><div class="setcell"><label>Moves</label>'; buf += '<input type="text" name="move1" class="textbox chartinput" value="' + Tools.escapeHTML(set.moves[0]) + '" /></div>'; buf += '<div class="setcell"><input type="text" name="move2" class="textbox chartinput" value="' + Tools.escapeHTML(set.moves[1]) + '" /></div>'; buf += '<div class="setcell"><input type="text" name="move3" class="textbox chartinput" value="' + Tools.escapeHTML(set.moves[2]) + '" /></div>'; buf += '<div class="setcell"><input type="text" name="move4" class="textbox chartinput" value="' + Tools.escapeHTML(set.moves[3]) + '" /></div>'; buf += '</div>'; // stats buf += '<div class="setcol setcol-stats"><div class="setrow"><label>Stats</label><button class="textbox setstats" name="stats">'; buf += '<span class="statrow statrow-head"><label></label> <span class="statgraph"></span> <em>EV</em></span>'; var stats = {}; var defaultEV = (this.curTeam.gen > 2 ? 0 : 252); for (var j in BattleStatNames) { if (j === 'spd' && this.curTeam.gen === 1) continue; stats[j] = this.getStat(j, set); var ev = (set.evs[j] === undefined ? defaultEV : set.evs[j]); var evBuf = '<em>' + (ev === defaultEV ? '' : ev) + '</em>'; if (BattleNatures[set.nature] && BattleNatures[set.nature].plus === j) { evBuf += '<small>+</small>'; } else if (BattleNatures[set.nature] && BattleNatures[set.nature].minus === j) { evBuf += '<small>&minus;</small>'; } var width = stats[j] * 75 / 504; if (j == 'hp') width = stats[j] * 75 / 704; if (width > 75) width = 75; var color = Math.floor(stats[j] * 180 / 714); if (color > 360) color = 360; var statName = this.curTeam.gen === 1 && j === 'spa' ? 'Spc' : BattleStatNames[j]; buf += '<span class="statrow"><label>' + statName + '</label> <span class="statgraph"><span style="width:' + width + 'px;background:hsl(' + color + ',40%,75%);"></span></span> ' + evBuf + '</span>'; } buf += '</button></div></div>'; buf += '</div></li>'; return buf; }, saveImport: function () { Storage.activeSetList = this.curSetList = Storage.importTeam(this.$('.teamedit textarea').val()); this.back(); }, addPokemon: function () { if (!this.curTeam) return; var team = this.curSetList; if (!team.length || team[team.length - 1].species) { var newPokemon = { name: '', species: '', item: '', nature: '', evs: {}, ivs: {}, moves: [] }; team.push(newPokemon); } this.curSet = team[team.length - 1]; this.curSetLoc = team.length - 1; this.curChartName = ''; this.update(); this.$('input[name=pokemon]').select(); }, pastePokemon: function (i, btn) { if (!this.curTeam) return; var team = this.curSetList; if (team.length >= 6) return; if (!this.clipboardCount()) return; if (team.push($.extend(true, {}, this.clipboard[0])) >= 6) { $(btn).css('display', 'none'); } this.update(); this.save(); }, saveFlag: false, save: function () { this.saveFlag = true; if (this.curTeam) { Storage.saveTeam(this.curTeam); } else { Storage.saveTeams(); } }, validate: function () { var format = this.curTeam.format || 'anythinggoes'; if (!this.curSetList.length) { app.addPopupMessage("You need at least one Pokémon to validate."); return; } if (window.BattleFormats && BattleFormats[format] && BattleFormats[format].hasBattleFormat) { format = BattleFormats[format].battleFormat; } app.sendTeam(this.curTeam); app.send('/vtm ' + format); }, teamNameChange: function (e) { var name = ($.trim(e.currentTarget.value) || 'Untitled ' + (this.curTeamLoc + 1)); if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) { app.addPopupMessage("Names can't contain slashes, since they're used as a folder separator."); name = name.replace(/[\\\/]/g, ''); } if (name.indexOf('|') >= 0) { app.addPopupMessage("Names can't contain the character |, since they're used for storing teams."); name = name.replace(/\|/g, ''); } this.curTeam.name = name; e.currentTarget.value = name; this.save(); }, format: function (format, button) { if (!window.BattleFormats) { return; } var self = this; app.addPopup(FormatPopup, {format: format, sourceEl: button, selectType: 'teambuilder', onselect: function (newFormat) { self.changeFormat(newFormat); }}); }, changeFormat: function (format) { this.curTeam.format = format; this.curTeam.gen = this.getGen(this.curTeam.format); this.save(); if (this.curTeam.gen === 5 && !Tools.loadedSpriteData['bw']) Tools.loadSpriteData('bw'); this.update(); }, nicknameChange: function (e) { var i = +$(e.currentTarget).closest('li').attr('value'); var set = this.curSetList[i]; var name = $.trim(e.currentTarget.value).replace(/\|/g, ''); e.currentTarget.value = set.name = name; this.save(); }, // clipboard clipboard: [], clipboardCount: function () { return this.clipboard.length; }, clipboardVisible: function () { return !!this.clipboardCount(); }, clipboardHTML: function () { var buf = ''; buf += '<div class="teambuilder-clipboard-container" style="display: ' + (this.clipboardVisible() ? 'block' : 'none') + ';">'; buf += '<div class="teambuilder-clipboard-title">Clipboard:</div>'; buf += '<div class="teambuilder-clipboard-data" tabindex="-1">' + this.clipboardInnerHTML() + '</div>'; buf += '<div class="teambuilder-clipboard-buttons">'; if (this.curTeam && this.curSetList.length < 6) { buf += '<button name="pastePokemon" class="teambuilder-clipboard-button-left"><i class="fa fa-clipboard"></i> Paste!</button>'; } buf += '<button name="clipboardRemoveAll" class="teambuilder-clipboard-button-right"><i class="fa fa-trash"></i> Clear clipboard</button>'; buf += '</div>'; buf += '</div>'; return buf; }, clipboardInnerHTMLCache: '', clipboardInnerHTML: function () { if (this.clipboardInnerHTMLCache) { return this.clipboardInnerHTMLCache; } var buf = ''; for (var i = 0; i < this.clipboardCount(); i++) { var res = this.clipboard[i]; var pokemon = Tools.getTemplate(res.species); buf += '<div class="result" data-id="' + i + '">'; buf += '<div class="section"><span class="icon" style="' + Tools.getIcon(res.species) + '"></span>'; buf += '<span class="species">' + (pokemon.species === pokemon.baseSpecies ? pokemon.species : (pokemon.baseSpecies + '-<small>' + pokemon.species.substr(pokemon.baseSpecies.length + 1) + '</small>')) + '</span></div>'; buf += '<div class="section"><span class="ability-item">' + (res.ability || '<i>No ability</i>') + '<br />' + (res.item || '<i>No item</i>') + '</span></div>'; buf += '<div class="section no-border">'; for (var j = 0; j < 4; j++) { if (!(j & 1)) { buf += '<span class="moves">'; } buf += (res.moves[j] || '<i>No move</i>') + (!(j & 1) ? '<br />' : ''); if (j & 1) { buf += '</span>'; } } buf += '</div>'; buf += '</div>'; } this.clipboardInnerHTMLCache = buf; return buf; }, clipboardUpdate: function () { this.clipboardInnerHTMLCache = ''; $('.teambuilder-clipboard-data').html(this.clipboardInnerHTML()); }, clipboardExpanded: false, clipboardExpand: function () { var $clipboard = $('.teambuilder-clipboard-data'); $clipboard.animate({height: this.clipboardCount() * 28}, 500, function () { setTimeout(function () { $clipboard.focus(); }, 100); }); setTimeout(function () { this.clipboardExpanded = true; }.bind(this), 10); }, clipboardShrink: function () { var $clipboard = $('.teambuilder-clipboard-data'); $clipboard.animate({height: 26}, 500); setTimeout(function () { this.clipboardExpanded = false; }.bind(this), 10); }, clipboardResultSelect: function (e) { if (!this.clipboardExpanded) return; e.preventDefault(); e.stopPropagation(); var target = +($(e.target).closest('.result').data('id')); if (target === -1) { this.clipboardShrink(); this.clipboardRemoveAll(); return; } this.clipboard.unshift(this.clipboard.splice(target, 1)[0]); this.clipboardUpdate(); this.clipboardShrink(); }, clipboardAdd: function (set) { if (this.clipboard.unshift(set) > 6) { // we don't want the clipboard so big that it lags the teambuilder this.clipboard.pop(); } this.clipboardUpdate(); if (this.clipboardCount() === 1) { var $clipboard = $('.teambuilder-clipboard-container').css('opacity', 0); $clipboard.slideDown(250, function () { $clipboard.animate({opacity: 1}, 250); }); } }, clipboardRemoveAll: function () { this.clipboard = []; var self = this; var $clipboard = $('.teambuilder-clipboard-container'); $clipboard.animate({opacity: 0}, 250, function () { $clipboard.slideUp(250, function () { self.clipboardUpdate(); }); }); }, // copy/import/export/move/delete copySet: function (i, button) { i = +($(button).closest('li').attr('value')); this.clipboardAdd($.extend(true, {}, this.curSetList[i])); button.blur(); }, wasViewingPokemon: false, importSet: function (i, button) { i = +($(button).closest('li').attr('value')); this.wasViewingPokemon = true; if (!this.curSet) { this.wasViewingPokemon = false; this.selectPokemon(i); } this.$('li').find('input, button').prop('disabled', true); this.$chart.hide(); this.$('.teambuilder-pokemon-import') .show() .find('textarea') .val(Storage.exportTeam([this.curSet]).trim()) .focus() .select(); }, closePokemonImport: function (force) { if (!this.wasViewingPokemon) return this.back(); var $li = this.$('li'); var i = +($li.attr('value')); this.$('.teambuilder-pokemon-import').hide(); this.$chart.show(); if (force === true) return this.selectPokemon(i); $li.find('input, button').prop('disabled', false); }, savePokemonImport: function (i) { i = +(this.$('li').attr('value')); var curSet = Storage.importTeam(this.$('.pokemonedit').val())[0]; if (curSet) { this.curSet = curSet; this.curSetList[i] = curSet; } this.closePokemonImport(true); }, moveSet: function (i, button) { i = +($(button).closest('li').attr('value')); app.addPopup(MoveSetPopup, { i: i, team: this.curSetList }); }, deleteSet: function (i, button) { i = +($(button).closest('li').attr('value')); this.deletedSetLoc = i; this.deletedSet = this.curSetList.splice(i, 1)[0]; if (this.curSet) { this.addPokemon(); } else { this.update(); } this.save(); }, undeleteSet: function () { if (this.deletedSet) { var loc = this.deletedSetLoc; this.curSetList.splice(loc, 0, this.deletedSet); this.deletedSet = null; this.deletedSetLoc = -1; this.save(); if (this.curSet) { this.curSetLoc = loc; this.curSet = this.curSetList[loc]; this.curChartName = ''; this.update(); this.updateChart(); } else { this.update(); } } }, /********************************************************* * Set view *********************************************************/ updateSetView: function () { // pokemon var buf = '<div class="pad">'; buf += '<button name="back"><i class="fa fa-chevron-left"></i> Team</button></div>'; buf += '<div class="teambar">'; buf += this.renderTeambar(); buf += '</div>'; // pokemon buf += '<div class="teamchartbox individual">'; buf += '<ol class="teamchart">'; buf += this.renderSet(this.curSet, this.curSetLoc); buf += '</ol>'; buf += '</div>'; // results this.chartPrevSearch = '[init]'; buf += '<div class="teambuilder-results"></div>'; // import/export buf += '<div class="teambuilder-pokemon-import">'; buf += '<div class="pokemonedit-buttons"><button name="closePokemonImport"><i class="fa fa-chevron-left"></i> Back</button> <button name="savePokemonImport"><i class="fa fa-floppy-o"></i> Save</button></div>'; buf += '<textarea class="pokemonedit textbox" rows="14"></textarea>'; buf += '</div>'; this.$el.html('<div class="teamwrapper">' + buf + '</div>'); if ($(window).width() < 640) this.show(); this.$chart = this.$('.teambuilder-results'); this.search = new BattleSearch(this.$chart, this.$chart); var self = this; // fun fact: Backbone DOM events don't support scroll... // I guess scroll doesn't bubble like other events this.$chart.on('scroll', function () { if (self.curChartType in self.searchChartTypes) { self.search.updateScroll(); } }); }, updateSetTop: function () { this.$('.teambar').html(this.renderTeambar()); this.$('.teamchart').first().html(this.renderSet(this.curSet, this.curSetLoc)); }, renderTeambar: function () { var buf = ''; var isAdd = false; if (this.curSetList.length && !this.curSetList[this.curSetList.length - 1].species && this.curSetLoc !== this.curSetList.length - 1) { this.curSetList.splice(this.curSetList.length - 1, 1); } for (var i = 0; i < this.curSetList.length; i++) { var set = this.curSetList[i]; var pokemonicon = '<span class="picon pokemonicon-' + i + '" style="' + Tools.getPokemonIcon(set) + '"></span>'; if (!set.species) { buf += '<button disabled="disabled" class="addpokemon"><i class="fa fa-plus"></i></button> '; isAdd = true; } else if (i == this.curSetLoc) { buf += '<button disabled="disabled" class="pokemon">' + pokemonicon + Tools.escapeHTML(set.name || Tools.getTemplate(set.species).baseSpecies || '<i class="fa fa-plus"></i>') + '</button> '; } else { buf += '<button name="selectPokemon" value="' + i + '" class="pokemon">' + pokemonicon + Tools.escapeHTML(set.name || Tools.getTemplate(set.species).baseSpecies) + '</button> '; } } if (this.curSetList.length < 6 && !isAdd) { buf += '<button name="addPokemon"><i class="fa fa-plus"></i></button> '; } return buf; }, updatePokemonSprite: function () { var set = this.curSet; if (!set) return; this.$('.setchart').attr('style', Tools.getTeambuilderSprite(set, this.curTeam.gen)); this.$('.pokemonicon-' + this.curSetLoc).css('background', Tools.getPokemonIcon(set).substr(11)); var item = Tools.getItem(set.item); if (item.id) { this.$('.setcol-icon .itemicon').css('background', Tools.getItemIcon(item).substr(11)); } else { this.$('.setcol-icon .itemicon').css('background', 'none'); } this.updateStatGraph(); }, updateStatGraph: function () { var set = this.curSet; if (!set) return; var stats = {hp:'', atk:'', def:'', spa:'', spd:'', spe:''}; // stat cell var buf = '<span class="statrow statrow-head"><label></label> <span class="statgraph"></span> <em>EV</em></span>'; var defaultEV = (this.curTeam.gen > 2 ? 0 : 252); for (var stat in stats) { if (stat === 'spd' && this.curTeam.gen === 1) continue; stats[stat] = this.getStat(stat, set); var ev = (set.evs[stat] === undefined ? defaultEV : set.evs[stat]); var evBuf = '<em>' + (ev === defaultEV ? '' : ev) + '</em>'; if (BattleNatures[set.nature] && BattleNatures[set.nature].plus === stat) { evBuf += '<small>+</small>'; } else if (BattleNatures[set.nature] && BattleNatures[set.nature].minus === stat) { evBuf += '<small>&minus;</small>'; } var width = stats[stat] * 75 / 504; if (stat == 'hp') width = stats[stat] * 75 / 704; if (width > 75) width = 75; var color = Math.floor(stats[stat] * 180 / 714); if (color > 360) color = 360; buf += '<span class="statrow"><label>' + BattleStatNames[stat] + '</label> <span class="statgraph"><span style="width:' + width + 'px;background:hsl(' + color + ',40%,75%);"></span></span> ' + evBuf + '</span>'; } this.$('button[name=stats]').html(buf); if (this.curChartType !== 'stats') return; buf = '<div></div>'; for (var stat in stats) { if (stat === 'spd' && this.curTeam.gen === 1) continue; buf += '<div><b>' + stats[stat] + '</b></div>'; } this.$chart.find('.statscol').html(buf); buf = '<div></div>'; var totalev = 0; for (var stat in stats) { if (stat === 'spd' && this.curTeam.gen === 1) continue; var width = stats[stat] * 180 / 504; if (stat == 'hp') width = stats[stat] * 180 / 704; if (width > 179) width = 179; var color = Math.floor(stats[stat] * 180 / 714); if (color > 360) color = 360; buf += '<div><em><span style="width:' + Math.floor(width) + 'px;background:hsl(' + color + ',85%,45%);border-color:hsl(' + color + ',85%,35%)"></span></em></div>'; totalev += (set.evs[stat] || 0); } if (this.curTeam.gen > 2) buf += '<div><em>Remaining:</em></div>'; this.$chart.find('.graphcol').html(buf); if (this.curTeam.gen <= 2) return; var maxEv = 510; if (totalev <= maxEv) { this.$chart.find('.totalev').html('<em>' + (totalev > (maxEv - 2) ? 0 : (maxEv - 2) - totalev) + '</em>'); } else { this.$chart.find('.totalev').html('<b>' + (maxEv - totalev) + '</b>'); } this.$chart.find('select[name=nature]').val(set.nature || 'Serious'); }, curChartType: '', curChartName: '', searchChartTypes: { pokemon: 'pokemon', ability: 'abilities', move: 'moves', item: 'items' }, updateChart: function (pokemonChanged, wasIncomplete) { var type = this.curChartType; app.clearGlobalListeners(); if (type === 'stats') { this.search.qType = null; this.search.qName = null; this.updateStatForm(); return; } if (type === 'details') { this.search.qType = null; this.search.qName = null; this.updateDetailsForm(); return; } var $inputEl = this.$('input[name=' + this.curChartName + ']'); var q = $inputEl.val(); if (pokemonChanged || this.search.qName !== this.curChartName) { var cur = {}; cur[toId(q)] = 1; // make sure selected one is first if (type === 'move') { cur[toId(this.$('input[name=move1]').val())] = 1; cur[toId(this.$('input[name=move2]').val())] = 1; cur[toId(this.$('input[name=move3]').val())] = 1; cur[toId(this.$('input[name=move4]').val())] = 1; } if (type !== this.search.qType) { this.$chart.scrollTop(0); } this.search.$inputEl = $inputEl; this.search.setType(type, this.curTeam.format, this.curSet, cur); this.qInitial = q; this.search.qName = this.curChartName; if (wasIncomplete) { if (this.search.find(q)) { if (this.search.q) this.$chart.find('a').first().addClass('hover'); } } } else if (q !== this.qInitial) { this.qInitial = undefined; if (this.search.find(q)) { if (this.search.q) this.$chart.find('a').first().addClass('hover'); } } }, selectPokemon: function (i) { i = +i; var set = this.curSetList[i]; if (set) { this.curSet = set; this.curSetLoc = i; if (!this.curChartName) { this.curChartName = 'details'; this.curChartType = 'details'; } if (this.curChartType in this.searchChartTypes) { this.update(); this.updateChart(true); this.$('input[name=' + this.curChartName + ']').select(); } else { this.update(); this.updateChart(true); } } }, stats: function (i, button) { if (!this.curSet) this.selectPokemon($(button).closest('li').val()); this.curChartName = 'stats'; this.curChartType = 'stats'; this.updateChart(); }, details: function (i, button) { if (!this.curSet) this.selectPokemon($(button).closest('li').val()); this.curChartName = 'details'; this.curChartType = 'details'; this.updateChart(); }, /********************************************************* * Set stat form *********************************************************/ plus: '', minus: '', smogdexLink: function (template) { var template = Tools.getTemplate(template); var format = this.curTeam && this.curTeam.format; var smogdexid = toId(template.baseSpecies); if (template.isNonstandard) { return 'http://www.smogon.com/cap/pokemon/strategies/' + smogdexid; } if (template.speciesid === 'meowstic') { smogdexid = 'meowstic-m'; } else if (smogdexid === 'rotom' || smogdexid === 'deoxys' || smogdexid === 'kyurem' || smogdexid === 'giratina' || smogdexid === 'shaymin' || smogdexid === 'tornadus' || smogdexid === 'thundurus' || smogdexid === 'landorus' || smogdexid === 'pumpkaboo' || smogdexid === 'gourgeist' || smogdexid === 'arceus' || smogdexid === 'meowstic' || smogdexid === 'hoopa') { if (template.forme) smogdexid += '-' + toId(template.forme); } var generationNumber = 6; if (format.substr(0, 3) === 'gen') { var number = format.charAt(3); if ('1' <= number && number <= '5') { generationNumber = +number; format = format.substr(4); } } var generation = ['rb', 'gs', 'rs', 'dp', 'bw', 'xy'][generationNumber - 1]; if (format === 'battlespotdoubles') { smogdexid += '/vgc15'; } else if (format === 'doublesou' || format === 'doublesuu') { smogdexid += '/doubles'; } else if (format === 'ou' || format === 'uu' || format === 'ru' || format === 'nu' || format === 'pu' || format === 'lc') { smogdexid += '/' + format; } return 'http://smogon.com/dex/' + generation + '/pokemon/' + smogdexid + '/'; }, getBaseStats: function (template) { var baseStats = template.baseStats; var gen = this.curTeam.gen; if (gen < 6) { var overrideStats = BattleTeambuilderTable['gen' + gen].overrideStats[template.id]; if (overrideStats || gen === 1) { baseStats = { hp: template.baseStats.hp, atk: template.baseStats.atk, def: template.baseStats.def, spa: template.baseStats.spa, spd: template.baseStats.spd, spe: template.baseStats.spe }; } if (overrideStats) { if ('hp' in overrideStats) baseStats.hp = overrideStats.hp; if ('atk' in overrideStats) baseStats.atk = overrideStats.atk; if ('def' in overrideStats) baseStats.def = overrideStats.def; if ('spa' in overrideStats) baseStats.spa = overrideStats.spa; if ('spd' in overrideStats) baseStats.spd = overrideStats.spd; if ('spe' in overrideStats) baseStats.spe = overrideStats.spe; } if (gen === 1) baseStats.spd = 0; } return baseStats; }, updateStatForm: function (setGuessed) { var buf = ''; var set = this.curSet; var template = Tools.getTemplate(this.curSet.species); var baseStats = this.getBaseStats(template); buf += '<div class="resultheader"><h3>EVs</h3></div>'; buf += '<div class="statform">'; var role = this.guessRole(); var guessedEVs = {}; var guessedPlus = ''; var guessedMinus = ''; buf += '<p class="suggested"><small>Suggested spread:'; if (role === '?') { buf += ' (Please choose 4 moves to get a suggested spread) (<a target="_blank" href="' + this.smogdexLink(template) + '">Smogon&nbsp;analysis</a>)</small></p>'; } else { guessedEVs = this.guessEVs(role); guessedPlus = guessedEVs.plusStat; delete guessedEVs.plusStat; guessedMinus = guessedEVs.minusStat; delete guessedEVs.minusStat; buf += ' </small><button name="setStatFormGuesses">' + role + ': '; for (var i in guessedEVs) { if (guessedEVs[i]) { var statName = this.curTeam.gen === 1 && i === 'spa' ? 'Spc' : BattleStatNames[i]; buf += '' + guessedEVs[i] + ' ' + statName + ' / '; } } if (guessedPlus && guessedMinus) buf += ' (+' + BattleStatNames[guessedPlus] + ', -' + BattleStatNames[guessedMinus] + ')'; else buf = buf.slice(0, -3); buf += '</button><small> (<a target="_blank" href="' + this.smogdexLink(template) + '">Smogon&nbsp;analysis</a>)</small></p>'; //buf += ' <small>(' + role + ' | bulk: phys ' + Math.round(this.moveCount.physicalBulk/1000) + ' + spec ' + Math.round(this.moveCount.specialBulk/1000) + ' = ' + Math.round(this.moveCount.bulk/1000) + ')</small>'; } if (setGuessed) { set.evs = guessedEVs; this.plus = guessedPlus; this.minus = guessedMinus; this.updateNature(); this.save(); this.updateStatGraph(); this.natureChange(); return; } var stats = {hp:'', atk:'', def:'', spa:'', spd:'', spe:''}; if (this.curTeam.gen === 1) delete stats.spd; if (!set) return; var nature = BattleNatures[set.nature || 'Serious']; if (!nature) nature = {}; // label column buf += '<div class="col labelcol"><div></div>'; buf += '<div><label>HP</label></div><div><label>Attack</label></div><div><label>Defense</label></div><div>'; if (this.curTeam.gen === 1) { buf += '<label>Special</label></div>'; } else { buf += '<label>Sp. Atk.</label></div><div><label>Sp. Def.</label></div>'; } buf += '<div><label>Speed</label></div></div>'; buf += '<div class="col basestatscol"><div><em>Base</em></div>'; for (var i in stats) { buf += '<div><b>' + baseStats[i] + '</b></div>'; } buf += '</div>'; buf += '<div class="col graphcol"><div></div>'; for (var i in stats) { stats[i] = this.getStat(i); var width = stats[i] * 180 / 504; if (i == 'hp') width = Math.floor(stats[i] * 180 / 704); if (width > 179) width = 179; var color = Math.floor(stats[i] * 180 / 714); if (color > 360) color = 360; buf += '<div><em><span style="width:' + Math.floor(width) + 'px;background:hsl(' + color + ',85%,45%);border-color:hsl(' + color + ',85%,35%)"></span></em></div>'; } if (this.curTeam.gen > 2) buf += '<div><em>Remaining:</em></div>'; buf += '</div>'; buf += '<div class="col evcol"><div><strong>EVs</strong></div>'; var totalev = 0; this.plus = ''; this.minus = ''; for (var i in stats) { var width = stats[i] * 200 / 504; if (i == 'hp') width = stats[i] * 200 / 704; if (width > 200) width = 200; var val; if (this.curTeam.gen > 2) { val = '' + (set.evs[i] || ''); } else { val = (set.evs[i] === undefined ? '252' : '' + set.evs[i]); } if (nature.plus === i) { val += '+'; this.plus = i; } if (nature.minus === i) { val += '-'; this.minus = i; } buf += '<div><input type="text" name="stat-' + i + '" value="' + val + '" class="textbox inputform numform" /></div>'; totalev += (set.evs[i] || 0); } if (this.curTeam.gen > 2) { var maxEv = 510; if (totalev <= maxEv) { buf += '<div class="totalev"><em>' + (totalev > (maxEv - 2) ? 0 : (maxEv - 2) - totalev) + '</em></div>'; } else { buf += '<div class="totalev"><b>' + (maxEv - totalev) + '</b></div>'; } } buf += '</div>'; buf += '<div class="col evslidercol"><div></div>'; for (var i in stats) { if (i === 'spd' && this.curTeam.gen === 1) continue; buf += '<div><input type="slider" name="evslider-' + i + '" value="' + Tools.escapeHTML(set.evs[i] === undefined ? (this.curTeam.gen > 2 ? '0' : '252') : '' + set.evs[i]) + '" min="0" max="252" step="4" class="evslider" /></div>'; } buf += '</div>'; if (this.curTeam.gen > 2) { buf += '<div class="col ivcol"><div><strong>IVs</strong></div>'; if (!set.ivs) set.ivs = {}; for (var i in stats) { if (set.ivs[i] === undefined || isNaN(set.ivs[i])) set.ivs[i] = 31; var val = '' + (set.ivs[i]); buf += '<div><input type="number" name="iv-' + i + '" value="' + Tools.escapeHTML(val) + '" class="textbox inputform numform" min="0" max="31" step="1" /></div>'; } var hpType = ''; if (set.moves) { for (var i = 0; i < set.moves.length; i++) { var moveid = toId(set.moves[i]); if (moveid.slice(0, 11) === 'hiddenpower') { hpType = moveid.slice(11); } } } if (hpType) { var hpIVs; switch (hpType) { case 'dark': hpIVs = ['111111']; break; case 'dragon': hpIVs = ['011111', '101111', '110111']; break; case 'ice': hpIVs = ['010111', '100111', '111110']; break; case 'psychic': hpIVs = ['011110', '101110', '110110']; break; case 'electric': hpIVs = ['010110', '100110', '111011']; break; case 'grass': hpIVs = ['011011', '101011', '110011']; break; case 'water': hpIVs = ['100011', '111010']; break; case 'fire': hpIVs = ['101010', '110010']; break; case 'steel': hpIVs = ['100010', '111101']; break; case 'ghost': hpIVs = ['101101', '110101']; break; case 'bug': hpIVs = ['100101', '111100', '101100']; break; case 'rock': hpIVs = ['001100', '110100', '100100']; break; case 'ground': hpIVs = ['000100', '111001', '101001']; break; case 'poison': hpIVs = ['001001', '110001', '100001']; break; case 'flying': hpIVs = ['000001', '111000', '101000']; break; case 'fighting': hpIVs = ['001000', '110000', '100000']; break; } buf += '<div style="margin-left:-80px;text-align:right"><select name="ivspread">'; buf += '<option value="" selected>HP ' + hpType.charAt(0).toUpperCase() + hpType.slice(1) + ' IVs</option>'; var minStat = this.curTeam.gen >= 6 ? 0 : 2; buf += '<optgroup label="min Atk">'; for (var i = 0; i < hpIVs.length; i++) { var spread = ''; for (var j = 0; j < 6; j++) { if (j) spread += '/'; spread += (j === 1 ? minStat : 30) + parseInt(hpIVs[i].charAt(j), 10); } buf += '<option value="' + spread + '">' + spread + '</option>'; } buf += '</optgroup>'; buf += '<optgroup label="min Atk, min Spe">'; for (var i = 0; i < hpIVs.length; i++) { var spread = ''; for (var j = 0; j < 6; j++) { if (j) spread += '/'; spread += (j === 5 || j === 1 ? minStat : 30) + parseInt(hpIVs[i].charAt(j), 10); } buf += '<option value="' + spread + '">' + spread + '</option>'; } buf += '</optgroup>'; buf += '<optgroup label="max all">'; for (var i = 0; i < hpIVs.length; i++) { var spread = ''; for (var j = 0; j < 6; j++) { if (j) spread += '/'; spread += 30 + parseInt(hpIVs[i].charAt(j), 10); } buf += '<option value="' + spread + '">' + spread + '</option>'; } buf += '</optgroup>'; buf += '<optgroup label="min Spe">'; for (var i = 0; i < hpIVs.length; i++) { var spread = ''; for (var j = 0; j < 6; j++) { if (j) spread += '/'; spread += (j === 5 ? minStat : 30) + parseInt(hpIVs[i].charAt(j), 10); } buf += '<option value="' + spread + '">' + spread + '</option>'; } buf += '</optgroup>'; buf += '</select></div>'; } buf += '</div>'; } else { buf += '<div class="col ivcol"><div><strong>DVs</strong></div>'; if (!set.ivs) set.ivs = {}; for (var i in stats) { if (set.ivs[i] === undefined || isNaN(set.ivs[i])) set.ivs[i] = 31; var val = '' + Math.floor(set.ivs[i] / 2); buf += '<div><input type="number" name="iv-' + i + '" value="' + Tools.escapeHTML(val) + '" class="textbox inputform numform" min="0" max="15" step="1" /></div>'; } buf += '</div>'; } buf += '<div class="col statscol"><div></div>'; for (var i in stats) { buf += '<div><b>' + stats[i] + '</b></div>'; } buf += '</div>'; if (this.curTeam.gen > 2) { buf += '<p style="clear:both">Nature: <select name="nature">'; for (var i in BattleNatures) { var curNature = BattleNatures[i]; buf += '<option value="' + i + '"' + (curNature === nature ? 'selected="selected"' : '') + '>' + i; if (curNature.plus) { buf += ' (+' + BattleStatNames[curNature.plus] + ', -' + BattleStatNames[curNature.minus] + ')'; } buf += '</option>'; } buf += '</select></p>'; buf += '<p><em>Protip:</em> You can also set natures by typing "+" and "-" next to a stat.</p>'; } buf += '</div>'; this.$chart.html(buf); var self = this; this.suppressSliderCallback = true; app.clearGlobalListeners(); this.$chart.find('.evslider').slider({ from: 0, to: 252, step: 4, skin: 'round_plastic', onstatechange: function (val) { if (!self.suppressSliderCallback) self.statSlide(val, this); }, callback: function () { self.save(); } }); this.suppressSliderCallback = false; }, setStatFormGuesses: function () { this.updateStatForm(true); }, setSlider: function (stat, val) { this.suppressSliderCallback = true; this.$chart.find('input[name=evslider-' + stat + ']').slider('value', val || 0); this.suppressSliderCallback = false; }, updateNature: function () { var set = this.curSet; if (!set) return; if (this.plus === '' || this.minus === '') { set.nature = 'Serious'; } else { for (var i in BattleNatures) { if (BattleNatures[i].plus === this.plus && BattleNatures[i].minus === this.minus) { set.nature = i; break; } } } }, statChange: function (e) { var inputName = ''; inputName = e.currentTarget.name; var val = Math.abs(parseInt(e.currentTarget.value, 10)); var set = this.curSet; if (!set) return; if (inputName.substr(0, 5) === 'stat-') { // EV // Handle + and - var stat = inputName.substr(5); var lastchar = e.currentTarget.value.charAt(e.target.value.length - 1); var firstchar = e.currentTarget.value.charAt(0); var natureChange = true; if ((lastchar === '+' || firstchar === '+') && stat !== 'hp') { if (this.plus && this.plus !== stat) this.$chart.find('input[name=stat-' + this.plus + ']').val(set.evs[this.plus] || ''); this.plus = stat; } else if ((lastchar === '-' || lastchar === "\u2212" || firstchar === '-' || firstchar === "\u2212") && stat !== 'hp') { if (this.minus && this.minus !== stat) this.$chart.find('input[name=stat-' + this.minus + ']').val(set.evs[this.minus] || ''); this.minus = stat; } else if (this.plus === stat) { this.plus = ''; } else if (this.minus === stat) { this.minus = ''; } else { natureChange = false; } if (natureChange) { this.updateNature(); } // cap if (val > 252) val = 252; if (val < 0 || isNaN(val)) val = 0; if (set.evs[stat] !== val || natureChange) { set.evs[stat] = val; if (this.curTeam.gen <= 2) { if (set.evs['hp'] === undefined) set.evs['hp'] = 252; if (set.evs['atk'] === undefined) set.evs['atk'] = 252; if (set.evs['def'] === undefined) set.evs['def'] = 252; if (set.evs['spa'] === undefined) set.evs['spa'] = 252; if (set.evs['spd'] === undefined) set.evs['spd'] = 252; if (set.evs['spe'] === undefined) set.evs['spe'] = 252; } this.setSlider(stat, val); this.updateStatGraph(); } } else { // IV var stat = inputName.substr(3); if (this.curTeam.gen <= 2) { val *= 2; if (val === 30) val = 31; } if (val > 31 || isNaN(val)) val = 31; if (val < 0) val = 0; if (!set.ivs) set.ivs = {}; if (set.ivs[stat] !== val) { set.ivs[stat] = val; this.updateStatGraph(); } } this.save(); }, statSlide: function (val, slider) { var stat = slider.inputNode[0].name.substr(9); var set = this.curSet; if (!set) return; val = +val; var originalVal = val; var result = this.getStat(stat, set, val); while (val && this.getStat(stat, set, val - 4) == result) val -= 4; if (!this.ignoreEVLimits && set.evs) { var total = 0; for (var i in set.evs) { total += (i === stat ? val : set.evs[i]); } if (total > 508 && val - total + 508 >= 0) { // don't allow dragging beyond 508 EVs val = val - total + 508; // make sure val is a legal value val = +val; if (!val || val <= 0) val = 0; if (val > 252) val = 252; } } // Don't try this at home. // I am a trained professional. if (val !== originalVal) slider.o.pointers[0].set(val); if (!set.evs) set.evs = {}; if (this.curTeam.gen <= 2) { if (set.evs['hp'] === undefined) set.evs['hp'] = 252; if (set.evs['atk'] === undefined) set.evs['atk'] = 252; if (set.evs['def'] === undefined) set.evs['def'] = 252; if (set.evs['spa'] === undefined) set.evs['spa'] = 252; if (set.evs['spd'] === undefined) set.evs['spd'] = 252; if (set.evs['spe'] === undefined) set.evs['spe'] = 252; } set.evs[stat] = val; val = '' + (val || '') + (this.plus === stat ? '+' : '') + (this.minus === stat ? '-' : ''); this.$('input[name=stat-' + stat + ']').val(val); this.updateStatGraph(); }, natureChange: function (e) { var set = this.curSet; if (!set) return; if (e) { set.nature = e.currentTarget.value; } this.plus = ''; this.minus = ''; var nature = BattleNatures[set.nature || 'Serious']; for (var i in BattleStatNames) { var val = '' + (set.evs[i] || ''); if (nature.plus === i) { this.plus = i; val += '+'; } if (nature.minus === i) { this.minus = i; val += '-'; } this.$chart.find('input[name=stat-' + i + ']').val(val); if (!e) this.setSlider(i, set.evs[i]); } this.save(); this.updateStatGraph(); }, ivSpreadChange: function (e) { var set = this.curSet; if (!set) return; var spread = e.currentTarget.value.split('/'); if (!set.ivs) set.ivs = {}; if (spread.length !== 6) return; var stats = ['hp', 'atk', 'def', 'spa', 'spd', 'spe']; for (var i = 0; i < 6; i++) { this.$chart.find('input[name=iv-' + stats[i] + ']').val(spread[i]); set.ivs[stats[i]] = parseInt(spread[i], 10); } $(e.currentTarget).val(''); this.save(); this.updateStatGraph(); }, /********************************************************* * Set details form *********************************************************/ updateDetailsForm: function () { var buf = ''; var set = this.curSet; var template = Tools.getTemplate(set.species); if (!set) return; buf += '<div class="resultheader"><h3>Details</h3></div>'; buf += '<form class="detailsform">'; buf += '<div class="formrow"><label class="formlabel">Level:</label><div><input type="number" min="1" max="100" step="1" name="level" value="' + Tools.escapeHTML(set.level || 100) + '" class="textbox inputform numform" /></div></div>'; if (this.curTeam.gen > 1) { buf += '<div class="formrow"><label class="formlabel">Gender:</label><div>'; if (template.gender && this.curTeam.format !== 'balancedhackmons') { var genderTable = {'M': "Male", 'F': "Female", 'N': "Genderless"}; buf += genderTable[template.gender]; } else { buf += '<label><input type="radio" name="gender" value="M"' + (set.gender === 'M' ? ' checked' : '') + ' /> Male</label> '; buf += '<label><input type="radio" name="gender" value="F"' + (set.gender === 'F' ? ' checked' : '') + ' /> Female</label> '; if (this.curTeam.format !== 'balancedhackmons') { buf += '<label><input type="radio" name="gender" value="N"' + (!set.gender ? ' checked' : '') + ' /> Random</label>'; } else { buf += '<label><input type="radio" name="gender" value="N"' + (set.gender === 'N' ? ' checked' : '') + ' /> Genderless</label>'; } } buf += '</div></div>'; buf += '<div class="formrow"><label class="formlabel">Happiness:</label><div><input type="number" min="0" max="255" step="1" name="happiness" value="' + (typeof set.happiness === 'number' ? set.happiness : 255) + '" class="textbox inputform numform" /></div></div>'; buf += '<div class="formrow"><label class="formlabel">Shiny:</label><div>'; buf += '<label><input type="radio" name="shiny" value="yes"' + (set.shiny ? ' checked' : '') + ' /> Yes</label> '; buf += '<label><input type="radio" name="shiny" value="no"' + (!set.shiny ? ' checked' : '') + ' /> No</label>'; buf += '</div></div>'; } buf += '</form>'; this.$chart.html(buf); }, detailsChange: function () { var set = this.curSet; if (!set) return; // level var level = parseInt(this.$chart.find('input[name=level]').val(), 10); if (!level || level > 100 || level < 1) level = 100; if (level !== 100 || set.level) set.level = level; // happiness var happiness = parseInt(this.$chart.find('input[name=happiness]').val(), 10); if (happiness > 255) happiness = 255; if (happiness < 0) happiness = 255; set.happiness = happiness; if (set.happiness === 255) delete set.happiness; // shiny var shiny = (this.$chart.find('input[name=shiny]:checked').val() === 'yes'); if (shiny) { set.shiny = true; } else { delete set.shiny; } var gender = this.$chart.find('input[name=gender]:checked').val(); if (gender === 'M' || gender === 'F') { set.gender = gender; } else { delete set.gender; } // update details cell var buf = ''; var GenderChart = { 'M': 'Male', 'F': 'Female', 'N': '&mdash;' }; buf += '<span class="detailcell detailcell-first"><label>Level</label>' + (set.level || 100) + '</span>'; if (this.curTeam.gen > 1) { buf += '<span class="detailcell"><label>Gender</label>' + GenderChart[set.gender || 'N'] + '</span>'; buf += '<span class="detailcell"><label>Happiness</label>' + (typeof set.happiness === 'number' ? set.happiness : 255) + '</span>'; buf += '<span class="detailcell"><label>Shiny</label>' + (set.shiny ? 'Yes' : 'No') + '</span>'; } this.$('button[name=details]').html(buf); this.save(); this.updatePokemonSprite(); }, /********************************************************* * Set charts *********************************************************/ chartTypes: { pokemon: 'pokemon', item: 'item', ability: 'ability', move1: 'move', move2: 'move', move3: 'move', move4: 'move', stats: 'stats', details: 'details' }, chartClick: function (e) { if (this.search.addFilter(e.currentTarget)) { this.$('input[name=' + this.curChartName + ']').val('').select(); this.search.find(''); return; } var val = $(e.currentTarget).data('entry').split(':')[1]; if (this.curChartType === 'move' && e.currentTarget.className === 'cur') { // clicked a move, remove it if we already have it var $emptyEl; var moves = []; for (var i = 1; i <= 4; i++) { var $inputEl = this.$('input[name=move' + i + ']'); var curVal = $inputEl.val(); if (curVal === val) { this.unChooseMove(curVal); $inputEl.val(''); delete this.search.cur[toId(val)]; } else if (curVal) { moves.push(curVal); } } if (moves.length < 4) { this.$('input[name=move1]').val(moves[0] || ''); this.$('input[name=move2]').val(moves[1] || ''); this.$('input[name=move3]').val(moves[2] || ''); this.$('input[name=move4]').val(moves[3] || ''); this.$('input[name=move' + (1 + moves.length) + ']').focus(); return; } } this.chartSet(val, true); }, chartKeydown: function (e) { var modifier = (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey || e.cmdKey); if (e.keyCode === 13 || (e.keyCode === 9 && !modifier)) { // enter/tab if (!(this.curChartType in this.searchChartTypes)) return; var $firstResult = this.$chart.find('a.hover'); e.stopPropagation(); e.preventDefault(); if (!$firstResult.length) { this.chartChange(e, true); return; } if (this.search.addFilter($firstResult[0])) { $(e.currentTarget).val('').select(); this.search.find(''); return; } var val = $firstResult.data('entry').split(':')[1]; this.chartSet(val, true); return; } else if (e.keyCode === 38) { // up e.preventDefault(); e.stopPropagation(); var $active = this.$chart.find('a.hover'); if (!$active.length) return this.$chart.find('a').first().addClass('hover'); var $li = $active.parent().prev(); while ($li[0] && $li[0].firstChild.tagName !== 'A') $li = $li.prev(); if ($li[0] && $li.children()[0]) { $active.removeClass('hover'); $active = $li.children(); $active.addClass('hover'); } } else if (e.keyCode === 40) { // down e.preventDefault(); e.stopPropagation(); var $active = this.$chart.find('a.hover'); if (!$active.length) return this.$chart.find('a').first().addClass('hover'); var $li = $active.parent().next(); while ($li[0] && $li[0].firstChild.tagName !== 'A') $li = $li.next(); if ($li[0] && $li.children()[0]) { $active.removeClass('hover'); $active = $li.children(); $active.addClass('hover'); } } else if (e.keyCode === 27 || e.keyCode === 8) { // esc, backspace if (!e.currentTarget.value && this.search.removeFilter()) { this.search.find(''); return; } } else if (e.keyCode === 188) { var $firstResult = this.$chart.find('a').first(); if (!this.search.q) return; if (this.search.addFilter($firstResult[0])) { e.preventDefault(); e.stopPropagation(); $(e.currentTarget).val('').select(); this.search.find(''); return; } } }, chartKeyup: function () { this.updateChart(); }, chartFocus: function (e) { var $target = $(e.currentTarget); var name = e.currentTarget.name; var type = this.chartTypes[name]; var wasIncomplete = false; if ($target.hasClass('incomplete')) { wasIncomplete = true; $target.removeClass('incomplete'); } if (this.curChartName === name) return; if (!this.curSet) { var i = +$target.closest('li').prop('value'); this.curSet = this.curSetList[i]; this.curSetLoc = i; this.update(); if (type === 'stats' || type === 'details') { this.$('button[name=' + name + ']').click(); } else { this.$('input[name=' + name + ']').select(); } return; } this.curChartName = name; this.curChartType = type; this.updateChart(false, wasIncomplete); }, chartChange: function (e, selectNext) { var name = e.currentTarget.name; if (this.curChartName !== name) return; var id = toId(e.currentTarget.value); var val = ''; switch (name) { case 'pokemon': val = (id in BattlePokedex ? BattlePokedex[id].species : ''); break; case 'ability': val = (id in BattleAbilities ? BattleAbilities[id].name : ''); break; case 'item': val = (id in BattleItems ? BattleItems[id].name : ''); break; case 'move1': case 'move2': case 'move3': case 'move4': val = (id in BattleMovedex ? BattleMovedex[id].name : ''); break; } if (!val) { if (name === 'pokemon' || name === 'ability' || id) { $(e.currentTarget).addClass('incomplete'); return; } } this.chartSet(val, selectNext); }, chartSet: function (val, selectNext) { var inputName = this.curChartName; var id = toId(val); this.$('input[name=' + inputName + ']').val(val).removeClass('incomplete'); switch (inputName) { case 'pokemon': this.setPokemon(val, selectNext); break; case 'item': this.curSet.item = val; this.updatePokemonSprite(); if (selectNext) this.$(this.$('input[name=ability]').length ? 'input[name=ability]' : 'input[name=move1]').select(); break; case 'ability': this.curSet.ability = val; if (selectNext) this.$('input[name=move1]').select(); break; case 'move1': this.unChooseMove(this.curSet.moves[0]); this.curSet.moves[0] = val; this.chooseMove(val); if (selectNext) this.$('input[name=move2]').select(); break; case 'move2': if (!this.curSet.moves[0]) this.curSet.moves[0] = ''; this.unChooseMove(this.curSet.moves[1]); this.curSet.moves[1] = val; this.chooseMove(val); if (selectNext) this.$('input[name=move3]').select(); break; case 'move3': if (!this.curSet.moves[0]) this.curSet.moves[0] = ''; if (!this.curSet.moves[1]) this.curSet.moves[1] = ''; this.unChooseMove(this.curSet.moves[2]); this.curSet.moves[2] = val; this.chooseMove(val); if (selectNext) this.$('input[name=move4]').select(); break; case 'move4': if (!this.curSet.moves[0]) this.curSet.moves[0] = ''; if (!this.curSet.moves[1]) this.curSet.moves[1] = ''; if (!this.curSet.moves[2]) this.curSet.moves[2] = ''; this.unChooseMove(this.curSet.moves[3]); this.curSet.moves[3] = val; this.chooseMove(val); if (selectNext) { this.stats(); this.$('button.setstats').focus(); } break; } this.save(); }, unChooseMove: function (move) { var set = this.curSet; if (!move || !set) return; if (move.substr(0, 13) === 'Hidden Power ') { if (set.ivs) { for (var i in set.ivs) { if (set.ivs[i] === 30) delete set.ivs[i]; } } } }, chooseMove: function (move) { var set = this.curSet; if (!set) return; if (move.substr(0, 13) === 'Hidden Power ') { set.ivs = {}; if (this.curTeam.gen > 2) { for (var i in exports.BattleTypeChart[move.substr(13)].HPivs) { set.ivs[i] = exports.BattleTypeChart[move.substr(13)].HPivs[i]; } } else { for (var i in exports.BattleTypeChart[move.substr(13)].HPdvs) { set.ivs[i] = exports.BattleTypeChart[move.substr(13)].HPdvs[i] * 2; } } var moves = this.curSet.moves; for (var i = 0; i < moves.length; ++i) { if (moves[i] === 'Gyro Ball' || moves[i] === 'Trick Room') set.ivs['spe'] = set.ivs['spe'] % 4; } } else if (move === 'Gyro Ball' || move === 'Trick Room') { var hasHiddenPower = false; var moves = this.curSet.moves; for (var i = 0; i < moves.length; ++i) { if (moves[i].substr(0, 13) === 'Hidden Power ') hasHiddenPower = true; } set.ivs['spe'] = hasHiddenPower ? set.ivs['spe'] % 4 : 0; } else if (move === 'Return') { this.curSet.happiness = 255; } else if (move === 'Frustration') { this.curSet.happiness = 0; } }, setPokemon: function (val, selectNext) { var set = this.curSet; var template = Tools.getTemplate(val); var newPokemon = !set.species; if (!template.exists || set.species === template.species) { if (selectNext) this.$('input[name=item]').select(); return; } set.name = ""; set.species = val; if (set.level) delete set.level; if (this.curTeam && this.curTeam.format) { if (this.curTeam.format.substr(0, 10) === 'battlespot' || this.curTeam.format.substr(0, 3) === 'vgc') set.level = 50; if (this.curTeam.format.substr(0, 2) === 'lc' || this.curTeam.format === 'gen5lc' || this.curTeam.format === 'gen4lc') set.level = 5; } if (set.gender) delete set.gender; if (template.gender && template.gender !== 'N') set.gender = template.gender; if (set.happiness) delete set.happiness; if (set.shiny) delete set.shiny; if (this.curTeam.format !== 'balancedhackmons') { set.item = (template.requiredItem || ''); } else { set.item = ''; } set.ability = template.abilities['0']; set.moves = []; set.evs = {}; set.ivs = {}; set.nature = ''; this.updateSetTop(); if (selectNext) this.$(set.item || !this.$('input[name=item]').length ? (this.$('input[name=ability]').length ? 'input[name=ability]' : 'input[name=move1]') : 'input[name=item]').select(); }, /********************************************************* * Utility functions *********************************************************/ // EV guesser guessRole: function () { var set = this.curSet; if (!set) return '?'; if (!set.moves) return '?'; var moveCount = { 'Physical': 0, 'Special': 0, 'PhysicalOffense': 0, 'SpecialOffense': 0, 'PhysicalSetup': 0, 'SpecialSetup': 0, 'Support': 0, 'Setup': 0, 'Restoration': 0, 'Offense': 0, 'Stall': 0, 'SpecialStall': 0, 'PhysicalStall': 0, 'Ultrafast': 0 }; var hasMove = {}; var template = Tools.getTemplate(set.species || set.name); var stats = this.getBaseStats(template); var itemid = toId(set.item); var abilityid = toId(set.ability); if (set.moves.length < 4 && template.id !== 'unown' && template.id !== 'ditto' && this.curTeam.gen > 2) return '?'; for (var i = 0, len = set.moves.length; i < len; i++) { var move = Tools.getMove(set.moves[i]); hasMove[move.id] = 1; if (move.category === 'Status') { if (move.id === 'batonpass' || move.id === 'healingwish' || move.id === 'lunardance') { moveCount['Support']++; } else if (move.id === 'naturepower') { moveCount['Special']++; } else if (move.id === 'protect' || move.id === 'detect' || move.id === 'spikyshield' || move.id === 'kingsshield') { moveCount['Stall']++; } else if (move.id === 'wish') { moveCount['Restoration']++; moveCount['Stall']++; moveCount['Support']++; } else if (move.heal) { moveCount['Restoration']++; moveCount['Stall']++; } else if (move.target === 'self') { if (move.id === 'agility' || move.id === 'rockpolish' || move.id === 'shellsmash' || move.id === 'growth' || move.id === 'workup') { moveCount['PhysicalSetup']++; moveCount['SpecialSetup']++; } else if (move.id === 'dragondance' || move.id === 'swordsdance' || move.id === 'coil' || move.id === 'bulkup' || move.id === 'curse' || move.id === 'bellydrum') { moveCount['PhysicalSetup']++; } else if (move.id === 'nastyplot' || move.id === 'tailglow' || move.id === 'quiverdance' || move.id === 'calmmind' || move.id === 'geomancy') { moveCount['SpecialSetup']++; } if (move.id === 'substitute') moveCount['Stall']++; moveCount['Setup']++; } else { if (move.id === 'toxic' || move.id === 'leechseed' || move.id === 'willowisp') moveCount['Stall']++; moveCount['Support']++; } } else if (move.id === 'counter' || move.id === 'endeavor' || move.id === 'metalburst' || move.id === 'mirrorcoat' || move.id === 'rapidspin') { moveCount['Support']++; } else if (move.id === 'nightshade' || move.id === 'seismictoss' || move.id === 'superfang' || move.id === 'foulplay' || move.id === 'finalgambit') { moveCount['Offense']++; } else if (move.id === 'fellstinger') { moveCount['PhysicalSetup']++; moveCount['Setup']++; } else { moveCount[move.category]++; moveCount['Offense']++; if (move.id === 'knockoff') moveCount['Support']++; if (move.id === 'scald' || move.id === 'voltswitch' || move.id === 'uturn') moveCount[move.category] -= 0.2; } } if (hasMove['batonpass']) moveCount['Support'] += moveCount['Setup']; moveCount['PhysicalAttack'] = moveCount['Physical']; moveCount['Physical'] += moveCount['PhysicalSetup']; moveCount['SpecialAttack'] = moveCount['Special']; moveCount['Special'] += moveCount['SpecialSetup']; if (hasMove['dragondance'] || hasMove['quiverdance']) moveCount['Ultrafast'] = 1; var isFast = (stats.spe > 95); var physicalBulk = (stats.hp + 75) * (stats.def + 87); var specialBulk = (stats.hp + 75) * (stats.spd + 87); if (hasMove['willowisp'] || hasMove['acidarmor'] || hasMove['irondefense'] || hasMove['cottonguard']) { physicalBulk *= 1.6; moveCount['PhysicalStall']++; } else if (hasMove['scald'] || hasMove['bulkup'] || hasMove['coil'] || hasMove['cosmicpower']) { physicalBulk *= 1.3; if (hasMove['scald']) { // partial stall goes in reverse moveCount['SpecialStall']++; } else { moveCount['PhysicalStall']++; } } if (abilityid === 'flamebody') physicalBulk *= 1.1; if (hasMove['calmmind'] || hasMove['quiverdance'] || hasMove['geomancy']) { specialBulk *= 1.3; moveCount['SpecialStall']++; } if (template.id === 'tyranitar') specialBulk *= 1.5; if (hasMove['bellydrum']) { physicalBulk *= 0.6; specialBulk *= 0.6; } if (moveCount['Restoration']) { physicalBulk *= 1.5; specialBulk *= 1.5; } else if (hasMove['painsplit'] && hasMove['substitute']) { // SubSplit isn't generally a stall set moveCount['Stall']--; } else if (hasMove['painsplit'] || hasMove['rest']) { physicalBulk *= 1.4; specialBulk *= 1.4; } if ((hasMove['bodyslam'] || hasMove['thunder']) && abilityid === 'serenegrace' || hasMove['thunderwave']) { physicalBulk *= 1.1; specialBulk *= 1.1; } if ((hasMove['ironhead'] || hasMove['airslash']) && abilityid === 'serenegrace') { physicalBulk *= 1.1; specialBulk *= 1.1; } if (hasMove['gigadrain'] || hasMove['drainpunch'] || hasMove['hornleech']) { physicalBulk *= 1.15; specialBulk *= 1.15; } if (itemid === 'leftovers' || itemid === 'blacksludge') { physicalBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5); specialBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5); } if (hasMove['leechseed']) { physicalBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5); specialBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5); } if ((itemid === 'flameorb' || itemid === 'toxicorb') && abilityid !== 'magicguard') { if (itemid === 'toxicorb' && abilityid === 'poisonheal') { physicalBulk *= 1 + 0.1 * (2 + moveCount['Stall']); specialBulk *= 1 + 0.1 * (2 + moveCount['Stall']); } else { physicalBulk *= 0.8; specialBulk *= 0.8; } } if (itemid === 'lifeorb') { physicalBulk *= 0.7; specialBulk *= 0.7; } if (abilityid === 'multiscale' || abilityid === 'magicguard' || abilityid === 'regenerator') { physicalBulk *= 1.4; specialBulk *= 1.4; } if (itemid === 'eviolite') { physicalBulk *= 1.5; specialBulk *= 1.5; } if (itemid === 'assaultvest') specialBulk *= 1.5; var bulk = physicalBulk + specialBulk; if (bulk < 46000 && stats.spe >= 70) isFast = true; moveCount['bulk'] = bulk; moveCount['physicalBulk'] = physicalBulk; moveCount['specialBulk'] = specialBulk; if (hasMove['agility'] || hasMove['dragondance'] || hasMove['quiverdance'] || hasMove['rockpolish'] || hasMove['shellsmash'] || hasMove['flamecharge']) { isFast = true; } else if (abilityid === 'unburden' || abilityid === 'speedboost' || abilityid === 'motordrive') { isFast = true; moveCount['Ultrafast'] = 1; } else if (abilityid === 'chlorophyll' || abilityid === 'swiftswim' || abilityid === 'sandrush') { isFast = true; moveCount['Ultrafast'] = 2; } else if (itemid === 'salacberry') { isFast = true; } if (hasMove['agility'] || hasMove['shellsmash'] || hasMove['autotomize'] || hasMove['shiftgear'] || hasMove['rockpolish']) moveCount['Ultrafast'] = 2; moveCount['Fast'] = isFast ? 1 : 0; this.moveCount = moveCount; this.hasMove = hasMove; if (template.id === 'ditto') return abilityid === 'imposter' ? 'Physically Defensive' : 'Fast Bulky Support'; if (template.id === 'shedinja') return 'Fast Physical Sweeper'; if (itemid === 'choiceband' && moveCount['PhysicalAttack'] >= 2) { if (!isFast) return 'Bulky Band'; return 'Fast Band'; } else if (itemid === 'choicespecs' && moveCount['SpecialAttack'] >= 2) { if (!isFast) return 'Bulky Specs'; return 'Fast Specs'; } else if (itemid === 'choicescarf') { if (moveCount['PhysicalAttack'] === 0) return 'Special Scarf'; if (moveCount['SpecialAttack'] === 0) return 'Physical Scarf'; if (moveCount['PhysicalAttack'] > moveCount['SpecialAttack']) return 'Physical Biased Mixed Scarf'; if (moveCount['PhysicalAttack'] < moveCount['SpecialAttack']) return 'Special Biased Mixed Scarf'; if (stats.atk < stats.spa) return 'Special Biased Mixed Scarf'; return 'Physical Biased Mixed Scarf'; } if (template.id === 'unown') return 'Fast Special Sweeper'; if (moveCount['PhysicalStall'] && moveCount['Restoration']) { return 'Specially Defensive'; } if (moveCount['SpecialStall'] && moveCount['Restoration'] && itemid !== 'lifeorb') { return 'Physically Defensive'; } var offenseBias = ''; if (stats.spa > stats.atk && moveCount['Special'] > 1) offenseBias = 'Special'; else if (stats.atk > stats.spa && moveCount['Physical'] > 1) offenseBias = 'Physical'; else if (moveCount['Special'] > moveCount['Physical']) offenseBias = 'Special'; else offenseBias = 'Physical'; var offenseStat = stats[offenseBias === 'Special' ? 'spa' : 'atk']; if (moveCount['Stall'] + moveCount['Support'] / 2 <= 2 && bulk < 135000 && moveCount[offenseBias] >= 1.5) { if (isFast) { if (bulk > 80000 && !moveCount['Ultrafast']) return 'Bulky ' + offenseBias + ' Sweeper'; return 'Fast ' + offenseBias + ' Sweeper'; } else { if (moveCount[offenseBias] >= 3 || moveCount['Stall'] <= 0) { return 'Bulky ' + offenseBias + ' Sweeper'; } } } if (isFast && abilityid !== 'prankster') { if (stats.spe > 100 || bulk < 55000 || moveCount['Ultrafast']) { return 'Fast Bulky Support'; } } if (moveCount['SpecialStall']) return 'Physically Defensive'; if (moveCount['PhysicalStall']) return 'Specially Defensive'; if (template.id === 'blissey' || template.id === 'chansey') return 'Physically Defensive'; if (specialBulk >= physicalBulk) return 'Specially Defensive'; return 'Physically Defensive'; }, ensureMinEVs: function (evs, stat, min, evTotal) { if (!evs[stat]) evs[stat] = 0; var diff = min - evs[stat]; if (diff <= 0) return evTotal; if (evTotal <= 504) { var change = Math.min(508 - evTotal, diff); evTotal += change; evs[stat] += change; diff -= change; } if (diff <= 0) return evTotal; var evPriority = {def: 1, spd: 1, hp: 1, atk: 1, spa: 1, spe: 1}; for (var i in evPriority) { if (i === stat) continue; if (evs[i] && evs[i] > 128) { evs[i] -= diff; evs[stat] += diff; return evTotal; } } return evTotal; // can't do it :( }, ensureMaxEVs: function (evs, stat, min, evTotal) { if (!evs[stat]) evs[stat] = 0; var diff = evs[stat] - min; if (diff <= 0) return evTotal; evs[stat] -= diff; evTotal -= diff; return evTotal; // can't do it :( }, guessEVs: function (role) { var set = this.curSet; if (!set) return {}; var template = Tools.getTemplate(set.species || set.name); var stats = this.getBaseStats(template); var hasMove = this.hasMove; var moveCount = this.moveCount; var evs = {}; var plusStat = ''; var minusStat = ''; var statChart = { 'Bulky Band': ['atk', 'hp'], 'Fast Band': ['spe', 'atk'], 'Bulky Specs': ['spa', 'hp'], 'Fast Specs': ['spe', 'spa'], 'Physical Scarf': ['spe', 'atk'], 'Special Scarf': ['spe', 'spa'], 'Physical Biased Mixed Scarf': ['spe', 'atk'], 'Special Biased Mixed Scarf': ['spe', 'spa'], 'Fast Physical Sweeper': ['spe', 'atk'], 'Fast Special Sweeper': ['spe', 'spa'], 'Bulky Physical Sweeper': ['atk', 'hp'], 'Bulky Special Sweeper': ['spa', 'hp'], 'Fast Bulky Support': ['spe', 'hp'], 'Physically Defensive': ['def', 'hp'], 'Specially Defensive': ['spd', 'hp'] }; plusStat = statChart[role][0]; if (role === 'Fast Bulky Support') moveCount['Ultrafast'] = 0; if (plusStat === 'spe' && (moveCount['Ultrafast'] || evs['spe'] < 252)) { if (statChart[role][1] === 'atk' || statChart[role][1] == 'spa') { plusStat = statChart[role][1]; } else if (moveCount['Physical'] >= 3) { plusStat = 'atk'; } else if (stats.spd > stats.def) { plusStat = 'spd'; } else { plusStat = 'def'; } } if (this.curTeam && this.ignoreEVLimits) { evs = {hp:252, atk:252, def:252, spa:252, spd:252, spe:252}; if (hasMove['gyroball'] || hasMove['trickroom']) delete evs.spe; if (this.curTeam.gen === 1) delete evs.spd; if (this.curTeam.gen < 3) return evs; } else { if (!statChart[role]) return {}; var evTotal = 0; var i = statChart[role][0]; var stat = this.getStat(i, null, 252, plusStat === i ? 1.1 : 1.0); var ev = 252; while (ev > 0 && stat <= this.getStat(i, null, ev - 4, plusStat === i ? 1.1 : 1.0)) ev -= 4; evs[i] = ev; evTotal += ev; var i = statChart[role][1]; if (i === 'hp' && set.level && set.level < 20) i = 'spd'; var stat = this.getStat(i, null, 252, plusStat === i ? 1.1 : 1.0); var ev = 252; if (i === 'hp' && (hasMove['substitute'] || hasMove['transform']) && stat == Math.floor(stat / 4) * 4) stat -= 1; while (ev > 0 && stat <= this.getStat(i, null, ev - 4, plusStat === i ? 1.1 : 1.0)) ev -= 4; evs[i] = ev; evTotal += ev; if (set.item !== 'Leftovers' && set.item !== 'Black Sludge') { var hpParity = 1; // 1 = should be odd, 0 = should be even if ((hasMove['substitute'] || hasMove['bellydrum']) && (set.item || '').slice(-5) === 'Berry') { hpParity = 0; } var hp = evs['hp'] || 0; while (hp < 252 && evTotal < 508 && this.getStat('hp', null, hp, 1) % 2 !== hpParity) { hp += 4; evTotal += 4; } while (hp > 0 && this.getStat('hp', null, hp, 1) % 2 !== hpParity) { hp -= 4; evTotal -= 4; } while (hp > 0 && this.getStat('hp', null, hp - 4, 1) % 2 === hpParity) { hp -= 4; evTotal -= 4; } if (hp || evs['hp']) evs['hp'] = hp; } if (template.id === 'tentacruel') evTotal = this.ensureMinEVs(evs, 'spe', 16, evTotal); if (template.id === 'skarmory') evTotal = this.ensureMinEVs(evs, 'spe', 24, evTotal); if (template.id === 'jirachi') evTotal = this.ensureMinEVs(evs, 'spe', 32, evTotal); if (template.id === 'celebi') evTotal = this.ensureMinEVs(evs, 'spe', 36, evTotal); if (template.id === 'volcarona') evTotal = this.ensureMinEVs(evs, 'spe', 52, evTotal); if (template.id === 'gliscor') evTotal = this.ensureMinEVs(evs, 'spe', 72, evTotal); if (stats.spe == 97) evTotal = this.ensureMaxEVs(evs, 'spe', 220, evTotal); if (template.id === 'dragonite' && evs['hp']) evTotal = this.ensureMaxEVs(evs, 'spe', 220, evTotal); if (evTotal < 508) { var remaining = 508 - evTotal; if (remaining > 252) remaining = 252; i = null; if (!evs['atk'] && moveCount['PhysicalAttack'] >= 1) { i = 'atk'; } else if (!evs['spa'] && moveCount['SpecialAttack'] >= 1) { i = 'spa'; } else if (stats.hp == 1 && !evs['def']) { i = 'def'; } else if (stats.def === stats.spd && !evs['spd']) { i = 'spd'; } else if (!evs['spd']) { i = 'spd'; } else if (!evs['def']) { i = 'def'; } if (i) { ev = remaining; stat = this.getStat(i, null, ev); while (ev > 0 && stat === this.getStat(i, null, ev - 4)) ev -= 4; if (ev) evs[i] = ev; remaining -= ev; } if (remaining && !evs['spe']) { ev = remaining; stat = this.getStat('spe', null, ev); while (ev > 0 && stat === this.getStat('spe', null, ev - 4)) ev -= 4; if (ev) evs['spe'] = ev; } } } if (hasMove['gyroball'] || hasMove['trickroom']) { minusStat = 'spe'; } else if (!moveCount['PhysicalAttack']) { minusStat = 'atk'; } else if (moveCount['SpecialAttack'] < 1) { minusStat = 'spa'; } else if (moveCount['PhysicalAttack'] < 1) { minusStat = 'atk'; } else if (stats.def > stats.spd) { minusStat = 'spd'; } else { minusStat = 'def'; } if (plusStat === minusStat) { minusStat = (plusStat === 'spe' ? 'spd' : 'spe'); } evs.plusStat = plusStat; evs.minusStat = minusStat; return evs; }, // Stat calculator getStat: function (stat, set, evOverride, natureOverride) { if (!set) set = this.curSet; if (!set) return 0; if (!set.ivs) set.ivs = { hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31 }; if (!set.evs) set.evs = {}; // do this after setting set.evs because it's assumed to exist // after getStat is run var template = Tools.getTemplate(set.species); if (!template.exists) return 0; if (!set.level) set.level = 100; if (typeof set.ivs[stat] === 'undefined') set.ivs[stat] = 31; var baseStat = (this.getBaseStats(template))[stat]; var iv = (set.ivs[stat] || 0); if (this.curTeam.gen <= 2) iv &= 30; var ev = set.evs[stat]; if (evOverride !== undefined) ev = evOverride; if (ev === undefined) ev = (this.curTeam.gen > 2 ? 0 : 252); if (stat === 'hp') { if (baseStat === 1) return 1; return Math.floor(Math.floor(2 * baseStat + iv + Math.floor(ev / 4) + 100) * set.level / 100 + 10); } var val = Math.floor(Math.floor(2 * baseStat + iv + Math.floor(ev / 4)) * set.level / 100 + 5); if (natureOverride) { val *= natureOverride; } else if (BattleNatures[set.nature] && BattleNatures[set.nature].plus === stat) { val *= 1.1; } else if (BattleNatures[set.nature] && BattleNatures[set.nature].minus === stat) { val *= 0.9; } return Math.floor(val); }, // initialization getGen: function (format) { format = '' + format; if (format.substr(0, 3) !== 'gen') return 6; return parseInt(format.substr(3, 1), 10) || 6; }, destroy: function () { app.clearGlobalListeners(); Room.prototype.destroy.call(this); } }); var MoveSetPopup = exports.MoveSetPopup = Popup.extend({ initialize: function (data) { var buf = '<ul class="popupmenu">'; this.i = data.i; this.team = data.team; for (var i = 0; i < data.team.length; i++) { var set = data.team[i]; if (i !== data.i && i !== data.i + 1) { buf += '<li><button name="moveHere" value="' + i + '"><i class="fa fa-arrow-right"></i> Move here</button></li>'; } buf += '<li' + (i === data.i ? ' style="opacity:.3"' : ' style="opacity:.6"') + '><span class="pokemonicon" style="display:inline-block;vertical-align:middle;' + Tools.getIcon(set) + '"></span> ' + Tools.escapeHTML(set.name) + '</li>'; } if (i !== data.i && i !== data.i + 1) { buf += '<li><button name="moveHere" value="' + i + '"><i class="fa fa-arrow-right"></i> Move here</button></li>'; } buf += '</ul>'; this.$el.html(buf); }, moveHere: function (i) { this.close(); i = +i; var movedSet = this.team.splice(this.i, 1)[0]; if (i > this.i) i--; this.team.splice(i, 0, movedSet); app.rooms['teambuilder'].save(); if (app.rooms['teambuilder'].curSet) { app.rooms['teambuilder'].curSetLoc = i; app.rooms['teambuilder'].update(); app.rooms['teambuilder'].updateChart(); } else { app.rooms['teambuilder'].update(); } } }); var DeleteFolderPopup = this.DeleteFolderPopup = Popup.extend({ type: 'semimodal', initialize: function (data) { this.room = data.room; this.folder = data.folder; var buf = '<form><p>Remove "' + data.folder.slice(0, -1) + '"?</p><p><label><input type="checkbox" name="addname" /> Add "' + Tools.escapeHTML(this.folder.slice(0, -1)) + '" before team names</label></p>'; buf += '<p><button type="submit"><strong>Remove (keep teams)</strong></button> <!--button name="removeDelete"><strong>Remove (delete teams)</strong></button--> <button name="close" class="autofocus">Cancel</button></p></form>'; this.$el.html(buf); }, submit: function (data) { this.room.deleteFolder(this.folder, !!this.$('input[name=addname]')[0].checked); this.close(); } }); })(window, jQuery);
js/client-teambuilder.js
(function (exports, $) { // this is a useful global var teams; var TeambuilderRoom = exports.TeambuilderRoom = exports.Room.extend({ type: 'teambuilder', title: 'Teambuilder', initialize: function () { teams = Storage.teams; // left menu this.$el.addClass('ps-room-light').addClass('scrollable'); if (!Storage.whenTeamsLoaded.isLoaded) { Storage.whenTeamsLoaded(this.update, this); } this.update(); }, focus: function () { if (this.curTeam) { this.curTeam.iconCache = '!'; this.curTeam.gen = this.getGen(this.curTeam.format); Storage.activeSetList = this.curSetList; } }, blur: function () { if (this.saveFlag) { this.saveFlag = false; app.user.trigger('saveteams'); } }, events: { // team changes 'change input.teamnameedit': 'teamNameChange', 'click button.formatselect': 'selectFormat', 'change input[name=nickname]': 'nicknameChange', // details 'change .detailsform input': 'detailsChange', // stats 'keyup .statform input.numform': 'statChange', 'input .statform input[type=number].numform': 'statChange', 'change select[name=nature]': 'natureChange', 'change select[name=ivspread]': 'ivSpreadChange', // teambuilder events 'click .utilichart a': 'chartClick', 'keydown .chartinput': 'chartKeydown', 'keyup .chartinput': 'chartKeyup', 'focus .chartinput': 'chartFocus', 'blur .chartinput': 'chartChange', // drag/drop 'click .team': 'edit', 'click .selectFolder': 'selectFolder', 'mouseover .team': 'mouseOverTeam', 'mouseout .team': 'mouseOutTeam', 'dragstart .team': 'dragStartTeam', 'dragend .team': 'dragEndTeam', 'dragenter .team': 'dragEnterTeam', 'dragenter .folder .selectFolder': 'dragEnterFolder', 'dragleave .folder .selectFolder': 'dragLeaveFolder', 'dragexit .folder .selectFolder': 'dragExitFolder', // clipboard 'click .teambuilder-clipboard-data .result': 'clipboardResultSelect', 'click .teambuilder-clipboard-data': 'clipboardExpand', 'blur .teambuilder-clipboard-data': 'clipboardShrink' }, dispatchClick: function (e) { e.preventDefault(); e.stopPropagation(); if (this[e.currentTarget.value]) this[e.currentTarget.value](e); }, back: function () { if (this.exportMode) { if (this.curTeam) { this.curTeam.team = Storage.packTeam(this.curSetList); Storage.saveTeam(this.curTeam); } this.exportMode = false; } else if (this.curSet) { app.clearGlobalListeners(); this.curSet = null; Storage.saveTeam(this.curTeam); } else if (this.curTeam) { this.curTeam.team = Storage.packTeam(this.curSetList); this.curTeam.iconCache = ''; var team = this.curTeam; this.curTeam = null; Storage.activeSetList = this.curSetList = null; Storage.saveTeam(team); } else { return; } app.user.trigger('saveteams'); this.update(); }, // the teambuilder has three views: // - team list (curTeam falsy) // - team view (curTeam exists, curSet falsy) // - set view (curTeam exists, curSet exists) curTeam: null, curTeamLoc: 0, curSet: null, curSetLoc: 0, // curFolder will have '/' at the end if it's a folder, but // it will be alphanumeric (so guaranteed no '/') if it's a // format // Special values: // '' - show all // 'gen6' - show teams with no format // '/' - show teams with no folder curFolder: '', curFolderKeep: '', exportMode: false, update: function () { teams = Storage.teams; if (this.curTeam) { this.ignoreEVLimits = (this.curTeam.gen < 3); if (this.curSet) { return this.updateSetView(); } return this.updateTeamView(); } return this.updateTeamInterface(); }, /********************************************************* * Team list view *********************************************************/ deletedTeam: null, deletedTeamLoc: -1, updateTeamInterface: function () { this.deletedSet = null; this.deletedSetLoc = -1; var buf = ''; if (this.exportMode) { buf = '<div class="pad"><button name="back"><i class="fa fa-chevron-left"></i> List</button> <button name="saveBackup" class="savebutton"><i class="fa fa-floppy-o"></i> Save</button></div>'; buf += '<div class="teamedit"><textarea class="textbox" rows="17">' + Tools.escapeHTML(Storage.exportAllTeams()) + '</textarea></div>'; this.$el.html(buf); this.$('.teamedit textarea').focus().select(); return; } if (!Storage.whenTeamsLoaded.isLoaded) { if (!Storage.whenTeamsLoaded.isStalled) { buf = '<div class="pad"><p>lol zarel this is a horrible teambuilder</p>'; buf += '<p>that\'s because we\'re not done loading it...</p></div>'; } else { buf = '<div class="pad"><p>We\'re having some trouble loading teams securely.</p>'; buf += '<p>This is sometimes caused by antiviruses like Avast and BitDefender.</p>'; buf += '<p><strong>If you\'re using Firefox and an antivirus:</strong> Your antivirus is trying to scan your teams, and a recent Firefox update doesn\'t let it. Turn off HTTPS scanning in your antivirus or uninstall your antivirus, and your teams will come back.</p>'; buf += '<p>You can use the teambuilder insecurely, but any teams you\'ve saved securely won\'t be there.</p>'; buf += '<p><button class="button" name="insecureUse">Use teambuilder insecurely</button></p></div>'; } this.$el.html(buf); return; } // folderpane buf = '<div class="folderpane">'; buf += '</div>'; // teampane buf += '<div class="teampane">'; buf += '</div>'; this.$el.html(buf); this.updateFolderList(); this.updateTeamList(); }, insecureUse: function () { Storage.whenTeamsLoaded.load(); this.updateTeamInterface(); }, updateFolderList: function () { var buf = '<div class="folderlist"><div class="folderlistbefore"></div>'; buf += '<div class="folder' + (!this.curFolder ? ' cur"><div class="folderhack3"><div class="folderhack1"></div><div class="folderhack2"></div>' : '">') + '<div class="selectFolder" data-value="all"><em>(all)</em></div></div>' + (!this.curFolder ? '</div>' : ''); var folderTable = {}; var folders = []; if (Storage.teams) for (var i = -2; i < Storage.teams.length; i++) { if (i >= 0) { var folder = Storage.teams[i].folder; if (folder && !((folder + '/') in folderTable)) { folders.push('Z' + folder); folderTable[folder + '/'] = 1; if (!('/' in folderTable)) { folders.push('Z~'); folderTable['/'] = 1; } } } var format; if (i === -2) { format = this.curFolderKeep; } else if (i === -1) { format = this.curFolder; } else { format = Storage.teams[i].format; if (!format) format = 'gen6'; } if (!format) continue; if (format in folderTable) continue; folderTable[format] = 1; if (format.slice(-1) === '/') { folders.push('Z' + (format.slice(0, -1) || '~')); if (!('/' in folderTable)) { folders.push('Z~'); folderTable['/'] = 1; } continue; } if (format === 'gen6') { folders.push('A~'); continue; } switch (format.slice(0, 4)) { case 'gen1': format = 'F' + format.slice(4); break; case 'gen2': format = 'E' + format.slice(4); break; case 'gen3': format = 'D' + format.slice(4); break; case 'gen4': format = 'C' + format.slice(4); break; case 'gen5': format = 'B' + format.slice(4); break; default: format = 'A' + format; break; } folders.push(format); } folders.sort(); var gen = ''; var formatFolderBuf = '<div class="foldersep"></div>'; formatFolderBuf += '<div class="folder"><div class="selectFolder" data-value="+"><i class="fa fa-plus"></i><em>(add format folder)</em></div></div>'; for (var i = 0; i < folders.length; i++) { var format = folders[i]; var newGen; switch (format.charAt(0)) { case 'F': newGen = '1'; break; case 'E': newGen = '2'; break; case 'D': newGen = '3'; break; case 'C': newGen = '4'; break; case 'B': newGen = '5'; break; case 'A': newGen = '6'; break; case 'Z': newGen = '/'; break; } if (gen !== newGen) { gen = newGen; if (gen === '/') { buf += formatFolderBuf; formatFolderBuf = ''; buf += '<div class="foldersep"></div>'; buf += '<div class="folder"><h3>Folders</h3></div>'; } else { buf += '<div class="folder"><h3>Gen ' + gen + '</h3></div>'; } } if (gen === '/') { formatName = format.slice(1); format = formatName + '/'; if (formatName === '~') { formatName = '(uncategorized)'; format = '/'; } else { formatName = Tools.escapeHTML(formatName); } buf += '<div class="folder' + (this.curFolder === format ? ' cur"><div class="folderhack3"><div class="folderhack1"></div><div class="folderhack2"></div>' : '">') + '<div class="selectFolder" data-value="' + format + '"><i class="fa ' + (this.curFolder === format ? 'fa-folder-open' : 'fa-folder') + (format === '/' ? '-o' : '') + '"></i>' + formatName + '</div></div>' + (this.curFolder === format ? '</div>' : ''); continue; } var formatName = format.slice(1); if (formatName === '~') formatName = ''; if (newGen === '6' && formatName) { format = formatName; } else { format = 'gen' + newGen + formatName; } if (format === 'gen6') formatName = '(uncategorized)'; // folders are <div>s rather than <button>s because in theory it has // less weird interactions with HTML5 drag-and-drop buf += '<div class="folder' + (this.curFolder === format ? ' cur"><div class="folderhack3"><div class="folderhack1"></div><div class="folderhack2"></div>' : '">') + '<div class="selectFolder" data-value="' + format + '"><i class="fa ' + (this.curFolder === format ? 'fa-folder-open-o' : 'fa-folder-o') + '"></i>' + formatName + '</div></div>' + (this.curFolder === format ? '</div>' : ''); } buf += formatFolderBuf; buf += '<div class="foldersep"></div>'; buf += '<div class="folder"><div class="selectFolder" data-value="++"><i class="fa fa-plus"></i><em>(add folder)</em></div></div>'; buf += '<div class="folderlistafter"></div></div>'; this.$('.folderpane').html(buf); }, updateTeamList: function (resetScroll) { var teams = Storage.teams; var buf = ''; // teampane buf += this.clipboardHTML(); var filterFormat = ''; var filterFolder = undefined; if (!this.curFolder) { buf += '<h2>Hi</h2>'; buf += '<p>Did you have a good day?</p>'; buf += '<p><button class="button" name="greeting" value="Y"><i class="fa fa-smile-o"></i> Yes, my day was pretty good</button> <button class="button" name="greeting" value="N"><i class="fa fa-frown-o"></i> No, it wasn\'t great</button></p>'; buf += '<h2>All teams</h2>'; } else { if (this.curFolder.slice(-1) === '/') { filterFolder = this.curFolder.slice(0, -1); if (filterFolder) { buf += '<h2><i class="fa fa-folder-open"></i> ' + filterFolder + ' <button class="button small" style="margin-left:5px" name="renameFolder"><i class="fa fa-pencil"></i> Rename</button> <button class="button small" style="margin-left:5px" name="promptDeleteFolder"><i class="fa fa-times"></i> Remove</button></h2>'; } else { buf += '<h2><i class="fa fa-folder-open-o"></i> Teams not in any folders</h2>'; } } else { filterFormat = this.curFolder; buf += '<h2><i class="fa fa-folder-open-o"></i> ' + filterFormat + '</h2>'; } } var newButtonText = "New Team"; if (filterFolder) newButtonText = "New Team in folder"; if (filterFormat && filterFormat !== 'gen6') { newButtonText = "New " + Tools.escapeFormat(filterFormat) + " Team"; } buf += '<p><button name="newTop" class="button big"><i class="fa fa-plus-circle"></i> ' + newButtonText + '</button></p>'; buf += '<ul class="teamlist">'; var atLeastOne = false; try { if (!window.localStorage && !window.nodewebkit) buf += '<li>== CAN\'T SAVE ==<br /><small>Your browser doesn\'t support <code>localStorage</code> and can\'t save teams! Update to a newer browser.</small></li>'; } catch (e) { buf += '<li>== CAN\'T SAVE ==<br /><small><code>Cookies</code> are disabled so you can\'t save teams! Enable them in your browser settings.</small></li>'; } if (Storage.cantSave) buf += '<li>== CAN\'T SAVE ==<br /><small>You hit your browser\'s limit for team storage! Please backup them and delete some of them. Your teams won\'t be saved until you\'re under the limit again.</small></li>'; if (!teams.length) { if (this.deletedTeamLoc >= 0) { buf += '<li><button name="undoDelete"><i class="fa fa-undo"></i> Undo Delete</button></li>'; } buf += '<li><p><em>you don\'t have any teams lol</em></p></li>'; } else { for (var i = 0; i < teams.length + 1; i++) { if (i === this.deletedTeamLoc) { if (!atLeastOne) atLeastOne = true; buf += '<li><button name="undoDelete"><i class="fa fa-undo"></i> Undo Delete</button></li>'; } if (i >= teams.length) break; var team = teams[i]; if (team && !team.team && team.team !== '') { team = null; } if (!team) { buf += '<li>Error: A corrupted team was dropped</li>'; teams.splice(i, 1); i--; if (this.deletedTeamLoc && this.deletedTeamLoc > i) this.deletedTeamLoc--; continue; } if (filterFormat && filterFormat !== (team.format || 'gen6')) continue; if (filterFolder !== undefined && filterFolder !== team.folder) continue; if (!atLeastOne) atLeastOne = true; var formatText = ''; if (team.format) { formatText = '[' + team.format + '] '; } if (team.folder) formatText += team.folder + '/'; // teams are <div>s rather than <button>s because Firefox doesn't // support dragging and dropping buttons. buf += '<li><div name="edit" data-value="' + i + '" class="team" draggable="true">' + formatText + '<strong>' + Tools.escapeHTML(team.name) + '</strong><br /><small>'; buf += Storage.getTeamIcons(team); buf += '</small></div><button name="edit" value="' + i + '"><i class="fa fa-pencil"></i>Edit</button><button name="delete" value="' + i + '"><i class="fa fa-trash"></i>Delete</button></li>'; } if (!atLeastOne) { if (filterFolder) { buf += '<li><p><em>you don\'t have any teams in this folder lol</em></p></li>'; } else { buf += '<li><p><em>you don\'t have any ' + this.curFolder + ' teams lol</em></p></li>'; } } } buf += '</ul>'; if (atLeastOne) { buf += '<p><button name="new" class="button"><i class="fa fa-plus-circle"></i> ' + newButtonText + '</button></p>'; } if (window.nodewebkit) { buf += '<button name="revealFolder" class="button"><i class="fa fa-folder-open"></i> Reveal teams folder</button> <button name="reloadTeamsFolder" class="button"><i class="fa fa-refresh"></i> Reload teams files</button> <button name="backup" class="button"><i class="fa fa-upload"></i> Backup/Restore all teams</button>'; } else if (atLeastOne) { buf += '<p><strong>Clearing your cookies (specifically, <code>localStorage</code>) will delete your teams.</strong></p>'; buf += '<button name="backup" class="button"><i class="fa fa-upload"></i> Backup/Restore all teams</button>'; buf += '<p>If you want to clear your cookies or <code>localStorage</code>, you can use the Backup/Restore feature to save your teams as text first.</p>'; } else { buf += '<button name="backup" class="button"><i class="fa fa-upload"></i> Restore teams from backup</button>'; } var $pane = this.$('.teampane'); $pane.html(buf); if (resetScroll) { $pane.scrollTop(0); } else if (this.teamScrollPos) { $pane.scrollTop(this.teamScrollPos); this.teamScrollPos = 0; } }, greeting: function (answer, button) { var buf = '<p><strong>' + $(button).html() + '</p></strong>'; if (answer === 'N') { buf += '<p>Aww, that\'s too bad. :( I hope playing on Pok&eacute;mon Showdown today can help cheer you up!</p>'; } else if (answer === 'Y') { buf += '<p>Cool! I just added some pretty cool teambuilder features, so I\'m pretty happy, too. Did you know you can drag and drop teams to different format-folders? You can also drag and drop them to and from your computer (works best in Chrome).</p>'; buf += '<p><button class="button" name="greeting" value="W"><i class="fa fa-question-circle"></i> Wait, who are you? Talking to a teambuilder is weird.</button></p>'; } else if (answer === 'W') { buf += '<p>Oh, I\'m Zarel! I made a Credits button for this...</p>'; buf += '<div class="menugroup"><p><button class="button mainmenu4" name="credits"><i class="fa fa-info-circle"></i> Credits</button></p></div>'; buf += '<p>Isn\'t it pretty? Matches your background and everything. It used to be in the Main Menu but we had to get rid of it to save space.</p>'; buf += '<p>Speaking of, you should try <button class="button" name="background"><i class="fa fa-picture-o"></i> changing your background</button>.'; buf += '<p><button class="button" name="greeting" value="B"><i class="fa fa-hand-pointer-o"></i> You might be having too much fun with these buttons and icons</button></p>'; } else if (answer === 'B') { buf += '<p>I paid good money for those icons! I need to get my money\'s worth!</p>'; buf += '<p><button class="button" name="greeting" value="WR"><i class="fa fa-exclamation-triangle"></i> Wait, really?</button></p>'; } else if (answer === 'WR') { buf += '<p>No, they were free. That just makes it easier to get my money\'s worth. Let\'s play rock paper scissors!</p>'; buf += '<p><button class="button" name="greeting" value="RR"><i class="fa fa-hand-rock-o"></i> Rock</button> <button class="button" name="greeting" value="RP"><i class="fa fa-hand-paper-o"></i> Paper</button> <button class="button" name="greeting" value="RS"><i class="fa fa-hand-scissors-o"></i> Scissors</button> <button class="button" name="greeting" value="RL"><i class="fa fa-hand-lizard-o"></i> Lizard</button> <button class="button" name="greeting" value="RK"><i class="fa fa-hand-spock-o"></i> Spock</button></p>'; } else if (answer[0] === 'R') { buf += '<p>I play laser, I win. <i class="fa fa-hand-o-left"></i></p>'; buf += '<p><button class="button" name="greeting" value="YC"><i class="fa fa-thumbs-o-down"></i> You can\'t do that!</button></p>'; } else if (answer === 'SP') { buf += '<p>Okay, sure. I warn you, I\'m using the same RNG that makes Stone Edge miss for you.</p>'; buf += '<p><button class="button" name="greeting" value="SP3"><i class="fa fa-caret-square-o-right"></i> I want to play Rock Paper Scissors</button> <button class="button" name="greeting" value="SP5"><i class="fa fa-caret-square-o-right"></i> I want to play Rock Paper Scissors Lizard Spock</button></p>'; } else if (answer === 'SP3') { buf += '<p><button class="button" name="greeting" value="PR3"><i class="fa fa-hand-rock-o"></i> Rock</button> <button class="button" name="greeting" value="PP3"><i class="fa fa-hand-paper-o"></i> Paper</button> <button class="button" name="greeting" value="PS3"><i class="fa fa-hand-scissors-o"></i> Scissors</button></p>'; } else if (answer === 'SP5') { buf += '<p><button class="button" name="greeting" value="PR5"><i class="fa fa-hand-rock-o"></i> Rock</button> <button class="button" name="greeting" value="PP5"><i class="fa fa-hand-paper-o"></i> Paper</button> <button class="button" name="greeting" value="PS5"><i class="fa fa-hand-scissors-o"></i> Scissors</button> <button class="button" name="greeting" value="PL5"><i class="fa fa-hand-lizard-o"></i> Lizard</button> <button class="button" name="greeting" value="PK5"><i class="fa fa-hand-spock-o"></i> Spock</button></p>'; } else if (answer[0] === 'P') { var rpsChart = { R: 'rock', P: 'paper', S: 'scissors', L: 'lizard', K: 'spock' }; var rpsWinChart = { SP: 'cuts', SL: 'decapitates', PR: 'covers', PK: 'disproves', RL: 'crushes', RS: 'crushes', LK: 'poisons', LP: 'eats', KS: 'smashes', KR: 'vaporizes' }; var my = ['R', 'P', 'S', 'L', 'K'][Math.floor(Math.random() * Number(answer[2]))]; var your = answer[1]; buf += '<p>I play <i class="fa fa-hand-' + rpsChart[my] + '-o"></i> ' + rpsChart[my] + '!</p>'; if ((my + your) in rpsWinChart) { buf += '<p>And ' + rpsChart[my] + ' ' + rpsWinChart[my + your] + ' ' + rpsChart[your] + ', so I win!</p>'; } else if ((your + my) in rpsWinChart) { buf += '<p>But ' + rpsChart[your] + ' ' + rpsWinChart[your + my] + ' ' + rpsChart[my] + ', so you win...</p>'; } else { buf += '<p>We played the same thing, so it\'s a tie.</p>'; } if (!this.rpsScores || !this.rpsScores.length) { this.rpsScores = ['pi', '$3.50', '9.80665 m/s<sup>2</sup>', '28°C', '百万点', '<i class="fa fa-bitcoin"></i>0.0000174', '<s>priceless</s> <i class="fa fa-cc-mastercard"></i> MasterCard', '127.0.0.1', 'C&minus;, see me after class']; } var score = this.rpsScores.splice(Math.floor(Math.random() * this.rpsScores.length), 1)[0]; buf += '<p>Score: ' + score + '</p>'; buf += '<p><button class="button" name="greeting" value="SP' + answer[2] + '"><i class="fa fa-caret-square-o-right"></i> I demand a rematch!</button></p>'; } else if (answer === 'YC') { buf += '<p>Okay, then I play peace sign <i class="fa fa-hand-peace-o"></i>, everyone signs a peace treaty, ending the war and ushering in a new era of prosperity.</p>'; buf += '<p><button class="button" name="greeting" value="SP"><i class="fa fa-caret-square-o-right"></i> I wanted to play for real...</button></p>'; } $(button).parent().replaceWith(buf); }, credits: function () { app.addPopup(CreditsPopup); }, background: function () { app.addPopup(CustomBackgroundPopup); }, selectFolder: function (format) { if (format && format.currentTarget) { var e = format; format = $(e.currentTarget).data('value'); e.preventDefault(); if (format === '+') { e.stopImmediatePropagation(); var self = this; app.addPopup(FormatPopup, {format: '', sourceEl: e.currentTarget, selectType: 'teambuilder', onselect: function (newFormat) { self.selectFolder(newFormat); }}); return; } if (format === '++') { e.stopImmediatePropagation(); var self = this; // app.addPopupPrompt("Folder name:", "Create folder", function (newFormat) { // self.selectFolder(newFormat + '/'); // }); app.addPopup(PromptPopup, {message: "Folder name:", button: "Create folder", sourceEl: e.currentTarget, callback: function (name) { name = $.trim(name); if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) { app.addPopupMessage("Names can't contain slashes, since they're used as a folder separator."); name = name.replace(/[\\\/]/g, ''); } if (!name) return; self.selectFolder(name + '/'); }}); return; } } else { this.curFolderKeep = format; } this.curFolder = (format === 'all' ? '' : format); this.updateFolderList(); this.updateTeamList(true); }, renameFolder: function () { if (!this.curFolder) return; if (this.curFolder.slice(-1) !== '/') return; var oldFolder = this.curFolder.slice(0, -1); var self = this; app.addPopup(PromptPopup, {message: "Folder name:", button: "Rename folder", value: oldFolder, callback: function (name) { name = $.trim(name); if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) { app.addPopupMessage("Names can't contain slashes, since they're used as a folder separator."); name = name.replace(/[\\\/]/g, ''); } if (!name) return; if (name === oldFolder) return; for (var i = 0; i < Storage.teams.length; i++) { var team = Storage.teams[i]; if (team.folder !== oldFolder) continue; team.folder = name; if (window.nodewebkit) Storage.saveTeam(team); } if (!window.nodewebkit) Storage.saveTeams(); self.selectFolder(name + '/'); }}); }, promptDeleteFolder: function () { app.addPopup(DeleteFolderPopup, {folder: this.curFolder, room: this}); }, deleteFolder: function (format, addName) { if (format.slice(-1) !== '/') return; var oldFolder = format.slice(0, -1); if (this.curFolderKeep === oldFolder) { this.curFolderKeep = ''; } for (var i = 0; i < Storage.teams.length; i++) { var team = Storage.teams[i]; if (team.folder !== oldFolder) continue; team.folder = ''; if (addName) team.name = oldFolder + ' ' + team.name; if (window.nodewebkit) Storage.saveTeam(team); } if (!window.nodewebkit) Storage.saveTeams(); this.selectFolder('/'); }, show: function () { Room.prototype.show.apply(this, arguments); var $teamwrapper = this.$('.teamwrapper'); var width = $(window).width(); if (!$teamwrapper.length) return; if (width < 640) { var scale = (width / 640); $teamwrapper.css('transform', 'scale(' + scale + ')'); $teamwrapper.addClass('scaled'); } else { $teamwrapper.css('transform', 'none'); $teamwrapper.removeClass('scaled'); } }, // button actions revealFolder: function () { Storage.revealFolder(); }, reloadTeamsFolder: function () { Storage.nwLoadTeams(); }, edit: function (i) { this.teamScrollPos = this.$('.teampane').scrollTop(); if (i && i.currentTarget) { i = $(i.currentTarget).data('value'); } i = +i; this.curTeam = teams[i]; this.curTeam.iconCache = '!'; this.curTeam.gen = this.getGen(this.curTeam.format); Storage.activeSetList = this.curSetList = Storage.unpackTeam(this.curTeam.team); this.curTeamIndex = i; this.update(); }, "delete": function (i) { i = +i; this.deletedTeamLoc = i; this.deletedTeam = teams.splice(i, 1)[0]; for (var room in app.rooms) { var selection = app.rooms[room].$('button.teamselect').val(); if (!selection || selection === 'random') continue; var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox; if (i < obj.curTeamIndex) { obj.curTeamIndex--; } else if (i === obj.curTeamIndex) { obj.curTeamIndex = -1; } } Storage.deleteTeam(this.deletedTeam); app.user.trigger('saveteams'); this.updateTeamList(); }, undoDelete: function () { if (this.deletedTeamLoc >= 0) { teams.splice(this.deletedTeamLoc, 0, this.deletedTeam); for (var room in app.rooms) { var selection = app.rooms[room].$('button.teamselect').val(); if (!selection || selection === 'random') continue; var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox; if (this.deletedTeamLoc < obj.curTeamIndex + 1) { obj.curTeamIndex++; } else if (obj.curTeamIndex === -1) { obj.curTeamIndex = this.deletedTeamLoc; } } var undeletedTeam = this.deletedTeam; this.deletedTeam = null; this.deletedTeamLoc = -1; Storage.saveTeam(undeletedTeam); app.user.trigger('saveteams'); this.update(); } }, saveBackup: function () { Storage.deleteAllTeams(); Storage.importTeam(this.$('.teamedit textarea').val(), true); teams = Storage.teams; Storage.saveAllTeams(); for (var room in app.rooms) { var selection = app.rooms[room].$('button.teamselect').val(); if (!selection || selection === 'random') continue; var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox; obj.curTeamIndex = 0; } this.back(); }, "new": function () { var format = this.curFolder; var folder = ''; if (format && format.charAt(format.length - 1) === '/') { folder = format.slice(0, -1); format = ''; } var newTeam = { name: 'Untitled ' + (teams.length + 1), format: format, team: '', folder: folder, iconCache: '' }; teams.push(newTeam); this.edit(teams.length - 1); }, newTop: function () { var format = this.curFolder; var folder = ''; if (format && format.charAt(format.length - 1) === '/') { folder = format.slice(0, -1); format = ''; } var newTeam = { name: 'Untitled ' + (teams.length + 1), format: format, team: '', folder: folder, iconCache: '' }; teams.unshift(newTeam); for (var room in app.rooms) { var selection = app.rooms[room].$('button.teamselect').val(); if (!selection || selection === 'random') continue; var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox; obj.curTeamIndex++; } this.edit(0); }, "import": function () { if (this.exportMode) return this.back(); this.exportMode = true; if (!this.curTeam) { this['new'](); } else { this.update(); } }, backup: function () { this.curTeam = null; this.curSetList = null; this.exportMode = true; this.update(); }, // drag and drop // because of a bug in Chrome and Webkit: // https://code.google.com/p/chromium/issues/detail?id=410328 // we can't use CSS :hover mouseOverTeam: function (e) { e.currentTarget.className = 'team team-hover'; }, mouseOutTeam: function (e) { e.currentTarget.className = 'team'; }, dragStartTeam: function (e) { var target = e.currentTarget; var dataTransfer = e.originalEvent.dataTransfer; dataTransfer.effectAllowed = 'copyMove'; dataTransfer.setData("text/plain", "Team " + e.currentTarget.dataset.value); var team = Storage.teams[e.currentTarget.dataset.value]; var filename = team.name; if (team.format) filename = '[' + team.format + '] ' + filename; filename = $.trim(filename).replace(/[\\\/]+/g, '') + '.txt'; var urlprefix = "data:text/plain;base64,"; if (document.location.protocol === 'https:') { // Chrome is dumb and doesn't support data URLs in HTTPS urlprefix = "https://play.pokemonshowdown.com/action.php?act=dlteam&team="; } var contents = Storage.exportTeam(team.team).replace(/\n/g, '\r\n'); var downloadurl = "text/plain:" + filename + ":" + urlprefix + encodeURIComponent(window.btoa(unescape(encodeURIComponent(contents)))); console.log(downloadurl); dataTransfer.setData("DownloadURL", downloadurl); app.dragging = e.currentTarget; app.draggingRoom = this.id; app.draggingLoc = parseInt(e.currentTarget.dataset.value, 10); var elOffset = $(e.currentTarget).offset(); app.draggingOffsetX = e.originalEvent.pageX - elOffset.left; app.draggingOffsetY = e.originalEvent.pageY - elOffset.top; this.finalOffset = null; setTimeout(function () { $(e.currentTarget).parent().addClass('dragging'); }, 0); }, dragEndTeam: function (e) { this.finishDrop(); }, finishDrop: function () { var teamEl = app.dragging; app.dragging = null; var originalLoc = parseInt(teamEl.dataset.value, 10); if (isNaN(originalLoc)) { throw new Error("drag failed"); } var newLoc = Math.floor(app.draggingLoc); if (app.draggingLoc < originalLoc) newLoc += 1; var team = Storage.teams[originalLoc]; var edited = false; if (newLoc !== originalLoc) { Storage.teams.splice(originalLoc, 1); Storage.teams.splice(newLoc, 0, team); for (var room in app.rooms) { var selection = app.rooms[room].$('button.teamselect').val(); if (!selection || selection === 'random') continue; var obj = app.rooms[room].id === "" ? app.rooms[room] : app.rooms[room].tournamentBox; if (originalLoc === obj.curTeamIndex) { obj.curTeamIndex = newLoc; } else if (originalLoc > obj.curTeamIndex && newLoc <= obj.curTeamIndex) { obj.curTeamIndex++; } else if (originalLoc < obj.curTeamIndex && newLoc >= obj.curTeamIndex) { obj.curTeamIndex--; } } edited = true; } // possibly half-works-around a hover issue in this.$('.teamlist').css('pointer-events', 'none'); $(teamEl).parent().removeClass('dragging'); var format = this.curFolder; if (app.draggingFolder) { var $folder = $(app.draggingFolder); app.draggingFolder = null; var $plusOneFolder = $folder.find('.plusonefolder'); $folder.removeClass('active'); if (!$plusOneFolder.length) { $folder.prepend('<strong style="float:right;margin-right:3px;padding:0 2px;border-radius:3px;background:#CC8500;color:white" class="plusonefolder">+1</strong>'); } else { var count = Number($plusOneFolder.text().substr(1)) + 1; $plusOneFolder.text('+' + count); } format = $folder.data('value'); if (format.slice(-1) === '/') { team.folder = format.slice(0, -1); } else { team.format = format; } edited = true; this.updateTeamList(); } else { if (format.slice(-1) === '/') { team.folder = format.slice(0, -1); edited = true; } this.updateTeamList(); } if (edited) { Storage.saveTeam(team); app.user.trigger('saveteams'); } // We're going to try to animate the team settling into its new position if (this.finalOffset) { // event.pageY and event.pageX are buggy on literally every browser: // in Chrome: // event.pageX|pageY is the position of the bottom left corner of the draggable, instead // of the mouse position // in Safari: // window.innerHeight * 2 - window.outerHeight - event.pageY is the mouse position // No, I don't understand what's going on, either, but unsurprisingly this fails utterly // if the page is zoomed. // in Firefox: // event.pageX|pageY are straight-up unsupported // if you don't believe me, uncomment and see for yourself: // console.log('x,y = ' + [e.originalEvent.x, e.originalEvent.y]); // console.log('screenX,screenY = ' + [e.originalEvent.screenX, e.originalEvent.screenY]); // console.log('clientX,clientY = ' + [e.originalEvent.clientX, e.originalEvent.clientY]); // console.log('pageX,pageY = ' + [e.originalEvent.pageX, e.originalEvent.pageY]); // Because of this, we're just going to steal the values from the drop event, where // everything is sane. var $newTeamEl = this.$('.team[data-value=' + newLoc + ']'); if (!$newTeamEl.length) return; var finalPos = $newTeamEl.offset(); $newTeamEl.css('transform', 'translate(' + (this.finalOffset[0] - finalPos.left) + 'px, ' + (this.finalOffset[1] - finalPos.top) + 'px)'); setTimeout(function () { $newTeamEl.css('transition', 'transform 0.15s'); // it's 2015 and Safari doesn't support unprefixed transition!!! $newTeamEl.css('-webkit-transition', '-webkit-transform 0.15s'); $newTeamEl.css('transform', 'translate(0px, 0px)'); }); } }, dragEnterTeam: function (e) { if (!app.dragging) return; var $draggingLi = $(app.dragging).parent(); this.dragLeaveFolder(); if (e.currentTarget === app.dragging) { e.preventDefault(); return; } var hoverLoc = parseInt(e.currentTarget.dataset.value, 10); if (app.draggingLoc > hoverLoc) { // dragging up $(e.currentTarget).parent().before($draggingLi); app.draggingLoc = parseInt(e.currentTarget.dataset.value, 10) - 0.5; } else { // dragging down $(e.currentTarget).parent().after($draggingLi); app.draggingLoc = parseInt(e.currentTarget.dataset.value, 10) + 0.5; } }, dragEnterFolder: function (e) { if (!app.dragging) return; this.dragLeaveFolder(); if (e.currentTarget === app.draggingFolder) { return; } var format = e.currentTarget.dataset.value; if (format === '+' || format === '++' || format === 'all' || format === this.curFolder) { return; } if (parseInt(app.dragging.dataset.value, 10) >= Storage.teams.length && format.slice(-1) !== '/') { // dragging a team file, already has a known format return; } app.draggingFolder = e.currentTarget; $(app.draggingFolder).addClass('active'); // amusing note: using .detach() instead of .hide() will make `dragend` not fire $(app.dragging).parent().hide(); }, dragLeaveFolder: function (e) { // sometimes there's a race condition and dragEnter happens before dragLeave if (e && e.currentTarget !== app.draggingFolder) return; if (!app.dragging || !app.draggingFolder) return; $(app.draggingFolder).removeClass('active'); app.draggingFolder = null; $(app.dragging).parent().show(); }, defaultDragEnterTeam: function (e) { var dataTransfer = e.originalEvent.dataTransfer; if (!dataTransfer) return; if (dataTransfer.types.indexOf && dataTransfer.types.indexOf('Files') === -1) return; if (dataTransfer.types.contains && !dataTransfer.types.contains('Files')) return; if (dataTransfer.files[0] && dataTransfer.files[0].name.slice(-4) !== '.txt') return; // We're dragging a file! It might be a team! if (app.curFolder && app.curFolder.slice(-1) !== '/') { this.selectFolder('all'); } this.$('.teamlist').append('<li class="dragging"><div class="team" data-value="' + Storage.teams.length + '"></div></li>'); app.dragging = this.$('.dragging .team')[0]; app.draggingRoom = this.id; app.draggingLoc = Storage.teams.length; app.draggingOffsetX = 180; app.draggingOffsetY = 25; }, defaultDropTeam: function (e) { if (e.originalEvent.dataTransfer.files && e.originalEvent.dataTransfer.files[0]) { var file = e.originalEvent.dataTransfer.files[0]; var name = file.name; if (name.slice(-4) !== '.txt') { app.dragging = null; this.updateTeamList(); app.addPopupMessage("Your file is not a valid team. Team files are .txt files."); return; } var reader = new FileReader(); var self = this; reader.onload = function (e) { var team; try { team = Storage.packTeam(Storage.importTeam(e.target.result)); } catch (err) { app.addPopupMessage("Your file is not a valid team."); self.updateTeamList(); return; } var name = file.name; if (name.slice(name.length - 4).toLowerCase() === '.txt') { name = name.substr(0, name.length - 4); } var format = ''; var bracketIndex = name.indexOf(']'); if (bracketIndex >= 0) { format = name.substr(1, bracketIndex - 1); name = $.trim(name.substr(bracketIndex + 1)); } Storage.teams.push({ name: name, format: format, team: team, folder: '', iconCache: '' }); self.finishDrop(); }; reader.readAsText(file); } this.finalOffset = [e.originalEvent.pageX - app.draggingOffsetX, e.originalEvent.pageY - app.draggingOffsetY]; }, /********************************************************* * Team view *********************************************************/ updateTeamView: function () { this.curChartName = ''; this.curChartType = ''; var buf = ''; if (this.exportMode) { buf = '<div class="pad"><button name="back"><i class="fa fa-chevron-left"></i> List</button> <input class="textbox teamnameedit" type="text" class="teamnameedit" size="30" value="' + Tools.escapeHTML(this.curTeam.name) + '" /> <button name="saveImport"><i class="fa fa-upload"></i> Import/Export</button> <button name="saveImport" class="savebutton"><i class="fa fa-floppy-o"></i> Save</button></div>'; buf += '<div class="teamedit"><textarea class="textbox" rows="17">' + Tools.escapeHTML(Storage.exportTeam(this.curSetList)) + '</textarea></div>'; } else { buf = '<div class="pad"><button name="back"><i class="fa fa-chevron-left"></i> List</button> <input class="textbox teamnameedit" type="text" class="teamnameedit" size="30" value="' + Tools.escapeHTML(this.curTeam.name) + '" /> <button name="import"><i class="fa fa-upload"></i> Import/Export</button></div>'; buf += '<div class="teamchartbox">'; buf += '<ol class="teamchart">'; buf += '<li>' + this.clipboardHTML() + '</li>'; var i = 0; if (this.curSetList.length && !this.curSetList[this.curSetList.length - 1].species) { this.curSetList.splice(this.curSetList.length - 1, 1); } if (exports.BattleFormats) { buf += '<li class="format-select">'; buf += '<label class="label">Format:</label><button class="select formatselect teambuilderformatselect" name="format" value="' + this.curTeam.format + '">' + (Tools.escapeFormat(this.curTeam.format) || '<em>Select a format</em>') + '</button>'; var btnClass = 'button' + (!this.curSetList.length ? ' disabled' : ''); buf += ' <button name="validate" class="' + btnClass + '"><i class="fa fa-check"></i> Validate</button></li>'; } if (!this.curSetList.length) { buf += '<li><em>you have no pokemon lol</em></li>'; } for (i = 0; i < this.curSetList.length; i++) { if (this.curSetList.length < 6 && this.deletedSet && i === this.deletedSetLoc) { buf += '<li><button name="undeleteSet"><i class="fa fa-undo"></i> Undo Delete</button></li>'; } buf += this.renderSet(this.curSetList[i], i); } if (this.deletedSet && i === this.deletedSetLoc) { buf += '<li><button name="undeleteSet"><i class="fa fa-undo"></i> Undo Delete</button></li>'; } if (i === 0) { buf += '<li><button name="import" class="button big"><i class="fa fa-upload"></i> Import from text</button></li>'; } if (i < 6) { buf += '<li><button name="addPokemon" class="button big"><i class="fa fa-plus"></i> Add Pok&eacute;mon</button></li>'; } buf += '</ol>'; buf += '</div>'; } this.$el.html('<div class="teamwrapper">' + buf + '</div>'); this.$(".teamedit textarea").focus().select(); if ($(window).width() < 640) this.show(); }, renderSet: function (set, i) { var template = Tools.getTemplate(set.species); var buf = '<li value="' + i + '">'; if (!set.species) { if (this.deletedSet) { buf += '<div class="setmenu setmenu-left"><button name="undeleteSet"><i class="fa fa-undo"></i> Undo Delete</button></div>'; } buf += '<div class="setmenu"><button name="importSet"><i class="fa fa-upload"></i>Import</button></div>'; buf += '<div class="setchart" style="background-image:url(' + Tools.resourcePrefix + 'sprites/bw/0.png);"><div class="setcol setcol-icon"><span class="itemicon"></span><div class="setcell setcell-pokemon"><label>Pok&eacute;mon</label><input type="text" name="pokemon" class="textbox chartinput" value="" /></div></div></div>'; buf += '</li>'; return buf; } buf += '<div class="setmenu"><button name="copySet"><i class="fa fa-files-o"></i>Copy</button> <button name="importSet"><i class="fa fa-upload"></i>Import/Export</button> <button name="moveSet"><i class="fa fa-arrows"></i>Move</button> <button name="deleteSet"><i class="fa fa-trash"></i>Delete</button></div>'; buf += '<div class="setchart-nickname">'; buf += '<label>Nickname</label><input type="text" name="nickname" class="textbox" value="' + Tools.escapeHTML(set.name || '') + '" placeholder="' + Tools.escapeHTML(template.baseSpecies) + '" />'; buf += '</div>'; buf += '<div class="setchart" style="' + Tools.getTeambuilderSprite(set, this.curTeam.gen) + ';">'; // icon var itemicon = '<span class="itemicon"></span>'; if (set.item) { var item = Tools.getItem(set.item); itemicon = '<span class="itemicon" style="' + Tools.getItemIcon(item) + '"></span>'; } buf += '<div class="setcol setcol-icon">' + itemicon + '<div class="setcell setcell-pokemon"><label>Pok&eacute;mon</label><input type="text" name="pokemon" class="textbox chartinput" value="' + Tools.escapeHTML(set.species) + '" /></div></div>'; // details buf += '<div class="setcol setcol-details"><div class="setrow">'; buf += '<div class="setcell setcell-details"><label>Details</label><button class="textbox setdetails" tabindex="-1" name="details">'; var GenderChart = { 'M': 'Male', 'F': 'Female', 'N': '&mdash;' }; buf += '<span class="detailcell detailcell-first"><label>Level</label>' + (set.level || 100) + '</span>'; if (this.curTeam.gen > 1) { buf += '<span class="detailcell"><label>Gender</label>' + GenderChart[set.gender || template.gender || 'N'] + '</span>'; buf += '<span class="detailcell"><label>Happiness</label>' + (typeof set.happiness === 'number' ? set.happiness : 255) + '</span>'; buf += '<span class="detailcell"><label>Shiny</label>' + (set.shiny ? 'Yes' : 'No') + '</span>'; } buf += '</button></div>'; buf += '</div><div class="setrow">'; if (this.curTeam.gen > 1) buf += '<div class="setcell setcell-item"><label>Item</label><input type="text" name="item" class="textbox chartinput" value="' + Tools.escapeHTML(set.item) + '" /></div>'; if (this.curTeam.gen > 2) buf += '<div class="setcell setcell-ability"><label>Ability</label><input type="text" name="ability" class="textbox chartinput" value="' + Tools.escapeHTML(set.ability) + '" /></div>'; buf += '</div></div>'; // moves if (!set.moves) set.moves = []; buf += '<div class="setcol setcol-moves"><div class="setcell"><label>Moves</label>'; buf += '<input type="text" name="move1" class="textbox chartinput" value="' + Tools.escapeHTML(set.moves[0]) + '" /></div>'; buf += '<div class="setcell"><input type="text" name="move2" class="textbox chartinput" value="' + Tools.escapeHTML(set.moves[1]) + '" /></div>'; buf += '<div class="setcell"><input type="text" name="move3" class="textbox chartinput" value="' + Tools.escapeHTML(set.moves[2]) + '" /></div>'; buf += '<div class="setcell"><input type="text" name="move4" class="textbox chartinput" value="' + Tools.escapeHTML(set.moves[3]) + '" /></div>'; buf += '</div>'; // stats buf += '<div class="setcol setcol-stats"><div class="setrow"><label>Stats</label><button class="textbox setstats" name="stats">'; buf += '<span class="statrow statrow-head"><label></label> <span class="statgraph"></span> <em>EV</em></span>'; var stats = {}; var defaultEV = (this.curTeam.gen > 2 ? 0 : 252); for (var j in BattleStatNames) { if (j === 'spd' && this.curTeam.gen === 1) continue; stats[j] = this.getStat(j, set); var ev = (set.evs[j] === undefined ? defaultEV : set.evs[j]); var evBuf = '<em>' + (ev === defaultEV ? '' : ev) + '</em>'; if (BattleNatures[set.nature] && BattleNatures[set.nature].plus === j) { evBuf += '<small>+</small>'; } else if (BattleNatures[set.nature] && BattleNatures[set.nature].minus === j) { evBuf += '<small>&minus;</small>'; } var width = stats[j] * 75 / 504; if (j == 'hp') width = stats[j] * 75 / 704; if (width > 75) width = 75; var color = Math.floor(stats[j] * 180 / 714); if (color > 360) color = 360; var statName = this.curTeam.gen === 1 && j === 'spa' ? 'Spc' : BattleStatNames[j]; buf += '<span class="statrow"><label>' + statName + '</label> <span class="statgraph"><span style="width:' + width + 'px;background:hsl(' + color + ',40%,75%);"></span></span> ' + evBuf + '</span>'; } buf += '</button></div></div>'; buf += '</div></li>'; return buf; }, saveImport: function () { Storage.activeSetList = this.curSetList = Storage.importTeam(this.$('.teamedit textarea').val()); this.back(); }, addPokemon: function () { if (!this.curTeam) return; var team = this.curSetList; if (!team.length || team[team.length - 1].species) { var newPokemon = { name: '', species: '', item: '', nature: '', evs: {}, ivs: {}, moves: [] }; team.push(newPokemon); } this.curSet = team[team.length - 1]; this.curSetLoc = team.length - 1; this.curChartName = ''; this.update(); this.$('input[name=pokemon]').select(); }, pastePokemon: function (i, btn) { if (!this.curTeam) return; var team = this.curSetList; if (team.length >= 6) return; if (!this.clipboardCount()) return; if (team.push($.extend(true, {}, this.clipboard[0])) >= 6) { $(btn).css('display', 'none'); } this.update(); this.save(); }, saveFlag: false, save: function () { this.saveFlag = true; if (this.curTeam) { Storage.saveTeam(this.curTeam); } else { Storage.saveTeams(); } }, validate: function () { var format = this.curTeam.format || 'anythinggoes'; if (!this.curSetList.length) { app.addPopupMessage("You need at least one Pokémon to validate."); return; } if (window.BattleFormats && BattleFormats[format] && BattleFormats[format].hasBattleFormat) { format = BattleFormats[format].battleFormat; } app.sendTeam(this.curTeam); app.send('/vtm ' + format); }, teamNameChange: function (e) { var name = ($.trim(e.currentTarget.value) || 'Untitled ' + (this.curTeamLoc + 1)); if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) { app.addPopupMessage("Names can't contain slashes, since they're used as a folder separator."); name = name.replace(/[\\\/]/g, ''); } if (name.indexOf('|') >= 0) { app.addPopupMessage("Names can't contain the character |, since they're used for storing teams."); name = name.replace(/\|/g, ''); } this.curTeam.name = name; e.currentTarget.value = name; this.save(); }, format: function (format, button) { if (!window.BattleFormats) { return; } var self = this; app.addPopup(FormatPopup, {format: format, sourceEl: button, selectType: 'teambuilder', onselect: function (newFormat) { self.changeFormat(newFormat); }}); }, changeFormat: function (format) { this.curTeam.format = format; this.curTeam.gen = this.getGen(this.curTeam.format); this.save(); if (this.curTeam.gen === 5 && !Tools.loadedSpriteData['bw']) Tools.loadSpriteData('bw'); this.update(); }, nicknameChange: function (e) { var i = +$(e.currentTarget).closest('li').attr('value'); var set = this.curSetList[i]; var name = $.trim(e.currentTarget.value).replace(/\|/g, ''); e.currentTarget.value = set.name = name; this.save(); }, // clipboard clipboard: [], clipboardCount: function () { return this.clipboard.length; }, clipboardVisible: function () { return !!this.clipboardCount(); }, clipboardHTML: function () { var buf = ''; buf += '<div class="teambuilder-clipboard-container" style="display: ' + (this.clipboardVisible() ? 'block' : 'none') + ';">'; buf += '<div class="teambuilder-clipboard-title">Clipboard:</div>'; buf += '<div class="teambuilder-clipboard-data" tabindex="-1">' + this.clipboardInnerHTML() + '</div>'; buf += '<div class="teambuilder-clipboard-buttons">'; if (this.curTeam && this.curSetList.length < 6) { buf += '<button name="pastePokemon" class="teambuilder-clipboard-button-left"><i class="fa fa-clipboard"></i> Paste!</button>'; } buf += '<button name="clipboardRemoveAll" class="teambuilder-clipboard-button-right"><i class="fa fa-trash"></i> Clear clipboard</button>'; buf += '</div>'; buf += '</div>'; return buf; }, clipboardInnerHTMLCache: '', clipboardInnerHTML: function () { if (this.clipboardInnerHTMLCache) { return this.clipboardInnerHTMLCache; } var buf = ''; for (var i = 0; i < this.clipboardCount(); i++) { var res = this.clipboard[i]; var pokemon = Tools.getTemplate(res.species); buf += '<div class="result" data-id="' + i + '">'; buf += '<div class="section"><span class="icon" style="' + Tools.getIcon(res.species) + '"></span>'; buf += '<span class="species">' + (pokemon.species === pokemon.baseSpecies ? pokemon.species : (pokemon.baseSpecies + '-<small>' + pokemon.species.substr(pokemon.baseSpecies.length + 1) + '</small>')) + '</span></div>'; buf += '<div class="section"><span class="ability-item">' + (res.ability || '<i>No ability</i>') + '<br />' + (res.item || '<i>No item</i>') + '</span></div>'; buf += '<div class="section no-border">'; for (var j = 0; j < 4; j++) { if (!(j & 1)) { buf += '<span class="moves">'; } buf += (res.moves[j] || '<i>No move</i>') + (!(j & 1) ? '<br />' : ''); if (j & 1) { buf += '</span>'; } } buf += '</div>'; buf += '</div>'; } this.clipboardInnerHTMLCache = buf; return buf; }, clipboardUpdate: function () { this.clipboardInnerHTMLCache = ''; $('.teambuilder-clipboard-data').html(this.clipboardInnerHTML()); }, clipboardExpanded: false, clipboardExpand: function () { var $clipboard = $('.teambuilder-clipboard-data'); $clipboard.animate({height: this.clipboardCount() * 28}, 500, function () { setTimeout(function () { $clipboard.focus(); }, 100); }); setTimeout(function () { this.clipboardExpanded = true; }.bind(this), 10); }, clipboardShrink: function () { var $clipboard = $('.teambuilder-clipboard-data'); $clipboard.animate({height: 26}, 500); setTimeout(function () { this.clipboardExpanded = false; }.bind(this), 10); }, clipboardResultSelect: function (e) { if (!this.clipboardExpanded) return; e.preventDefault(); e.stopPropagation(); var target = +($(e.target).closest('.result').data('id')); if (target === -1) { this.clipboardShrink(); this.clipboardRemoveAll(); return; } this.clipboard.unshift(this.clipboard.splice(target, 1)[0]); this.clipboardUpdate(); this.clipboardShrink(); }, clipboardAdd: function (set) { if (this.clipboard.unshift(set) > 6) { // we don't want the clipboard so big that it lags the teambuilder this.clipboard.pop(); } this.clipboardUpdate(); if (this.clipboardCount() === 1) { var $clipboard = $('.teambuilder-clipboard-container').css('opacity', 0); $clipboard.slideDown(250, function () { $clipboard.animate({opacity: 1}, 250); }); } }, clipboardRemoveAll: function () { this.clipboard = []; var self = this; var $clipboard = $('.teambuilder-clipboard-container'); $clipboard.animate({opacity: 0}, 250, function () { $clipboard.slideUp(250, function () { self.clipboardUpdate(); }); }); }, // copy/import/export/move/delete copySet: function (i, button) { i = +($(button).closest('li').attr('value')); this.clipboardAdd($.extend(true, {}, this.curSetList[i])); button.blur(); }, wasViewingPokemon: false, importSet: function (i, button) { i = +($(button).closest('li').attr('value')); this.wasViewingPokemon = true; if (!this.curSet) { this.wasViewingPokemon = false; this.selectPokemon(i); } this.$('li').find('input, button').prop('disabled', true); this.$chart.hide(); this.$('.teambuilder-pokemon-import') .show() .find('textarea') .val(Storage.exportTeam([this.curSet]).trim()) .focus() .select(); }, closePokemonImport: function (force) { if (!this.wasViewingPokemon) return this.back(); var $li = this.$('li'); var i = +($li.attr('value')); this.$('.teambuilder-pokemon-import').hide(); this.$chart.show(); if (force === true) return this.selectPokemon(i); $li.find('input, button').prop('disabled', false); }, savePokemonImport: function (i) { i = +(this.$('li').attr('value')); var curSet = Storage.importTeam(this.$('.pokemonedit').val())[0]; if (curSet) { this.curSet = curSet; this.curSetList[i] = curSet; } this.closePokemonImport(true); }, moveSet: function (i, button) { i = +($(button).closest('li').attr('value')); app.addPopup(MoveSetPopup, { i: i, team: this.curSetList }); }, deleteSet: function (i, button) { i = +($(button).closest('li').attr('value')); this.deletedSetLoc = i; this.deletedSet = this.curSetList.splice(i, 1)[0]; if (this.curSet) { this.addPokemon(); } else { this.update(); } this.save(); }, undeleteSet: function () { if (this.deletedSet) { var loc = this.deletedSetLoc; this.curSetList.splice(loc, 0, this.deletedSet); this.deletedSet = null; this.deletedSetLoc = -1; this.save(); if (this.curSet) { this.curSetLoc = loc; this.curSet = this.curSetList[loc]; this.curChartName = ''; this.update(); this.updateChart(); } else { this.update(); } } }, /********************************************************* * Set view *********************************************************/ updateSetView: function () { // pokemon var buf = '<div class="pad">'; buf += '<button name="back"><i class="fa fa-chevron-left"></i> Team</button></div>'; buf += '<div class="teambar">'; buf += this.renderTeambar(); buf += '</div>'; // pokemon buf += '<div class="teamchartbox individual">'; buf += '<ol class="teamchart">'; buf += this.renderSet(this.curSet, this.curSetLoc); buf += '</ol>'; buf += '</div>'; // results this.chartPrevSearch = '[init]'; buf += '<div class="teambuilder-results"></div>'; // import/export buf += '<div class="teambuilder-pokemon-import">'; buf += '<div class="pokemonedit-buttons"><button name="closePokemonImport"><i class="fa fa-chevron-left"></i> Back</button> <button name="savePokemonImport"><i class="fa fa-floppy-o"></i> Save</button></div>'; buf += '<textarea class="pokemonedit textbox" rows="14"></textarea>'; buf += '</div>'; this.$el.html('<div class="teamwrapper">' + buf + '</div>'); if ($(window).width() < 640) this.show(); this.$chart = this.$('.teambuilder-results'); this.search = new BattleSearch(this.$chart, this.$chart); var self = this; // fun fact: Backbone DOM events don't support scroll... // I guess scroll doesn't bubble like other events this.$chart.on('scroll', function () { if (self.curChartType in self.searchChartTypes) { self.search.updateScroll(); } }); }, updateSetTop: function () { this.$('.teambar').html(this.renderTeambar()); this.$('.teamchart').first().html(this.renderSet(this.curSet, this.curSetLoc)); }, renderTeambar: function () { var buf = ''; var isAdd = false; if (this.curSetList.length && !this.curSetList[this.curSetList.length - 1].species && this.curSetLoc !== this.curSetList.length - 1) { this.curSetList.splice(this.curSetList.length - 1, 1); } for (var i = 0; i < this.curSetList.length; i++) { var set = this.curSetList[i]; var pokemonicon = '<span class="picon pokemonicon-' + i + '" style="' + Tools.getPokemonIcon(set) + '"></span>'; if (!set.species) { buf += '<button disabled="disabled" class="addpokemon"><i class="fa fa-plus"></i></button> '; isAdd = true; } else if (i == this.curSetLoc) { buf += '<button disabled="disabled" class="pokemon">' + pokemonicon + Tools.escapeHTML(set.name || Tools.getTemplate(set.species).baseSpecies || '<i class="fa fa-plus"></i>') + '</button> '; } else { buf += '<button name="selectPokemon" value="' + i + '" class="pokemon">' + pokemonicon + Tools.escapeHTML(set.name || Tools.getTemplate(set.species).baseSpecies) + '</button> '; } } if (this.curSetList.length < 6 && !isAdd) { buf += '<button name="addPokemon"><i class="fa fa-plus"></i></button> '; } return buf; }, updatePokemonSprite: function () { var set = this.curSet; if (!set) return; this.$('.setchart').attr('style', Tools.getTeambuilderSprite(set, this.curTeam.gen)); this.$('.pokemonicon-' + this.curSetLoc).css('background', Tools.getPokemonIcon(set).substr(11)); var item = Tools.getItem(set.item); if (item.id) { this.$('.setcol-icon .itemicon').css('background', Tools.getItemIcon(item).substr(11)); } else { this.$('.setcol-icon .itemicon').css('background', 'none'); } this.updateStatGraph(); }, updateStatGraph: function () { var set = this.curSet; if (!set) return; var stats = {hp:'', atk:'', def:'', spa:'', spd:'', spe:''}; // stat cell var buf = '<span class="statrow statrow-head"><label></label> <span class="statgraph"></span> <em>EV</em></span>'; var defaultEV = (this.curTeam.gen > 2 ? 0 : 252); for (var stat in stats) { if (stat === 'spd' && this.curTeam.gen === 1) continue; stats[stat] = this.getStat(stat, set); var ev = (set.evs[stat] === undefined ? defaultEV : set.evs[stat]); var evBuf = '<em>' + (ev === defaultEV ? '' : ev) + '</em>'; if (BattleNatures[set.nature] && BattleNatures[set.nature].plus === stat) { evBuf += '<small>+</small>'; } else if (BattleNatures[set.nature] && BattleNatures[set.nature].minus === stat) { evBuf += '<small>&minus;</small>'; } var width = stats[stat] * 75 / 504; if (stat == 'hp') width = stats[stat] * 75 / 704; if (width > 75) width = 75; var color = Math.floor(stats[stat] * 180 / 714); if (color > 360) color = 360; buf += '<span class="statrow"><label>' + BattleStatNames[stat] + '</label> <span class="statgraph"><span style="width:' + width + 'px;background:hsl(' + color + ',40%,75%);"></span></span> ' + evBuf + '</span>'; } this.$('button[name=stats]').html(buf); if (this.curChartType !== 'stats') return; buf = '<div></div>'; for (var stat in stats) { if (stat === 'spd' && this.curTeam.gen === 1) continue; buf += '<div><b>' + stats[stat] + '</b></div>'; } this.$chart.find('.statscol').html(buf); buf = '<div></div>'; var totalev = 0; for (var stat in stats) { if (stat === 'spd' && this.curTeam.gen === 1) continue; var width = stats[stat] * 180 / 504; if (stat == 'hp') width = stats[stat] * 180 / 704; if (width > 179) width = 179; var color = Math.floor(stats[stat] * 180 / 714); if (color > 360) color = 360; buf += '<div><em><span style="width:' + Math.floor(width) + 'px;background:hsl(' + color + ',85%,45%);border-color:hsl(' + color + ',85%,35%)"></span></em></div>'; totalev += (set.evs[stat] || 0); } if (this.curTeam.gen > 2) buf += '<div><em>Remaining:</em></div>'; this.$chart.find('.graphcol').html(buf); if (this.curTeam.gen <= 2) return; var maxEv = 510; if (totalev <= maxEv) { this.$chart.find('.totalev').html('<em>' + (totalev > (maxEv - 2) ? 0 : (maxEv - 2) - totalev) + '</em>'); } else { this.$chart.find('.totalev').html('<b>' + (maxEv - totalev) + '</b>'); } this.$chart.find('select[name=nature]').val(set.nature || 'Serious'); }, curChartType: '', curChartName: '', searchChartTypes: { pokemon: 'pokemon', ability: 'abilities', move: 'moves', item: 'items' }, updateChart: function (pokemonChanged, wasIncomplete) { var type = this.curChartType; app.clearGlobalListeners(); if (type === 'stats') { this.search.qType = null; this.search.qName = null; this.updateStatForm(); return; } if (type === 'details') { this.search.qType = null; this.search.qName = null; this.updateDetailsForm(); return; } var $inputEl = this.$('input[name=' + this.curChartName + ']'); var q = $inputEl.val(); if (pokemonChanged || this.search.qName !== this.curChartName) { var cur = {}; cur[toId(q)] = 1; // make sure selected one is first if (type === 'move') { cur[toId(this.$('input[name=move1]').val())] = 1; cur[toId(this.$('input[name=move2]').val())] = 1; cur[toId(this.$('input[name=move3]').val())] = 1; cur[toId(this.$('input[name=move4]').val())] = 1; } if (type !== this.search.qType) { this.$chart.scrollTop(0); } this.search.$inputEl = $inputEl; this.search.setType(type, this.curTeam.format, this.curSet, cur); this.qInitial = q; this.search.qName = this.curChartName; if (wasIncomplete) { if (this.search.find(q)) { if (this.search.q) this.$chart.find('a').first().addClass('hover'); } } } else if (q !== this.qInitial) { this.qInitial = undefined; if (this.search.find(q)) { if (this.search.q) this.$chart.find('a').first().addClass('hover'); } } }, selectPokemon: function (i) { i = +i; var set = this.curSetList[i]; if (set) { this.curSet = set; this.curSetLoc = i; if (!this.curChartName) { this.curChartName = 'details'; this.curChartType = 'details'; } if (this.curChartType in this.searchChartTypes) { this.update(); this.updateChart(true); this.$('input[name=' + this.curChartName + ']').select(); } else { this.update(); this.updateChart(true); } } }, stats: function (i, button) { if (!this.curSet) this.selectPokemon($(button).closest('li').val()); this.curChartName = 'stats'; this.curChartType = 'stats'; this.updateChart(); }, details: function (i, button) { if (!this.curSet) this.selectPokemon($(button).closest('li').val()); this.curChartName = 'details'; this.curChartType = 'details'; this.updateChart(); }, /********************************************************* * Set stat form *********************************************************/ plus: '', minus: '', smogdexLink: function (template) { var template = Tools.getTemplate(template); var format = this.curTeam && this.curTeam.format; var smogdexid = toId(template.baseSpecies); if (template.isNonstandard) { return 'http://www.smogon.com/cap/pokemon/strategies/' + smogdexid; } if (template.speciesid === 'meowstic') { smogdexid = 'meowstic-m'; } else if (smogdexid === 'rotom' || smogdexid === 'deoxys' || smogdexid === 'kyurem' || smogdexid === 'giratina' || smogdexid === 'shaymin' || smogdexid === 'tornadus' || smogdexid === 'thundurus' || smogdexid === 'landorus' || smogdexid === 'pumpkaboo' || smogdexid === 'gourgeist' || smogdexid === 'arceus' || smogdexid === 'meowstic' || smogdexid === 'hoopa') { if (template.forme) smogdexid += '-' + toId(template.forme); } var generationNumber = 6; if (format.substr(0, 3) === 'gen') { var number = format.charAt(3); if ('1' <= number && number <= '5') { generationNumber = +number; format = format.substr(4); } } var generation = ['rb', 'gs', 'rs', 'dp', 'bw', 'xy'][generationNumber - 1]; if (format === 'battlespotdoubles') { smogdexid += '/vgc15'; } else if (format === 'doublesou' || format === 'doublesuu') { smogdexid += '/doubles'; } else if (format === 'ou' || format === 'uu' || format === 'ru' || format === 'nu' || format === 'pu' || format === 'lc') { smogdexid += '/' + format; } return 'http://smogon.com/dex/' + generation + '/pokemon/' + smogdexid + '/'; }, getBaseStats: function (template) { var baseStats = template.baseStats; var gen = this.curTeam.gen; if (gen < 6) { var overrideStats = BattleTeambuilderTable['gen' + gen].overrideStats[template.id]; if (overrideStats || gen === 1) { baseStats = { hp: template.baseStats.hp, atk: template.baseStats.atk, def: template.baseStats.def, spa: template.baseStats.spa, spd: template.baseStats.spd, spe: template.baseStats.spe }; } if (overrideStats) { if ('hp' in overrideStats) baseStats.hp = overrideStats.hp; if ('atk' in overrideStats) baseStats.atk = overrideStats.atk; if ('def' in overrideStats) baseStats.def = overrideStats.def; if ('spa' in overrideStats) baseStats.spa = overrideStats.spa; if ('spd' in overrideStats) baseStats.spd = overrideStats.spd; if ('spe' in overrideStats) baseStats.spe = overrideStats.spe; } if (gen === 1) baseStats.spd = 0; } return baseStats; }, updateStatForm: function (setGuessed) { var buf = ''; var set = this.curSet; var template = Tools.getTemplate(this.curSet.species); var baseStats = this.getBaseStats(template); buf += '<div class="resultheader"><h3>EVs</h3></div>'; buf += '<div class="statform">'; var role = this.guessRole(); var guessedEVs = {}; var guessedPlus = ''; var guessedMinus = ''; buf += '<p class="suggested"><small>Suggested spread:'; if (role === '?') { buf += ' (Please choose 4 moves to get a suggested spread) (<a target="_blank" href="' + this.smogdexLink(template) + '">Smogon&nbsp;analysis</a>)</small></p>'; } else { guessedEVs = this.guessEVs(role); guessedPlus = guessedEVs.plusStat; delete guessedEVs.plusStat; guessedMinus = guessedEVs.minusStat; delete guessedEVs.minusStat; buf += ' </small><button name="setStatFormGuesses">' + role + ': '; for (var i in guessedEVs) { if (guessedEVs[i]) { var statName = this.curTeam.gen === 1 && i === 'spa' ? 'Spc' : BattleStatNames[i]; buf += '' + guessedEVs[i] + ' ' + statName + ' / '; } } if (guessedPlus && guessedMinus) buf += ' (+' + BattleStatNames[guessedPlus] + ', -' + BattleStatNames[guessedMinus] + ')'; else buf = buf.slice(0, -3); buf += '</button><small> (<a target="_blank" href="' + this.smogdexLink(template) + '">Smogon&nbsp;analysis</a>)</small></p>'; //buf += ' <small>(' + role + ' | bulk: phys ' + Math.round(this.moveCount.physicalBulk/1000) + ' + spec ' + Math.round(this.moveCount.specialBulk/1000) + ' = ' + Math.round(this.moveCount.bulk/1000) + ')</small>'; } if (setGuessed) { set.evs = guessedEVs; this.plus = guessedPlus; this.minus = guessedMinus; this.updateNature(); this.save(); this.updateStatGraph(); this.natureChange(); return; } var stats = {hp:'', atk:'', def:'', spa:'', spd:'', spe:''}; if (this.curTeam.gen === 1) delete stats.spd; if (!set) return; var nature = BattleNatures[set.nature || 'Serious']; if (!nature) nature = {}; // label column buf += '<div class="col labelcol"><div></div>'; buf += '<div><label>HP</label></div><div><label>Attack</label></div><div><label>Defense</label></div><div>'; if (this.curTeam.gen === 1) { buf += '<label>Special</label></div>'; } else { buf += '<label>Sp. Atk.</label></div><div><label>Sp. Def.</label></div>'; } buf += '<div><label>Speed</label></div></div>'; buf += '<div class="col basestatscol"><div><em>Base</em></div>'; for (var i in stats) { buf += '<div><b>' + baseStats[i] + '</b></div>'; } buf += '</div>'; buf += '<div class="col graphcol"><div></div>'; for (var i in stats) { stats[i] = this.getStat(i); var width = stats[i] * 180 / 504; if (i == 'hp') width = Math.floor(stats[i] * 180 / 704); if (width > 179) width = 179; var color = Math.floor(stats[i] * 180 / 714); if (color > 360) color = 360; buf += '<div><em><span style="width:' + Math.floor(width) + 'px;background:hsl(' + color + ',85%,45%);border-color:hsl(' + color + ',85%,35%)"></span></em></div>'; } if (this.curTeam.gen > 2) buf += '<div><em>Remaining:</em></div>'; buf += '</div>'; buf += '<div class="col evcol"><div><strong>EVs</strong></div>'; var totalev = 0; this.plus = ''; this.minus = ''; for (var i in stats) { var width = stats[i] * 200 / 504; if (i == 'hp') width = stats[i] * 200 / 704; if (width > 200) width = 200; var val; if (this.curTeam.gen > 2) { val = '' + (set.evs[i] || ''); } else { val = (set.evs[i] === undefined ? '252' : '' + set.evs[i]); } if (nature.plus === i) { val += '+'; this.plus = i; } if (nature.minus === i) { val += '-'; this.minus = i; } buf += '<div><input type="text" name="stat-' + i + '" value="' + val + '" class="textbox inputform numform" /></div>'; totalev += (set.evs[i] || 0); } if (this.curTeam.gen > 2) { var maxEv = 510; if (totalev <= maxEv) { buf += '<div class="totalev"><em>' + (totalev > (maxEv - 2) ? 0 : (maxEv - 2) - totalev) + '</em></div>'; } else { buf += '<div class="totalev"><b>' + (maxEv - totalev) + '</b></div>'; } } buf += '</div>'; buf += '<div class="col evslidercol"><div></div>'; for (var i in stats) { if (i === 'spd' && this.curTeam.gen === 1) continue; buf += '<div><input type="slider" name="evslider-' + i + '" value="' + Tools.escapeHTML(set.evs[i] === undefined ? (this.curTeam.gen > 2 ? '0' : '252') : '' + set.evs[i]) + '" min="0" max="252" step="4" class="evslider" /></div>'; } buf += '</div>'; if (this.curTeam.gen > 2) { buf += '<div class="col ivcol"><div><strong>IVs</strong></div>'; if (!set.ivs) set.ivs = {}; for (var i in stats) { if (set.ivs[i] === undefined || isNaN(set.ivs[i])) set.ivs[i] = 31; var val = '' + (set.ivs[i]); buf += '<div><input type="number" name="iv-' + i + '" value="' + Tools.escapeHTML(val) + '" class="textbox inputform numform" min="0" max="31" step="1" /></div>'; } var hpType = ''; if (set.moves) { for (var i = 0; i < set.moves.length; i++) { var moveid = toId(set.moves[i]); if (moveid.slice(0, 11) === 'hiddenpower') { hpType = moveid.slice(11); } } } if (hpType) { var hpIVs; switch (hpType) { case 'dark': hpIVs = ['111111']; break; case 'dragon': hpIVs = ['011111', '101111', '110111']; break; case 'ice': hpIVs = ['010111', '100111', '111110']; break; case 'psychic': hpIVs = ['011110', '101110', '110110']; break; case 'electric': hpIVs = ['010110', '100110', '111011']; break; case 'grass': hpIVs = ['011011', '101011', '110011']; break; case 'water': hpIVs = ['100011', '111010']; break; case 'fire': hpIVs = ['101010', '110010']; break; case 'steel': hpIVs = ['100010', '111101']; break; case 'ghost': hpIVs = ['101101', '110101']; break; case 'bug': hpIVs = ['100101', '111100', '101100']; break; case 'rock': hpIVs = ['001100', '110100', '100100']; break; case 'ground': hpIVs = ['000100', '111001', '101001']; break; case 'poison': hpIVs = ['001001', '110001', '100001']; break; case 'flying': hpIVs = ['000001', '111000', '101000']; break; case 'fighting': hpIVs = ['001000', '110000', '100000']; break; } buf += '<div style="margin-left:-80px;text-align:right"><select name="ivspread">'; buf += '<option value="" selected>HP ' + hpType.charAt(0).toUpperCase() + hpType.slice(1) + ' IVs</option>'; var minStat = this.curTeam.gen >= 6 ? 0 : 2; buf += '<optgroup label="min Atk">'; for (var i = 0; i < hpIVs.length; i++) { var spread = ''; for (var j = 0; j < 6; j++) { if (j) spread += '/'; spread += (j === 1 ? minStat : 30) + parseInt(hpIVs[i].charAt(j), 10); } buf += '<option value="' + spread + '">' + spread + '</option>'; } buf += '</optgroup>'; buf += '<optgroup label="min Atk, min Spe">'; for (var i = 0; i < hpIVs.length; i++) { var spread = ''; for (var j = 0; j < 6; j++) { if (j) spread += '/'; spread += (j === 5 || j === 1 ? minStat : 30) + parseInt(hpIVs[i].charAt(j), 10); } buf += '<option value="' + spread + '">' + spread + '</option>'; } buf += '</optgroup>'; buf += '<optgroup label="max all">'; for (var i = 0; i < hpIVs.length; i++) { var spread = ''; for (var j = 0; j < 6; j++) { if (j) spread += '/'; spread += 30 + parseInt(hpIVs[i].charAt(j), 10); } buf += '<option value="' + spread + '">' + spread + '</option>'; } buf += '</optgroup>'; buf += '<optgroup label="min Spe">'; for (var i = 0; i < hpIVs.length; i++) { var spread = ''; for (var j = 0; j < 6; j++) { if (j) spread += '/'; spread += (j === 5 ? minStat : 30) + parseInt(hpIVs[i].charAt(j), 10); } buf += '<option value="' + spread + '">' + spread + '</option>'; } buf += '</optgroup>'; buf += '</select></div>'; } buf += '</div>'; } else { buf += '<div class="col ivcol"><div><strong>DVs</strong></div>'; if (!set.ivs) set.ivs = {}; for (var i in stats) { if (set.ivs[i] === undefined || isNaN(set.ivs[i])) set.ivs[i] = 31; var val = '' + Math.floor(set.ivs[i] / 2); buf += '<div><input type="number" name="iv-' + i + '" value="' + Tools.escapeHTML(val) + '" class="textbox inputform numform" min="0" max="15" step="1" /></div>'; } buf += '</div>'; } buf += '<div class="col statscol"><div></div>'; for (var i in stats) { buf += '<div><b>' + stats[i] + '</b></div>'; } buf += '</div>'; if (this.curTeam.gen > 2) { buf += '<p style="clear:both">Nature: <select name="nature">'; for (var i in BattleNatures) { var curNature = BattleNatures[i]; buf += '<option value="' + i + '"' + (curNature === nature ? 'selected="selected"' : '') + '>' + i; if (curNature.plus) { buf += ' (+' + BattleStatNames[curNature.plus] + ', -' + BattleStatNames[curNature.minus] + ')'; } buf += '</option>'; } buf += '</select></p>'; buf += '<p><em>Protip:</em> You can also set natures by typing "+" and "-" next to a stat.</p>'; } buf += '</div>'; this.$chart.html(buf); var self = this; this.suppressSliderCallback = true; app.clearGlobalListeners(); this.$chart.find('.evslider').slider({ from: 0, to: 252, step: 4, skin: 'round_plastic', onstatechange: function (val) { if (!self.suppressSliderCallback) self.statSlide(val, this); }, callback: function () { self.save(); } }); this.suppressSliderCallback = false; }, setStatFormGuesses: function () { this.updateStatForm(true); }, setSlider: function (stat, val) { this.suppressSliderCallback = true; this.$chart.find('input[name=evslider-' + stat + ']').slider('value', val || 0); this.suppressSliderCallback = false; }, updateNature: function () { var set = this.curSet; if (!set) return; if (this.plus === '' || this.minus === '') { set.nature = 'Serious'; } else { for (var i in BattleNatures) { if (BattleNatures[i].plus === this.plus && BattleNatures[i].minus === this.minus) { set.nature = i; break; } } } }, statChange: function (e) { var inputName = ''; inputName = e.currentTarget.name; var val = Math.abs(parseInt(e.currentTarget.value, 10)); var set = this.curSet; if (!set) return; if (inputName.substr(0, 5) === 'stat-') { // EV // Handle + and - var stat = inputName.substr(5); var lastchar = e.currentTarget.value.charAt(e.target.value.length - 1); var firstchar = e.currentTarget.value.charAt(0); var natureChange = true; if ((lastchar === '+' || firstchar === '+') && stat !== 'hp') { if (this.plus && this.plus !== stat) this.$chart.find('input[name=stat-' + this.plus + ']').val(set.evs[this.plus] || ''); this.plus = stat; } else if ((lastchar === '-' || lastchar === "\u2212" || firstchar === '-' || firstchar === "\u2212") && stat !== 'hp') { if (this.minus && this.minus !== stat) this.$chart.find('input[name=stat-' + this.minus + ']').val(set.evs[this.minus] || ''); this.minus = stat; } else if (this.plus === stat) { this.plus = ''; } else if (this.minus === stat) { this.minus = ''; } else { natureChange = false; } if (natureChange) { this.updateNature(); } // cap if (val > 252) val = 252; if (val < 0 || isNaN(val)) val = 0; if (set.evs[stat] !== val || natureChange) { set.evs[stat] = val; if (this.curTeam.gen <= 2) { if (set.evs['hp'] === undefined) set.evs['hp'] = 252; if (set.evs['atk'] === undefined) set.evs['atk'] = 252; if (set.evs['def'] === undefined) set.evs['def'] = 252; if (set.evs['spa'] === undefined) set.evs['spa'] = 252; if (set.evs['spd'] === undefined) set.evs['spd'] = 252; if (set.evs['spe'] === undefined) set.evs['spe'] = 252; } this.setSlider(stat, val); this.updateStatGraph(); } } else { // IV var stat = inputName.substr(3); if (this.curTeam.gen <= 2) { val *= 2; if (val === 30) val = 31; } if (val > 31 || isNaN(val)) val = 31; if (val < 0) val = 0; if (!set.ivs) set.ivs = {}; if (set.ivs[stat] !== val) { set.ivs[stat] = val; this.updateStatGraph(); } } this.save(); }, statSlide: function (val, slider) { var stat = slider.inputNode[0].name.substr(9); var set = this.curSet; if (!set) return; val = +val; var originalVal = val; var result = this.getStat(stat, set, val); while (val && this.getStat(stat, set, val - 4) == result) val -= 4; if (!this.ignoreEVLimits && set.evs) { var total = 0; for (var i in set.evs) { total += (i === stat ? val : set.evs[i]); } if (total > 508 && val - total + 508 >= 0) { // don't allow dragging beyond 508 EVs val = val - total + 508; // make sure val is a legal value val = +val; if (!val || val <= 0) val = 0; if (val > 252) val = 252; } } // Don't try this at home. // I am a trained professional. if (val !== originalVal) slider.o.pointers[0].set(val); if (!set.evs) set.evs = {}; if (this.curTeam.gen <= 2) { if (set.evs['hp'] === undefined) set.evs['hp'] = 252; if (set.evs['atk'] === undefined) set.evs['atk'] = 252; if (set.evs['def'] === undefined) set.evs['def'] = 252; if (set.evs['spa'] === undefined) set.evs['spa'] = 252; if (set.evs['spd'] === undefined) set.evs['spd'] = 252; if (set.evs['spe'] === undefined) set.evs['spe'] = 252; } set.evs[stat] = val; val = '' + (val || '') + (this.plus === stat ? '+' : '') + (this.minus === stat ? '-' : ''); this.$('input[name=stat-' + stat + ']').val(val); this.updateStatGraph(); }, natureChange: function (e) { var set = this.curSet; if (!set) return; if (e) { set.nature = e.currentTarget.value; } this.plus = ''; this.minus = ''; var nature = BattleNatures[set.nature || 'Serious']; for (var i in BattleStatNames) { var val = '' + (set.evs[i] || ''); if (nature.plus === i) { this.plus = i; val += '+'; } if (nature.minus === i) { this.minus = i; val += '-'; } this.$chart.find('input[name=stat-' + i + ']').val(val); if (!e) this.setSlider(i, set.evs[i]); } this.save(); this.updateStatGraph(); }, ivSpreadChange: function (e) { var set = this.curSet; if (!set) return; var spread = e.currentTarget.value.split('/'); if (!set.ivs) set.ivs = {}; if (spread.length !== 6) return; var stats = ['hp', 'atk', 'def', 'spa', 'spd', 'spe']; for (var i = 0; i < 6; i++) { this.$chart.find('input[name=iv-' + stats[i] + ']').val(spread[i]); set.ivs[stats[i]] = parseInt(spread[i], 10); } $(e.currentTarget).val(''); this.save(); this.updateStatGraph(); }, /********************************************************* * Set details form *********************************************************/ updateDetailsForm: function () { var buf = ''; var set = this.curSet; var template = Tools.getTemplate(set.species); if (!set) return; buf += '<div class="resultheader"><h3>Details</h3></div>'; buf += '<form class="detailsform">'; buf += '<div class="formrow"><label class="formlabel">Level:</label><div><input type="number" min="1" max="100" step="1" name="level" value="' + Tools.escapeHTML(set.level || 100) + '" class="textbox inputform numform" /></div></div>'; if (this.curTeam.gen > 1) { buf += '<div class="formrow"><label class="formlabel">Gender:</label><div>'; if (template.gender && this.curTeam.format !== 'balancedhackmons') { var genderTable = {'M': "Male", 'F': "Female", 'N': "Genderless"}; buf += genderTable[template.gender]; } else { buf += '<label><input type="radio" name="gender" value="M"' + (set.gender === 'M' ? ' checked' : '') + ' /> Male</label> '; buf += '<label><input type="radio" name="gender" value="F"' + (set.gender === 'F' ? ' checked' : '') + ' /> Female</label> '; if (this.curTeam.format !== 'balancedhackmons') { buf += '<label><input type="radio" name="gender" value="N"' + (!set.gender ? ' checked' : '') + ' /> Random</label>'; } else { buf += '<label><input type="radio" name="gender" value="N"' + (set.gender === 'N' ? ' checked' : '') + ' /> Genderless</label>'; } } buf += '</div></div>'; buf += '<div class="formrow"><label class="formlabel">Happiness:</label><div><input type="number" min="0" max="255" step="1" name="happiness" value="' + (typeof set.happiness === 'number' ? set.happiness : 255) + '" class="textbox inputform numform" /></div></div>'; buf += '<div class="formrow"><label class="formlabel">Shiny:</label><div>'; buf += '<label><input type="radio" name="shiny" value="yes"' + (set.shiny ? ' checked' : '') + ' /> Yes</label> '; buf += '<label><input type="radio" name="shiny" value="no"' + (!set.shiny ? ' checked' : '') + ' /> No</label>'; buf += '</div></div>'; } buf += '</form>'; this.$chart.html(buf); }, detailsChange: function () { var set = this.curSet; if (!set) return; // level var level = parseInt(this.$chart.find('input[name=level]').val(), 10); if (!level || level > 100 || level < 1) level = 100; if (level !== 100 || set.level) set.level = level; // happiness var happiness = parseInt(this.$chart.find('input[name=happiness]').val(), 10); if (happiness > 255) happiness = 255; if (happiness < 0) happiness = 255; set.happiness = happiness; if (set.happiness === 255) delete set.happiness; // shiny var shiny = (this.$chart.find('input[name=shiny]:checked').val() === 'yes'); if (shiny) { set.shiny = true; } else { delete set.shiny; } var gender = this.$chart.find('input[name=gender]:checked').val(); if (gender === 'M' || gender === 'F') { set.gender = gender; } else { delete set.gender; } // update details cell var buf = ''; var GenderChart = { 'M': 'Male', 'F': 'Female', 'N': '&mdash;' }; buf += '<span class="detailcell detailcell-first"><label>Level</label>' + (set.level || 100) + '</span>'; if (this.curTeam.gen > 1) { buf += '<span class="detailcell"><label>Gender</label>' + GenderChart[set.gender || 'N'] + '</span>'; buf += '<span class="detailcell"><label>Happiness</label>' + (typeof set.happiness === 'number' ? set.happiness : 255) + '</span>'; buf += '<span class="detailcell"><label>Shiny</label>' + (set.shiny ? 'Yes' : 'No') + '</span>'; } this.$('button[name=details]').html(buf); this.save(); this.updatePokemonSprite(); }, /********************************************************* * Set charts *********************************************************/ chartTypes: { pokemon: 'pokemon', item: 'item', ability: 'ability', move1: 'move', move2: 'move', move3: 'move', move4: 'move', stats: 'stats', details: 'details' }, chartClick: function (e) { if (this.search.addFilter(e.currentTarget)) { this.$('input[name=' + this.curChartName + ']').val('').select(); this.search.find(''); return; } var val = $(e.currentTarget).data('entry').split(':')[1]; if (this.curChartType === 'move' && e.currentTarget.className === 'cur') { // clicked a move, remove it if we already have it var $emptyEl; var moves = []; for (var i = 1; i <= 4; i++) { var $inputEl = this.$('input[name=move' + i + ']'); var curVal = $inputEl.val(); if (curVal === val) { this.unChooseMove(curVal); $inputEl.val(''); delete this.search.cur[toId(val)]; } else if (curVal) { moves.push(curVal); } } if (moves.length < 4) { this.$('input[name=move1]').val(moves[0] || ''); this.$('input[name=move2]').val(moves[1] || ''); this.$('input[name=move3]').val(moves[2] || ''); this.$('input[name=move4]').val(moves[3] || ''); this.$('input[name=move' + (1 + moves.length) + ']').focus(); return; } } this.chartSet(val, true); }, chartKeydown: function (e) { var modifier = (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey || e.cmdKey); if (e.keyCode === 13 || (e.keyCode === 9 && !modifier)) { // enter/tab if (!(this.curChartType in this.searchChartTypes)) return; var $firstResult = this.$chart.find('a.hover'); e.stopPropagation(); e.preventDefault(); if (!$firstResult.length) { this.chartChange(e, true); return; } if (this.search.addFilter($firstResult[0])) { $(e.currentTarget).val('').select(); this.search.find(''); return; } var val = $firstResult.data('entry').split(':')[1]; this.chartSet(val, true); return; } else if (e.keyCode === 38) { // up e.preventDefault(); e.stopPropagation(); var $active = this.$chart.find('a.hover'); if (!$active.length) return this.$chart.find('a').first().addClass('hover'); var $li = $active.parent().prev(); while ($li[0] && $li[0].firstChild.tagName !== 'A') $li = $li.prev(); if ($li[0] && $li.children()[0]) { $active.removeClass('hover'); $active = $li.children(); $active.addClass('hover'); } } else if (e.keyCode === 40) { // down e.preventDefault(); e.stopPropagation(); var $active = this.$chart.find('a.hover'); if (!$active.length) return this.$chart.find('a').first().addClass('hover'); var $li = $active.parent().next(); while ($li[0] && $li[0].firstChild.tagName !== 'A') $li = $li.next(); if ($li[0] && $li.children()[0]) { $active.removeClass('hover'); $active = $li.children(); $active.addClass('hover'); } } else if (e.keyCode === 27 || e.keyCode === 8) { // esc, backspace if (!e.currentTarget.value && this.search.removeFilter()) { this.search.find(''); return; } } else if (e.keyCode === 188) { var $firstResult = this.$chart.find('a').first(); if (!this.search.q) return; if (this.search.addFilter($firstResult[0])) { e.preventDefault(); e.stopPropagation(); $(e.currentTarget).val('').select(); this.search.find(''); return; } } }, chartKeyup: function () { this.updateChart(); }, chartFocus: function (e) { var $target = $(e.currentTarget); var name = e.currentTarget.name; var type = this.chartTypes[name]; var wasIncomplete = false; if ($target.hasClass('incomplete')) { wasIncomplete = true; $target.removeClass('incomplete'); } if (this.curChartName === name) return; if (!this.curSet) { var i = +$target.closest('li').prop('value'); this.curSet = this.curSetList[i]; this.curSetLoc = i; this.update(); if (type === 'stats' || type === 'details') { this.$('button[name=' + name + ']').click(); } else { this.$('input[name=' + name + ']').select(); } return; } this.curChartName = name; this.curChartType = type; this.updateChart(false, wasIncomplete); }, chartChange: function (e, selectNext) { var name = e.currentTarget.name; if (this.curChartName !== name) return; var id = toId(e.currentTarget.value); var val = ''; switch (name) { case 'pokemon': val = (id in BattlePokedex ? BattlePokedex[id].species : ''); break; case 'ability': val = (id in BattleAbilities ? BattleAbilities[id].name : ''); break; case 'item': val = (id in BattleItems ? BattleItems[id].name : ''); break; case 'move1': case 'move2': case 'move3': case 'move4': val = (id in BattleMovedex ? BattleMovedex[id].name : ''); break; } if (!val) { if (name === 'pokemon' || name === 'ability' || id) { $(e.currentTarget).addClass('incomplete'); return; } } this.chartSet(val, selectNext); }, chartSet: function (val, selectNext) { var inputName = this.curChartName; var id = toId(val); this.$('input[name=' + inputName + ']').val(val).removeClass('incomplete'); switch (inputName) { case 'pokemon': this.setPokemon(val, selectNext); break; case 'item': this.curSet.item = val; this.updatePokemonSprite(); if (selectNext) this.$(this.$('input[name=ability]').length ? 'input[name=ability]' : 'input[name=move1]').select(); break; case 'ability': this.curSet.ability = val; if (selectNext) this.$('input[name=move1]').select(); break; case 'move1': this.unChooseMove(this.curSet.moves[0]); this.curSet.moves[0] = val; this.chooseMove(val); if (selectNext) this.$('input[name=move2]').select(); break; case 'move2': if (!this.curSet.moves[0]) this.curSet.moves[0] = ''; this.unChooseMove(this.curSet.moves[1]); this.curSet.moves[1] = val; this.chooseMove(val); if (selectNext) this.$('input[name=move3]').select(); break; case 'move3': if (!this.curSet.moves[0]) this.curSet.moves[0] = ''; if (!this.curSet.moves[1]) this.curSet.moves[1] = ''; this.unChooseMove(this.curSet.moves[2]); this.curSet.moves[2] = val; this.chooseMove(val); if (selectNext) this.$('input[name=move4]').select(); break; case 'move4': if (!this.curSet.moves[0]) this.curSet.moves[0] = ''; if (!this.curSet.moves[1]) this.curSet.moves[1] = ''; if (!this.curSet.moves[2]) this.curSet.moves[2] = ''; this.unChooseMove(this.curSet.moves[3]); this.curSet.moves[3] = val; this.chooseMove(val); if (selectNext) { this.stats(); this.$('button.setstats').focus(); } break; } this.save(); }, unChooseMove: function (move) { var set = this.curSet; if (!move || !set) return; if (move.substr(0, 13) === 'Hidden Power ') { if (set.ivs) { for (var i in set.ivs) { if (set.ivs[i] === 30) delete set.ivs[i]; } } } }, chooseMove: function (move) { var set = this.curSet; if (!set) return; if (move.substr(0, 13) === 'Hidden Power ') { set.ivs = {}; if (this.curTeam.gen > 2) { for (var i in exports.BattleTypeChart[move.substr(13)].HPivs) { set.ivs[i] = exports.BattleTypeChart[move.substr(13)].HPivs[i]; } } else { for (var i in exports.BattleTypeChart[move.substr(13)].HPdvs) { set.ivs[i] = exports.BattleTypeChart[move.substr(13)].HPdvs[i] * 2; } } var moves = this.curSet.moves; for (var i = 0; i < moves.length; ++i) { if (moves[i] === 'Gyro Ball' || moves[i] === 'Trick Room') set.ivs['spe'] = set.ivs['spe'] % 4; } } else if (move === 'Gyro Ball' || move === 'Trick Room') { var hasHiddenPower = false; var moves = this.curSet.moves; for (var i = 0; i < moves.length; ++i) { if (moves[i].substr(0, 13) === 'Hidden Power ') hasHiddenPower = true; } set.ivs['spe'] = hasHiddenPower ? set.ivs['spe'] % 4 : 0; } else if (move === 'Return') { this.curSet.happiness = 255; } else if (move === 'Frustration') { this.curSet.happiness = 0; } }, setPokemon: function (val, selectNext) { var set = this.curSet; var template = Tools.getTemplate(val); var newPokemon = !set.species; if (!template.exists || set.species === template.species) { if (selectNext) this.$('input[name=item]').select(); return; } set.name = ""; set.species = val; if (set.level) delete set.level; if (this.curTeam && this.curTeam.format) { if (this.curTeam.format.substr(0, 10) === 'battlespot' || this.curTeam.format.substr(0, 3) === 'vgc') set.level = 50; if (this.curTeam.format.substr(0, 2) === 'lc' || this.curTeam.format === 'gen5lc' || this.curTeam.format === 'gen4lc') set.level = 5; } if (set.gender) delete set.gender; if (template.gender && template.gender !== 'N') set.gender = template.gender; if (set.happiness) delete set.happiness; if (set.shiny) delete set.shiny; if (this.curTeam.format !== 'balancedhackmons') { set.item = (template.requiredItem || ''); } else { set.item = ''; } set.ability = template.abilities['0']; set.moves = []; set.evs = {}; set.ivs = {}; set.nature = ''; this.updateSetTop(); if (selectNext) this.$(set.item || !this.$('input[name=item]').length ? (this.$('input[name=ability]').length ? 'input[name=ability]' : 'input[name=move1]') : 'input[name=item]').select(); }, /********************************************************* * Utility functions *********************************************************/ // EV guesser guessRole: function () { var set = this.curSet; if (!set) return '?'; if (!set.moves) return '?'; var moveCount = { 'Physical': 0, 'Special': 0, 'PhysicalOffense': 0, 'SpecialOffense': 0, 'PhysicalSetup': 0, 'SpecialSetup': 0, 'Support': 0, 'Setup': 0, 'Restoration': 0, 'Offense': 0, 'Stall': 0, 'SpecialStall': 0, 'PhysicalStall': 0, 'Ultrafast': 0 }; var hasMove = {}; var template = Tools.getTemplate(set.species || set.name); var stats = this.getBaseStats(template); var itemid = toId(set.item); var abilityid = toId(set.ability); if (set.moves.length < 4 && template.id !== 'unown' && template.id !== 'ditto' && this.curTeam.gen > 2) return '?'; for (var i = 0, len = set.moves.length; i < len; i++) { var move = Tools.getMove(set.moves[i]); hasMove[move.id] = 1; if (move.category === 'Status') { if (move.id === 'batonpass' || move.id === 'healingwish' || move.id === 'lunardance') { moveCount['Support']++; } else if (move.id === 'naturepower') { moveCount['Special']++; } else if (move.id === 'protect' || move.id === 'detect' || move.id === 'spikyshield' || move.id === 'kingsshield') { moveCount['Stall']++; } else if (move.id === 'wish') { moveCount['Restoration']++; moveCount['Stall']++; moveCount['Support']++; } else if (move.heal) { moveCount['Restoration']++; moveCount['Stall']++; } else if (move.target === 'self') { if (move.id === 'agility' || move.id === 'rockpolish' || move.id === 'shellsmash' || move.id === 'growth' || move.id === 'workup') { moveCount['PhysicalSetup']++; moveCount['SpecialSetup']++; } else if (move.id === 'dragondance' || move.id === 'swordsdance' || move.id === 'coil' || move.id === 'bulkup' || move.id === 'curse' || move.id === 'bellydrum') { moveCount['PhysicalSetup']++; } else if (move.id === 'nastyplot' || move.id === 'tailglow' || move.id === 'quiverdance' || move.id === 'calmmind' || move.id === 'geomancy') { moveCount['SpecialSetup']++; } if (move.id === 'substitute') moveCount['Stall']++; moveCount['Setup']++; } else { if (move.id === 'toxic' || move.id === 'leechseed' || move.id === 'willowisp') moveCount['Stall']++; moveCount['Support']++; } } else if (move.id === 'counter' || move.id === 'endeavor' || move.id === 'metalburst' || move.id === 'mirrorcoat' || move.id === 'rapidspin') { moveCount['Support']++; } else if (move.id === 'nightshade' || move.id === 'seismictoss' || move.id === 'superfang' || move.id === 'foulplay' || move.id === 'finalgambit') { moveCount['Offense']++; } else if (move.id === 'fellstinger') { moveCount['PhysicalSetup']++; moveCount['Setup']++; } else { moveCount[move.category]++; moveCount['Offense']++; if (move.id === 'knockoff') moveCount['Support']++; if (move.id === 'scald' || move.id === 'voltswitch' || move.id === 'uturn') moveCount[move.category] -= 0.2; } } if (hasMove['batonpass']) moveCount['Support'] += moveCount['Setup']; moveCount['PhysicalAttack'] = moveCount['Physical']; moveCount['Physical'] += moveCount['PhysicalSetup']; moveCount['SpecialAttack'] = moveCount['Special']; moveCount['Special'] += moveCount['SpecialSetup']; if (hasMove['dragondance'] || hasMove['quiverdance']) moveCount['Ultrafast'] = 1; var isFast = (stats.spe > 95); var physicalBulk = (stats.hp + 75) * (stats.def + 87); var specialBulk = (stats.hp + 75) * (stats.spd + 87); if (hasMove['willowisp'] || hasMove['acidarmor'] || hasMove['irondefense'] || hasMove['cottonguard']) { physicalBulk *= 1.6; moveCount['PhysicalStall']++; } else if (hasMove['scald'] || hasMove['bulkup'] || hasMove['coil'] || hasMove['cosmicpower']) { physicalBulk *= 1.3; if (hasMove['scald']) { // partial stall goes in reverse moveCount['SpecialStall']++; } else { moveCount['PhysicalStall']++; } } if (abilityid === 'flamebody') physicalBulk *= 1.1; if (hasMove['calmmind'] || hasMove['quiverdance'] || hasMove['geomancy']) { specialBulk *= 1.3; moveCount['SpecialStall']++; } if (template.id === 'tyranitar') specialBulk *= 1.5; if (hasMove['bellydrum']) { physicalBulk *= 0.6; specialBulk *= 0.6; } if (moveCount['Restoration']) { physicalBulk *= 1.5; specialBulk *= 1.5; } else if (hasMove['painsplit'] && hasMove['substitute']) { // SubSplit isn't generally a stall set moveCount['Stall']--; } else if (hasMove['painsplit'] || hasMove['rest']) { physicalBulk *= 1.4; specialBulk *= 1.4; } if ((hasMove['bodyslam'] || hasMove['thunder']) && abilityid === 'serenegrace' || hasMove['thunderwave']) { physicalBulk *= 1.1; specialBulk *= 1.1; } if ((hasMove['ironhead'] || hasMove['airslash']) && abilityid === 'serenegrace') { physicalBulk *= 1.1; specialBulk *= 1.1; } if (hasMove['gigadrain'] || hasMove['drainpunch'] || hasMove['hornleech']) { physicalBulk *= 1.15; specialBulk *= 1.15; } if (itemid === 'leftovers' || itemid === 'blacksludge') { physicalBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5); specialBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5); } if (hasMove['leechseed']) { physicalBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5); specialBulk *= 1 + 0.1 * (1 + moveCount['Stall'] / 1.5); } if ((itemid === 'flameorb' || itemid === 'toxicorb') && abilityid !== 'magicguard') { if (itemid === 'toxicorb' && abilityid === 'poisonheal') { physicalBulk *= 1 + 0.1 * (2 + moveCount['Stall']); specialBulk *= 1 + 0.1 * (2 + moveCount['Stall']); } else { physicalBulk *= 0.8; specialBulk *= 0.8; } } if (itemid === 'lifeorb') { physicalBulk *= 0.7; specialBulk *= 0.7; } if (abilityid === 'multiscale' || abilityid === 'magicguard' || abilityid === 'regenerator') { physicalBulk *= 1.4; specialBulk *= 1.4; } if (itemid === 'eviolite') { physicalBulk *= 1.5; specialBulk *= 1.5; } if (itemid === 'assaultvest') specialBulk *= 1.5; var bulk = physicalBulk + specialBulk; if (bulk < 46000 && stats.spe >= 70) isFast = true; moveCount['bulk'] = bulk; moveCount['physicalBulk'] = physicalBulk; moveCount['specialBulk'] = specialBulk; if (hasMove['agility'] || hasMove['dragondance'] || hasMove['quiverdance'] || hasMove['rockpolish'] || hasMove['shellsmash'] || hasMove['flamecharge']) { isFast = true; } else if (abilityid === 'unburden' || abilityid === 'speedboost' || abilityid === 'motordrive') { isFast = true; moveCount['Ultrafast'] = 1; } else if (abilityid === 'chlorophyll' || abilityid === 'swiftswim' || abilityid === 'sandrush') { isFast = true; moveCount['Ultrafast'] = 2; } if (hasMove['agility'] || hasMove['shellsmash'] || hasMove['autotomize'] || hasMove['shiftgear'] || hasMove['rockpolish']) moveCount['Ultrafast'] = 2; moveCount['Fast'] = isFast ? 1 : 0; this.moveCount = moveCount; this.hasMove = hasMove; if (template.id === 'ditto') return abilityid === 'imposter' ? 'Physically Defensive' : 'Fast Bulky Support'; if (template.id === 'shedinja') return 'Fast Physical Sweeper'; if (itemid === 'choiceband' && moveCount['PhysicalAttack'] >= 2) { if (!isFast) return 'Bulky Band'; return 'Fast Band'; } else if (itemid === 'choicespecs' && moveCount['SpecialAttack'] >= 2) { if (!isFast) return 'Bulky Specs'; return 'Fast Specs'; } else if (itemid === 'choicescarf') { if (moveCount['PhysicalAttack'] === 0) return 'Special Scarf'; if (moveCount['SpecialAttack'] === 0) return 'Physical Scarf'; if (moveCount['PhysicalAttack'] > moveCount['SpecialAttack']) return 'Physical Biased Mixed Scarf'; if (moveCount['PhysicalAttack'] < moveCount['SpecialAttack']) return 'Special Biased Mixed Scarf'; if (stats.atk < stats.spa) return 'Special Biased Mixed Scarf'; return 'Physical Biased Mixed Scarf'; } if (template.id === 'unown') return 'Fast Special Sweeper'; if (moveCount['PhysicalStall'] && moveCount['Restoration']) { return 'Specially Defensive'; } if (moveCount['SpecialStall'] && moveCount['Restoration'] && itemid !== 'lifeorb') { return 'Physically Defensive'; } var offenseBias = ''; if (stats.spa > stats.atk && moveCount['Special'] > 1) offenseBias = 'Special'; else if (stats.atk > stats.spa && moveCount['Physical'] > 1) offenseBias = 'Physical'; else if (moveCount['Special'] > moveCount['Physical']) offenseBias = 'Special'; else offenseBias = 'Physical'; var offenseStat = stats[offenseBias === 'Special' ? 'spa' : 'atk']; if (moveCount['Stall'] + moveCount['Support'] / 2 <= 2 && bulk < 135000 && moveCount[offenseBias] >= 1.5) { if (isFast) { if (bulk > 80000 && !moveCount['Ultrafast']) return 'Bulky ' + offenseBias + ' Sweeper'; return 'Fast ' + offenseBias + ' Sweeper'; } else { if (moveCount[offenseBias] >= 3 || moveCount['Stall'] <= 0) { return 'Bulky ' + offenseBias + ' Sweeper'; } } } if (isFast && abilityid !== 'prankster') { if (stats.spe > 100 || bulk < 55000 || moveCount['Ultrafast']) { return 'Fast Bulky Support'; } } if (moveCount['SpecialStall']) return 'Physically Defensive'; if (moveCount['PhysicalStall']) return 'Specially Defensive'; if (template.id === 'blissey' || template.id === 'chansey') return 'Physically Defensive'; if (specialBulk >= physicalBulk) return 'Specially Defensive'; return 'Physically Defensive'; }, ensureMinEVs: function (evs, stat, min, evTotal) { if (!evs[stat]) evs[stat] = 0; var diff = min - evs[stat]; if (diff <= 0) return evTotal; if (evTotal <= 504) { var change = Math.min(508 - evTotal, diff); evTotal += change; evs[stat] += change; diff -= change; } if (diff <= 0) return evTotal; var evPriority = {def: 1, spd: 1, hp: 1, atk: 1, spa: 1, spe: 1}; for (var i in evPriority) { if (i === stat) continue; if (evs[i] && evs[i] > 128) { evs[i] -= diff; evs[stat] += diff; return evTotal; } } return evTotal; // can't do it :( }, ensureMaxEVs: function (evs, stat, min, evTotal) { if (!evs[stat]) evs[stat] = 0; var diff = evs[stat] - min; if (diff <= 0) return evTotal; evs[stat] -= diff; evTotal -= diff; return evTotal; // can't do it :( }, guessEVs: function (role) { var set = this.curSet; if (!set) return {}; var template = Tools.getTemplate(set.species || set.name); var stats = this.getBaseStats(template); var hasMove = this.hasMove; var moveCount = this.moveCount; var evs = {}; var plusStat = ''; var minusStat = ''; var statChart = { 'Bulky Band': ['atk', 'hp'], 'Fast Band': ['spe', 'atk'], 'Bulky Specs': ['spa', 'hp'], 'Fast Specs': ['spe', 'spa'], 'Physical Scarf': ['spe', 'atk'], 'Special Scarf': ['spe', 'spa'], 'Physical Biased Mixed Scarf': ['spe', 'atk'], 'Special Biased Mixed Scarf': ['spe', 'spa'], 'Fast Physical Sweeper': ['spe', 'atk'], 'Fast Special Sweeper': ['spe', 'spa'], 'Bulky Physical Sweeper': ['atk', 'hp'], 'Bulky Special Sweeper': ['spa', 'hp'], 'Fast Bulky Support': ['spe', 'hp'], 'Physically Defensive': ['def', 'hp'], 'Specially Defensive': ['spd', 'hp'] }; plusStat = statChart[role][0]; if (role === 'Fast Bulky Support') moveCount['Ultrafast'] = 0; if (plusStat === 'spe' && (moveCount['Ultrafast'] || evs['spe'] < 252)) { if (statChart[role][1] === 'atk' || statChart[role][1] == 'spa') { plusStat = statChart[role][1]; } else if (moveCount['Physical'] >= 3) { plusStat = 'atk'; } else if (stats.spd > stats.def) { plusStat = 'spd'; } else { plusStat = 'def'; } } if (this.curTeam && this.ignoreEVLimits) { evs = {hp:252, atk:252, def:252, spa:252, spd:252, spe:252}; if (hasMove['gyroball'] || hasMove['trickroom']) delete evs.spe; if (this.curTeam.gen === 1) delete evs.spd; if (this.curTeam.gen < 3) return evs; } else { if (!statChart[role]) return {}; var evTotal = 0; var i = statChart[role][0]; var stat = this.getStat(i, null, 252, plusStat === i ? 1.1 : 1.0); var ev = 252; while (ev > 0 && stat <= this.getStat(i, null, ev - 4, plusStat === i ? 1.1 : 1.0)) ev -= 4; evs[i] = ev; evTotal += ev; var i = statChart[role][1]; if (i === 'hp' && set.level && set.level < 20) i = 'spd'; var stat = this.getStat(i, null, 252, plusStat === i ? 1.1 : 1.0); var ev = 252; if (i === 'hp' && (hasMove['substitute'] || hasMove['transform']) && stat == Math.floor(stat / 4) * 4) stat -= 1; while (ev > 0 && stat <= this.getStat(i, null, ev - 4, plusStat === i ? 1.1 : 1.0)) ev -= 4; evs[i] = ev; evTotal += ev; if (set.item !== 'Leftovers' && set.item !== 'Black Sludge') { var hpParity = 1; // 1 = should be odd, 0 = should be even if ((hasMove['substitute'] || hasMove['bellydrum']) && (set.item || '').slice(-5) === 'Berry') { hpParity = 0; } var hp = evs['hp'] || 0; while (hp < 252 && evTotal < 508 && this.getStat('hp', null, hp, 1) % 2 !== hpParity) { hp += 4; evTotal += 4; } while (hp > 0 && this.getStat('hp', null, hp, 1) % 2 !== hpParity) { hp -= 4; evTotal -= 4; } while (hp > 0 && this.getStat('hp', null, hp - 4, 1) % 2 === hpParity) { hp -= 4; evTotal -= 4; } if (hp || evs['hp']) evs['hp'] = hp; } if (template.id === 'tentacruel') evTotal = this.ensureMinEVs(evs, 'spe', 16, evTotal); if (template.id === 'skarmory') evTotal = this.ensureMinEVs(evs, 'spe', 24, evTotal); if (template.id === 'jirachi') evTotal = this.ensureMinEVs(evs, 'spe', 32, evTotal); if (template.id === 'celebi') evTotal = this.ensureMinEVs(evs, 'spe', 36, evTotal); if (template.id === 'volcarona') evTotal = this.ensureMinEVs(evs, 'spe', 52, evTotal); if (template.id === 'gliscor') evTotal = this.ensureMinEVs(evs, 'spe', 72, evTotal); if (stats.spe == 97) evTotal = this.ensureMaxEVs(evs, 'spe', 220, evTotal); if (template.id === 'dragonite' && evs['hp']) evTotal = this.ensureMaxEVs(evs, 'spe', 220, evTotal); if (evTotal < 508) { var remaining = 508 - evTotal; if (remaining > 252) remaining = 252; i = null; if (!evs['atk'] && moveCount['PhysicalAttack'] >= 1) { i = 'atk'; } else if (!evs['spa'] && moveCount['SpecialAttack'] >= 1) { i = 'spa'; } else if (stats.hp == 1 && !evs['def']) { i = 'def'; } else if (stats.def === stats.spd && !evs['spd']) { i = 'spd'; } else if (!evs['spd']) { i = 'spd'; } else if (!evs['def']) { i = 'def'; } if (i) { ev = remaining; stat = this.getStat(i, null, ev); while (ev > 0 && stat === this.getStat(i, null, ev - 4)) ev -= 4; if (ev) evs[i] = ev; remaining -= ev; } if (remaining && !evs['spe']) { ev = remaining; stat = this.getStat('spe', null, ev); while (ev > 0 && stat === this.getStat('spe', null, ev - 4)) ev -= 4; if (ev) evs['spe'] = ev; } } } if (hasMove['gyroball'] || hasMove['trickroom']) { minusStat = 'spe'; } else if (!moveCount['PhysicalAttack']) { minusStat = 'atk'; } else if (moveCount['SpecialAttack'] < 1) { minusStat = 'spa'; } else if (moveCount['PhysicalAttack'] < 1) { minusStat = 'atk'; } else if (stats.def > stats.spd) { minusStat = 'spd'; } else { minusStat = 'def'; } if (plusStat === minusStat) { minusStat = (plusStat === 'spe' ? 'spd' : 'spe'); } evs.plusStat = plusStat; evs.minusStat = minusStat; return evs; }, // Stat calculator getStat: function (stat, set, evOverride, natureOverride) { if (!set) set = this.curSet; if (!set) return 0; if (!set.ivs) set.ivs = { hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31 }; if (!set.evs) set.evs = {}; // do this after setting set.evs because it's assumed to exist // after getStat is run var template = Tools.getTemplate(set.species); if (!template.exists) return 0; if (!set.level) set.level = 100; if (typeof set.ivs[stat] === 'undefined') set.ivs[stat] = 31; var baseStat = (this.getBaseStats(template))[stat]; var iv = (set.ivs[stat] || 0); if (this.curTeam.gen <= 2) iv &= 30; var ev = set.evs[stat]; if (evOverride !== undefined) ev = evOverride; if (ev === undefined) ev = (this.curTeam.gen > 2 ? 0 : 252); if (stat === 'hp') { if (baseStat === 1) return 1; return Math.floor(Math.floor(2 * baseStat + iv + Math.floor(ev / 4) + 100) * set.level / 100 + 10); } var val = Math.floor(Math.floor(2 * baseStat + iv + Math.floor(ev / 4)) * set.level / 100 + 5); if (natureOverride) { val *= natureOverride; } else if (BattleNatures[set.nature] && BattleNatures[set.nature].plus === stat) { val *= 1.1; } else if (BattleNatures[set.nature] && BattleNatures[set.nature].minus === stat) { val *= 0.9; } return Math.floor(val); }, // initialization getGen: function (format) { format = '' + format; if (format.substr(0, 3) !== 'gen') return 6; return parseInt(format.substr(3, 1), 10) || 6; }, destroy: function () { app.clearGlobalListeners(); Room.prototype.destroy.call(this); } }); var MoveSetPopup = exports.MoveSetPopup = Popup.extend({ initialize: function (data) { var buf = '<ul class="popupmenu">'; this.i = data.i; this.team = data.team; for (var i = 0; i < data.team.length; i++) { var set = data.team[i]; if (i !== data.i && i !== data.i + 1) { buf += '<li><button name="moveHere" value="' + i + '"><i class="fa fa-arrow-right"></i> Move here</button></li>'; } buf += '<li' + (i === data.i ? ' style="opacity:.3"' : ' style="opacity:.6"') + '><span class="pokemonicon" style="display:inline-block;vertical-align:middle;' + Tools.getIcon(set) + '"></span> ' + Tools.escapeHTML(set.name) + '</li>'; } if (i !== data.i && i !== data.i + 1) { buf += '<li><button name="moveHere" value="' + i + '"><i class="fa fa-arrow-right"></i> Move here</button></li>'; } buf += '</ul>'; this.$el.html(buf); }, moveHere: function (i) { this.close(); i = +i; var movedSet = this.team.splice(this.i, 1)[0]; if (i > this.i) i--; this.team.splice(i, 0, movedSet); app.rooms['teambuilder'].save(); if (app.rooms['teambuilder'].curSet) { app.rooms['teambuilder'].curSetLoc = i; app.rooms['teambuilder'].update(); app.rooms['teambuilder'].updateChart(); } else { app.rooms['teambuilder'].update(); } } }); var DeleteFolderPopup = this.DeleteFolderPopup = Popup.extend({ type: 'semimodal', initialize: function (data) { this.room = data.room; this.folder = data.folder; var buf = '<form><p>Remove "' + data.folder.slice(0, -1) + '"?</p><p><label><input type="checkbox" name="addname" /> Add "' + Tools.escapeHTML(this.folder.slice(0, -1)) + '" before team names</label></p>'; buf += '<p><button type="submit"><strong>Remove (keep teams)</strong></button> <!--button name="removeDelete"><strong>Remove (delete teams)</strong></button--> <button name="close" class="autofocus">Cancel</button></p></form>'; this.$el.html(buf); }, submit: function (data) { this.room.deleteFolder(this.folder, !!this.$('input[name=addname]')[0].checked); this.close(); } }); })(window, jQuery);
Fix EV recommender for Salac Berry
js/client-teambuilder.js
Fix EV recommender for Salac Berry
<ide><path>s/client-teambuilder.js <ide> } else if (abilityid === 'chlorophyll' || abilityid === 'swiftswim' || abilityid === 'sandrush') { <ide> isFast = true; <ide> moveCount['Ultrafast'] = 2; <add> } else if (itemid === 'salacberry') { <add> isFast = true; <ide> } <ide> if (hasMove['agility'] || hasMove['shellsmash'] || hasMove['autotomize'] || hasMove['shiftgear'] || hasMove['rockpolish']) moveCount['Ultrafast'] = 2; <ide> moveCount['Fast'] = isFast ? 1 : 0;
Java
apache-2.0
345f6d6f9d3c4c9a061e73347b5a22698b751533
0
apache/jmeter,benbenw/jmeter,benbenw/jmeter,etnetera/jmeter,benbenw/jmeter,etnetera/jmeter,etnetera/jmeter,apache/jmeter,ham1/jmeter,apache/jmeter,etnetera/jmeter,ham1/jmeter,etnetera/jmeter,ham1/jmeter,ham1/jmeter,apache/jmeter,benbenw/jmeter,apache/jmeter,ham1/jmeter
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * */ package org.apache.jmeter.gui.util; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import javax.swing.JTextField; import javax.swing.SwingUtilities; /** * This is Date mask control. Using this control we can pop up our date in the * text field. And this control is developed basically for JDK1.3 and lower * version support. This control is similar to JSpinner control this is * available in JDK1.4 and above only. * <p> * This will set the date "yyyy/MM/dd HH:mm:ss" in this format only. * </p> */ public class JDateField extends JTextField { private static final long serialVersionUID = 240L; // Datefields are not thread-safe private final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); // $NON-NLS-1$ /* * The following array must agree with dateFormat * * It is used to translate the positions in the buffer to the values used by * the Calendar class for the field id. * * Current format: MM/DD/YYYY HH:MM:SS 01234567890123456789 ^buffer * positions */ private static final int[] FIELD_POSITIONS = { Calendar.YEAR, // Y Calendar.YEAR, // Y Calendar.YEAR, // Y Calendar.YEAR, // Y Calendar.YEAR, // sp Calendar.MONTH, // M Calendar.MONTH, // M Calendar.MONTH, // / Calendar.DAY_OF_MONTH, // D Calendar.DAY_OF_MONTH, // D Calendar.DAY_OF_MONTH, // / Calendar.HOUR_OF_DAY, // H Calendar.HOUR_OF_DAY, // H Calendar.HOUR_OF_DAY, // : Calendar.MINUTE, // M Calendar.MINUTE, // M Calendar.MINUTE, // : Calendar.SECOND, // S Calendar.SECOND, // S Calendar.SECOND // end }; /** * Create a DateField with the specified date. * * @param date * The {@link Date} to be used */ public JDateField(Date date) { super(20); this.addKeyListener(new KeyFocus()); this.addFocusListener(new FocusClass()); String myString = dateFormat.format(date); setText(myString); } // Dummy constructor to allo JUnit tests to work public JDateField() { this(new Date()); } /** * Set the date to the Date mask control. * * @param date * The {@link Date} to be set */ public void setDate(Date date) { setText(dateFormat.format(date)); } /** * Get the date from the Date mask control. * * @return The currently set date */ public Date getDate() { try { return dateFormat.parse(getText()); } catch (ParseException e) { return new Date(); } } /* * Convert position in buffer to Calendar type Assumes that pos >=0 (which * is true for getCaretPosition()) */ private static int posToField(int pos) { if (pos >= FIELD_POSITIONS.length) { // if beyond the end pos = FIELD_POSITIONS.length - 1; // then set to the end } return FIELD_POSITIONS[pos]; } /** * Converts a date/time to a calendar using the defined format */ private Calendar parseDate(String datetime) { Calendar c = Calendar.getInstance(); try { Date dat = dateFormat.parse(datetime); c.setTime(dat); } catch (ParseException e) { // Do nothing; the current time will be returned } return c; } /* * Update the current field. The addend is only expected to be +1/-1, but * other values will work. N.B. the roll() method only supports changes by a * single unit - up or down */ private void update(int addend, boolean shifted) { Calendar c = parseDate(getText()); int pos = getCaretPosition(); int field = posToField(pos); if (shifted) { c.roll(field, true); } else { c.add(field, addend); } String newDate = dateFormat.format(c.getTime()); setText(newDate); if (pos > newDate.length()) { pos = newDate.length(); } final int newPosition = pos; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { setCaretPosition(newPosition);// Restore position } }); } class KeyFocus extends KeyAdapter { KeyFocus() {} @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) { update(1, e.isShiftDown()); } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { update(-1, e.isShiftDown()); } } } class FocusClass implements FocusListener { FocusClass() {} @Override public void focusGained(FocusEvent e) {} @Override public void focusLost(FocusEvent e) { if(getText() == null || getText().isEmpty()) { return; } try { dateFormat.parse(getText()); } catch (ParseException e1) { requestFocusInWindow(); } } } }
src/core/org/apache/jmeter/gui/util/JDateField.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * */ package org.apache.jmeter.gui.util; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import javax.swing.JTextField; import javax.swing.SwingUtilities; /** * This is Date mask control. Using this control we can pop up our date in the * text field. And this control is developed basically for JDK1.3 and lower * version support. This control is similar to JSpinner control this is * available in JDK1.4 and above only. * <p> * This will set the date "yyyy/MM/dd HH:mm:ss" in this format only. * </p> */ public class JDateField extends JTextField { private static final long serialVersionUID = 240L; // Datefields are not thread-safe private final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); // $NON-NLS-1$ /* * The following array must agree with dateFormat * * It is used to translate the positions in the buffer to the values used by * the Calendar class for the field id. * * Current format: MM/DD/YYYY HH:MM:SS 01234567890123456789 ^buffer * positions */ private static final int fieldPositions[] = { Calendar.YEAR, // Y Calendar.YEAR, // Y Calendar.YEAR, // Y Calendar.YEAR, // Y Calendar.YEAR, // sp Calendar.MONTH, // M Calendar.MONTH, // M Calendar.MONTH, // / Calendar.DAY_OF_MONTH, // D Calendar.DAY_OF_MONTH, // D Calendar.DAY_OF_MONTH, // / Calendar.HOUR_OF_DAY, // H Calendar.HOUR_OF_DAY, // H Calendar.HOUR_OF_DAY, // : Calendar.MINUTE, // M Calendar.MINUTE, // M Calendar.MINUTE, // : Calendar.SECOND, // S Calendar.SECOND, // S Calendar.SECOND // end }; /** * Create a DateField with the specified date. * * @param date * The {@link Date} to be used */ public JDateField(Date date) { super(20); this.addKeyListener(new KeyFocus()); this.addFocusListener(new FocusClass()); String myString = dateFormat.format(date); setText(myString); } // Dummy constructor to allo JUnit tests to work public JDateField() { this(new Date()); } /** * Set the date to the Date mask control. * * @param date * The {@link Date} to be set */ public void setDate(Date date) { setText(dateFormat.format(date)); } /** * Get the date from the Date mask control. * * @return The currently set date */ public Date getDate() { try { return dateFormat.parse(getText()); } catch (ParseException e) { return new Date(); } } /* * Convert position in buffer to Calendar type Assumes that pos >=0 (which * is true for getCaretPosition()) */ private static int posToField(int pos) { if (pos >= fieldPositions.length) { // if beyond the end pos = fieldPositions.length - 1; // then set to the end } return fieldPositions[pos]; } /** * Converts a date/time to a calendar using the defined format */ private Calendar parseDate(String datetime) { Calendar c = Calendar.getInstance(); try { Date dat = dateFormat.parse(datetime); c.setTime(dat); } catch (ParseException e) { // Do nothing; the current time will be returned } return c; } /* * Update the current field. The addend is only expected to be +1/-1, but * other values will work. N.B. the roll() method only supports changes by a * single unit - up or down */ private void update(int addend, boolean shifted) { Calendar c = parseDate(getText()); int pos = getCaretPosition(); int field = posToField(pos); if (shifted) { c.roll(field, true); } else { c.add(field, addend); } String newDate = dateFormat.format(c.getTime()); setText(newDate); if (pos > newDate.length()) { pos = newDate.length(); } final int newPosition = pos; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { setCaretPosition(newPosition);// Restore position } }); } class KeyFocus extends KeyAdapter { KeyFocus() {} @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) { update(1, e.isShiftDown()); } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { update(-1, e.isShiftDown()); } } } class FocusClass implements FocusListener { FocusClass() {} @Override public void focusGained(FocusEvent e) {} @Override public void focusLost(FocusEvent e) { if(getText() == null || getText().isEmpty()) { return; } try { dateFormat.parse(getText()); } catch (ParseException e1) { requestFocusInWindow(); } } } }
Naming convention for static fields Patch by B. Wiart https://github.com/apache/jmeter/pull/108 git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1729728 13f79535-47bb-0310-9956-ffa450edef68 Former-commit-id: 4e36f4d3da130c3e81ae1bc452beca0cfd55b9f1
src/core/org/apache/jmeter/gui/util/JDateField.java
Naming convention for static fields Patch by B. Wiart https://github.com/apache/jmeter/pull/108
<ide><path>rc/core/org/apache/jmeter/gui/util/JDateField.java <ide> * Current format: MM/DD/YYYY HH:MM:SS 01234567890123456789 ^buffer <ide> * positions <ide> */ <del> private static final int fieldPositions[] = { <add> private static final int[] FIELD_POSITIONS = { <ide> Calendar.YEAR, // Y <ide> Calendar.YEAR, // Y <ide> Calendar.YEAR, // Y <ide> * is true for getCaretPosition()) <ide> */ <ide> private static int posToField(int pos) { <del> if (pos >= fieldPositions.length) { // if beyond the end <del> pos = fieldPositions.length - 1; // then set to the end <del> } <del> return fieldPositions[pos]; <add> if (pos >= FIELD_POSITIONS.length) { // if beyond the end <add> pos = FIELD_POSITIONS.length - 1; // then set to the end <add> } <add> return FIELD_POSITIONS[pos]; <ide> } <ide> <ide> /**
Java
apache-2.0
e119f59893df3237ca47371a1b39fb57b735d7cf
0
eFaps/eFaps-Kernel,ov3rflow/eFaps-Kernel
/* * Copyright 2003 - 2011 The eFaps Team * * 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. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.update.schema.ui; import java.net.URL; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.efaps.update.LinkInstance; /** * @author The eFaps Team * @version $Id$ * TODO: description */ public class MenuUpdate extends CommandUpdate { /** Link from menu to child command / menu. */ private static final Link LINK2CHILD = new OrderedLink("Admin_UI_Menu2Command", "FromMenu", "Admin_UI_Command", "ToCommand"); /** Link from menu to type as type tree menu. */ private static final Link LINK2TYPE = new Link("Admin_UI_LinkIsTypeTreeFor", "From", "Admin_DataModel_Type", "To"); /** * The links for the Menu to be updated. */ protected static final Set<Link> ALLLINKS = new HashSet<Link>(); static { MenuUpdate.ALLLINKS.add(MenuUpdate.LINK2CHILD); MenuUpdate.ALLLINKS.add(MenuUpdate.LINK2TYPE); MenuUpdate.ALLLINKS.addAll(CommandUpdate.ALLLINKS); } /** * @param _url URL to the Configuration Item. */ public MenuUpdate(final URL _url) { super(_url, "Admin_UI_Menu", MenuUpdate.ALLLINKS); } /** * * @param _url URL to the Configuration Item. * @param _typeName Name of the type * @param _allLinks link definitions */ protected MenuUpdate(final URL _url, final String _typeName, final Set<Link> _allLinks) { super(_url, _typeName, _allLinks); } /** * Creates new instance of class {@link MenuDefinition}. * * @return new definition instance * @see MenuDefinition */ @Override protected AbstractDefinition newDefinition() { return new MenuDefinition(); } /** * */ protected class MenuDefinition extends CommandDefinition { @Override protected void readXML(final List<String> _tags, final Map<String, String> _attributes, final String _text) { final String value = _tags.get(0); if ("childs".equals(value)) { if (_tags.size() > 1) { final String subValue = _tags.get(1); if ("child".equals(subValue)) { // assigns / removes child commands / menus to this menu if (!"remove".equals(_attributes.get("modus"))) { final LinkInstance child = new LinkInstance(_text); final String order = _attributes.get("order"); if (order != null) { child.setOrder(Integer.parseInt(order)); } addLink(MenuUpdate.LINK2CHILD, child); } } else { super.readXML(_tags, _attributes, _text); } } } else if ("type".equals(value)) { // assigns a type the menu for which this menu instance is the type // tree menu addLink(MenuUpdate.LINK2TYPE, new LinkInstance(_text)); } else { super.readXML(_tags, _attributes, _text); } } } }
src/main/java/org/efaps/update/schema/ui/MenuUpdate.java
/* * Copyright 2003 - 2011 The eFaps Team * * 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. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.update.schema.ui; import java.net.URL; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.efaps.update.LinkInstance; /** * @author The eFaps Team * @version $Id$ * TODO: description */ public class MenuUpdate extends CommandUpdate { /** * The links for the Menu to be updated. */ protected static final Set<Link> ALLLINKS = new HashSet<Link>(); static { MenuUpdate.ALLLINKS.add(MenuUpdate.LINK2CHILD); MenuUpdate.ALLLINKS.add(MenuUpdate.LINK2TYPE); MenuUpdate.ALLLINKS.addAll(CommandUpdate.ALLLINKS); } /** Link from menu to child command / menu. */ private static final Link LINK2CHILD = new OrderedLink("Admin_UI_Menu2Command", "FromMenu", "Admin_UI_Command", "ToCommand"); /** Link from menu to type as type tree menu. */ private static final Link LINK2TYPE = new Link("Admin_UI_LinkIsTypeTreeFor", "From", "Admin_DataModel_Type", "To"); /** * @param _url URL to the Configuration Item. */ public MenuUpdate(final URL _url) { super(_url, "Admin_UI_Menu", MenuUpdate.ALLLINKS); } /** * * @param _url URL to the Configuration Item. * @param _typeName Name of the type * @param _allLinks link definitions */ protected MenuUpdate(final URL _url, final String _typeName, final Set<Link> _allLinks) { super(_url, _typeName, _allLinks); } /** * Creates new instance of class {@link MenuDefinition}. * * @return new definition instance * @see MenuDefinition */ @Override protected AbstractDefinition newDefinition() { return new MenuDefinition(); } /** * */ protected class MenuDefinition extends CommandDefinition { @Override protected void readXML(final List<String> _tags, final Map<String, String> _attributes, final String _text) { final String value = _tags.get(0); if ("childs".equals(value)) { if (_tags.size() > 1) { final String subValue = _tags.get(1); if ("child".equals(subValue)) { // assigns / removes child commands / menus to this menu if (!"remove".equals(_attributes.get("modus"))) { final LinkInstance child = new LinkInstance(_text); final String order = _attributes.get("order"); if (order != null) { child.setOrder(Integer.parseInt(order)); } addLink(MenuUpdate.LINK2CHILD, child); } } else { super.readXML(_tags, _attributes, _text); } } } else if ("type".equals(value)) { // assigns a type the menu for which this menu instance is the type // tree menu addLink(MenuUpdate.LINK2TYPE, new LinkInstance(_text)); } else { super.readXML(_tags, _attributes, _text); } } } }
- corrected update via rest bug. git-svn-id: f6286d974079baf467dd211e2f0de75b0d75837f@7027 fee104cc-1dfa-8c0f-632d-d3b7e6b59fb0
src/main/java/org/efaps/update/schema/ui/MenuUpdate.java
- corrected update via rest bug.
<ide><path>rc/main/java/org/efaps/update/schema/ui/MenuUpdate.java <ide> public class MenuUpdate <ide> extends CommandUpdate <ide> { <del> /** <del> * The links for the Menu to be updated. <del> */ <del> protected static final Set<Link> ALLLINKS = new HashSet<Link>(); <del> static { <del> MenuUpdate.ALLLINKS.add(MenuUpdate.LINK2CHILD); <del> MenuUpdate.ALLLINKS.add(MenuUpdate.LINK2TYPE); <del> MenuUpdate.ALLLINKS.addAll(CommandUpdate.ALLLINKS); <del> } <ide> <ide> /** Link from menu to child command / menu. */ <ide> private static final Link LINK2CHILD = new OrderedLink("Admin_UI_Menu2Command", <ide> private static final Link LINK2TYPE = new Link("Admin_UI_LinkIsTypeTreeFor", <ide> "From", <ide> "Admin_DataModel_Type", "To"); <add> <add> /** <add> * The links for the Menu to be updated. <add> */ <add> protected static final Set<Link> ALLLINKS = new HashSet<Link>(); <add> static { <add> MenuUpdate.ALLLINKS.add(MenuUpdate.LINK2CHILD); <add> MenuUpdate.ALLLINKS.add(MenuUpdate.LINK2TYPE); <add> MenuUpdate.ALLLINKS.addAll(CommandUpdate.ALLLINKS); <add> } <ide> <ide> /** <ide> * @param _url URL to the Configuration Item.
Java
lgpl-2.1
13c451a51fae2496e710be841aba7f91003588ed
0
skplanet/syruppay-java,skplanet/syruppay-java
/* * Syrup Pay Token Library * * Copyright (C) 2015 SK PLANET. ALL Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the SK PLANET., Bundang-gu, 264, * Pangyo-ro The Planet SK planet co., Ltd., Seongnam-si, Gyeonggi-do, Korea * or see https://www.syruppay.co.kr/ */ package com.skplanet.syruppay.token.claims; import com.skplanet.syruppay.token.TokenBuilder; import org.codehaus.jackson.annotate.JsonIgnore; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * 정기/비정기 결제 정보에 대한 Claim 을 구성한다. * * @author 임형태 * @since 1.3 */ public class SubscriptionConfigurer<H extends TokenBuilder<H>> extends AbstractTokenConfigurer<SubscriptionConfigurer<H>, H> { private SubscriptionType subscriptionType; private String shippingAddress; private long subscriptionStartDate; private long subscriptionFinishDate; private PaymentCycle paymentCycle; private List<ProductInfo> productInfo = new ArrayList<ProductInfo>(); public String getShippingAddress() { return shippingAddress; } public SubscriptionConfigurer<H> withShippingAddress(PayConfigurer.ShippingAddress shippingAddress) { this.shippingAddress = shippingAddress.mapToStringForFds(); return this; } public SubscriptionConfigurer<H> fixed() { subscriptionType = SubscriptionType.FIXED; return this; } public SubscriptionConfigurer<H> unfixed() { subscriptionType = SubscriptionType.UNFIXED; return this; } public SubscriptionConfigurer<H> withSubscriptionStartDate(final long subscriptionStartDate) { this.subscriptionStartDate = subscriptionStartDate; return this; } public SubscriptionConfigurer<H> withSubscriptionFinishDate(final long subscriptionFinishDate) { this.subscriptionFinishDate = subscriptionFinishDate; return this; } public SubscriptionConfigurer<H> withPaymentCycle(final PaymentCycle paymentCycle) { this.paymentCycle = paymentCycle; return this; } public SubscriptionConfigurer<H> addProductInfo(final ProductInfo productInfo) { this.productInfo.add(productInfo); return this; } public SubscriptionConfigurer<H> withProductInfo(final List<ProductInfo> productInfo) { this.productInfo = productInfo; return this; } public SubscriptionType getSubscriptionType() { return subscriptionType; } public long getSubscriptionStartDate() { return subscriptionStartDate; } public long getSubscriptionFinishDate() { return subscriptionFinishDate; } public PaymentCycle getPaymentCycle() { return paymentCycle; } public List<ProductInfo> getProductInfo() { return Collections.unmodifiableList(productInfo); } public String claimName() { return "subscription"; } public void validRequired() throws Exception { if (this.subscriptionType == null) { throw new IllegalArgumentException("some of required fields is null(or empty) or wrong. " + "you should set subscriptionType : null" ); } if (productInfo.isEmpty()) { throw new IllegalArgumentException("product info list couldn't be empty. you should set product at least one more by addProductInfo() or setProductInfo."); } for (ProductInfo p : productInfo) { p.validRequiredToProductInfo(); } } public static enum SubscriptionType { FIXED, UNFIXED } public static enum PaymentCycle { ONCE_A_WEEK, ONCE_TWO_WEEKS, ONCE_A_MONTH, ONCE_TWO_MONTHS } public static class ProductInfo { private String productId; private String productTitle; private String autoPaymentId; private List<String> productUrls; private int paymentAmt; private PayConfigurer.Currency currencyCode; public void validRequiredToProductInfo() { if (productId == null || productId.isEmpty() || productTitle == null || productTitle.isEmpty() || paymentAmt == 0 || currencyCode == null) { throw new IllegalArgumentException("some of required fields is null(or empty) or wrong. " + "you should set productId : " + productId + ", productTitle : " + productTitle + ", currencyCode : " + currencyCode + " and paymentAmt should be bigger than 0. yours : " + paymentAmt); } } public String getAutoPaymentId() { return autoPaymentId; } public ProductInfo setAutoPaymentId(final String autoPaymentId) { this.autoPaymentId = autoPaymentId; return this; } public ProductInfo setProductId(final String productId) { this.productId = productId; return this; } public ProductInfo setProductTitle(final String productTitle) { this.productTitle = productTitle; return this; } public ProductInfo setProductUrls(final List<String> productUrls) { this.productUrls = productUrls; return this; } @JsonIgnore public ProductInfo setPaymentAmount(final int paymentAmount) { this.paymentAmt = paymentAmount; return this; } public void setCurrencyCode(PayConfigurer.Currency currencyCode) { this.currencyCode = currencyCode; } public String getProductId() { return productId; } public String getProductTitle() { return productTitle; } public List<String> getProductUrls() { return Collections.unmodifiableList(productUrls); } @JsonIgnore public int getPaymentAmount() { return paymentAmt; } public PayConfigurer.Currency getCurrencyCode() { return currencyCode; } } }
syruppay-token/src/main/java/com/skplanet/syruppay/token/claims/SubscriptionConfigurer.java
/* * Syrup Pay Token Library * * Copyright (C) 2015 SK PLANET. ALL Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the SK PLANET., Bundang-gu, 264, * Pangyo-ro The Planet SK planet co., Ltd., Seongnam-si, Gyeonggi-do, Korea * or see https://www.syruppay.co.kr/ */ package com.skplanet.syruppay.token.claims; import com.skplanet.syruppay.token.TokenBuilder; import org.codehaus.jackson.annotate.JsonIgnore; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * 정기/비정기 결제 정보에 대한 Claim 을 구성한다. * * @author 임형태 * @since 1.3 */ public class SubscriptionConfigurer<H extends TokenBuilder<H>> extends AbstractTokenConfigurer<SubscriptionConfigurer<H>, H> { private SubscriptionType subscriptionType; private String shippingAddress; private String subscriptionId; private long subscriptionStartDate; private long subscriptionFinishDate; private PaymentCycle paymentCycle; private List<ProductInfo> productInfo = new ArrayList<ProductInfo>(); public String getShippingAddress() { return shippingAddress; } public SubscriptionConfigurer<H> withShippingAddress(PayConfigurer.ShippingAddress shippingAddress) { this.shippingAddress = shippingAddress.mapToStringForFds(); return this; } public String getSubscriptionId() { return subscriptionId; } public SubscriptionConfigurer<H> withSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } public SubscriptionConfigurer<H> fixed() { subscriptionType = SubscriptionType.FIXED; return this; } public SubscriptionConfigurer<H> unfixed() { subscriptionType = SubscriptionType.UNFIXED; return this; } public SubscriptionConfigurer<H> withSubscriptionStartDate(final long subscriptionStartDate) { this.subscriptionStartDate = subscriptionStartDate; return this; } public SubscriptionConfigurer<H> withSubscriptionFinishDate(final long subscriptionFinishDate) { this.subscriptionFinishDate = subscriptionFinishDate; return this; } public SubscriptionConfigurer<H> withPaymentCycle(final PaymentCycle paymentCycle) { this.paymentCycle = paymentCycle; return this; } public SubscriptionConfigurer<H> addProductInfo(final ProductInfo productInfo) { this.productInfo.add(productInfo); return this; } public SubscriptionConfigurer<H> withProductInfo(final List<ProductInfo> productInfo) { this.productInfo = productInfo; return this; } public SubscriptionType getSubscriptionType() { return subscriptionType; } public long getSubscriptionStartDate() { return subscriptionStartDate; } public long getSubscriptionFinishDate() { return subscriptionFinishDate; } public PaymentCycle getPaymentCycle() { return paymentCycle; } public List<ProductInfo> getProductInfo() { return Collections.unmodifiableList(productInfo); } public String claimName() { return "subscription"; } public void validRequired() throws Exception { if (this.subscriptionType == null) { throw new IllegalArgumentException("some of required fields is null(or empty) or wrong. " + "you should set subscriptionType : null" ); } if (productInfo.isEmpty()) { throw new IllegalArgumentException("product info list couldn't be empty. you should set product at least one more by addProductInfo() or setProductInfo."); } for (ProductInfo p : productInfo) { p.validRequiredToProductInfo(); } } public static enum SubscriptionType { FIXED, UNFIXED } public static enum PaymentCycle { ONCE_A_WEEK, ONCE_TWO_WEEKS, ONCE_A_MONTH, ONCE_TWO_MONTHS } public static class ProductInfo { private String productId; private String productTitle; private List<String> productUrls; private int paymentAmt; private PayConfigurer.Currency currencyCode; public void validRequiredToProductInfo() { if (productId == null || productId.isEmpty() || productTitle == null || productTitle.isEmpty() || paymentAmt == 0 || currencyCode == null) { throw new IllegalArgumentException("some of required fields is null(or empty) or wrong. " + "you should set productId : " + productId + ", productTitle : " + productTitle + ", currencyCode : " + currencyCode + " and paymentAmt should be bigger than 0. yours : " + paymentAmt); } } public ProductInfo setProductId(final String productId) { this.productId = productId; return this; } public ProductInfo setProductTitle(final String productTitle) { this.productTitle = productTitle; return this; } public ProductInfo setProductUrls(final List<String> productUrls) { this.productUrls = productUrls; return this; } @JsonIgnore public ProductInfo setPaymentAmount(final int paymentAmount) { this.paymentAmt = paymentAmount; return this; } public void setCurrencyCode(PayConfigurer.Currency currencyCode) { this.currencyCode = currencyCode; } public String getProductId() { return productId; } public String getProductTitle() { return productTitle; } public List<String> getProductUrls() { return Collections.unmodifiableList(productUrls); } @JsonIgnore public int getPaymentAmount() { return paymentAmt; } public PayConfigurer.Currency getCurrencyCode() { return currencyCode; } } }
#27 subscriptionId 삭제, autoPaymentId 추가
syruppay-token/src/main/java/com/skplanet/syruppay/token/claims/SubscriptionConfigurer.java
#27 subscriptionId 삭제, autoPaymentId 추가
<ide><path>yruppay-token/src/main/java/com/skplanet/syruppay/token/claims/SubscriptionConfigurer.java <ide> public class SubscriptionConfigurer<H extends TokenBuilder<H>> extends AbstractTokenConfigurer<SubscriptionConfigurer<H>, H> { <ide> private SubscriptionType subscriptionType; <ide> private String shippingAddress; <del> private String subscriptionId; <ide> private long subscriptionStartDate; <ide> private long subscriptionFinishDate; <ide> private PaymentCycle paymentCycle; <ide> return this; <ide> } <ide> <del> public String getSubscriptionId() { <del> return subscriptionId; <del> } <del> <del> public SubscriptionConfigurer<H> withSubscriptionId(String subscriptionId) { <del> this.subscriptionId = subscriptionId; <del> return this; <del> } <del> <ide> public SubscriptionConfigurer<H> fixed() { <ide> subscriptionType = SubscriptionType.FIXED; <ide> return this; <ide> public static class ProductInfo { <ide> private String productId; <ide> private String productTitle; <add> private String autoPaymentId; <ide> private List<String> productUrls; <ide> private int paymentAmt; <ide> private PayConfigurer.Currency currencyCode; <ide> } <ide> } <ide> <add> public String getAutoPaymentId() { <add> return autoPaymentId; <add> } <add> <add> public ProductInfo setAutoPaymentId(final String autoPaymentId) { <add> this.autoPaymentId = autoPaymentId; <add> return this; <add> } <add> <ide> public ProductInfo setProductId(final String productId) { <ide> this.productId = productId; <ide> return this;
Java
lgpl-2.1
71044d741e8f4ead0fb22b1e87922c19219e12b9
0
pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.gwt.dom.client; /** * Extends the {@link com.google.gwt.dom.client.Style} to add constants for standard property names and values. * * @version $Id$ */ public class Style extends com.google.gwt.dom.client.Style { /** * The name of the style attribute. */ public static final String STYLE_ATTRIBUTE = "style"; /** * Sets how/if an element is displayed. */ public static final String DISPLAY = "display"; /** * Sets the background color of an element. */ public static final String BACKGROUND_COLOR = "backgroundColor"; /** * Sets the stack order of an element. An element with greater stack order is always in front of another element * with lower stack order.<br/> * Elements can have negative stack orders.<br/> * Z-index only works on elements that have been positioned (eg position:absolute;)! */ public static final String Z_INDEX = "zIndex"; /** * Sets how thick or thin characters in text should be displayed. */ public static final Property FONT_WEIGHT = new Property("font-weight", "fontWeight", true, false, FontWeight.NORMAL); /** * Sets the style of a font. */ public static final Property FONT_STYLE = new Property("font-style", "fontStyle", true, false, FontStyle.NORMAL); /** * Decorates the text. */ public static final Property TEXT_DECORATION = new Property("text-decoration", "textDecoration", false, true, TextDecoration.NONE); /** * The text-align property aligns the text in an element. */ public static final Property TEXT_ALIGN = new Property("text-align", "textAlign", true, false, ""); /** * The font-family property is a prioritized list of font family names and/or generic family names for an element. * The browser will use the first value it recognizes.<br/> * There are two types of font-family values: * <ul> * <li>family-name: "times", "courier", "arial", etc.</li> * <li>generic-family: "serif", "sans-serif", "cursive", "fantasy", "monospace".</li> * </ul> * Note: Separate each value with a comma, and always offer a generic-family name as the last alternative.<br/> * Note: If a family-name contains white-space, it should be quoted. Single quotes must be used when using the * "style" attribute in HTML. */ public static final Property FONT_FAMILY = new Property("font-family", "fontFamily", true, true, ""); /** * The font-size property sets the size of a font. */ public static final Property FONT_SIZE = new Property("font-size", "fontSize", true, false, FontSize.MEDIUM); /** * Sets the width of an element. */ public static final String WIDTH = "width"; /** * sets the height of an element. */ public static final String HEIGHT = "height"; /** * Sets how far the top edge of an element is above/below the top edge of the parent element. */ public static final String TOP = "top"; /** * Sets how far the left edge of an element is to the right/left of the left edge of the parent element. */ public static final String LEFT = "left"; /** * Places an element in a static, relative, absolute or fixed position. */ public static final String POSITION = "position"; /** * Standard values for {@link Style#DISPLAY}. */ public static final class Display { /** * Default. The element will be displayed as an inline element, with no line break before or after the element. */ public static final String INLINE = "inline"; /** * The element will be displayed as a block-level element, with a line break before and after the element. */ public static final String BLOCK = "block"; /** * The element will not be displayed. */ public static final String NONE = "none"; /** * This is a utility class so it has a private constructor. */ private Display() { } } /** * Standard values for {@link Style#FONT_WEIGHT}. */ public static final class FontWeight { /** * Default. Defines normal characters. */ public static final String NORMAL = FontStyle.NORMAL; /** * Defines thick characters. */ public static final String BOLD = "bold"; /** * Defines thicker characters. */ public static final String BOLDER = "bolder"; /** * This is a utility class so it has a private constructor. */ private FontWeight() { } } /** * Standard values for {@link Style#FONT_STYLE}. */ public static final class FontStyle { /** * Default. The browser displays a normal font. */ public static final String NORMAL = "normal"; /** * The browser displays an italic font. */ public static final String ITALIC = "italic"; /** * This is a utility class so it has a private constructor. */ private FontStyle() { } } /** * Standard values for {@link Style#TEXT_DECORATION}. */ public static final class TextDecoration { /** * Default. Defines a normal text. */ public static final String NONE = Display.NONE; /** * Defines a line through the text. */ public static final String LINE_THROUGH = "line-through"; /** * Defines a line under the text. */ public static final String UNDERLINE = "underline"; /** * This is a utility class so it has a private constructor. */ private TextDecoration() { } } /** * Standard values for {@link Style#POSITION}. */ public static final class Position { /** * Default. An element with position: static always has the position the normal flow of the page gives it (a * static element ignores any top, bottom, left, or right declarations). */ public static final String STATIC = "static"; /** * An element with position: relative moves an element relative to its normal position, so "left:20" adds 20 * pixels to the element's LEFT position. */ public static final String RELATIVE = "relative"; /** * An element with position: absolute is positioned at the specified coordinates relative to its containing * block. The element's position is specified with the "left", "top", "right", and "bottom" properties. */ public static final String ABSOLUTE = "absolute"; /** * An element with position: fixed is positioned at the specified coordinates relative to the browser window. * The element's position is specified with the "left", "top", "right", and "bottom" properties. The element * remains at that position regardless of scrolling. Works in IE7 (strict mode). */ public static final String FIXED = "fixed"; /** * This is a utility class so it has a private constructor. */ private Position() { } } /** * The text-align property aligns the text in an element. * * @see http://www.w3.org/TR/css3-text/#justification */ public static final class TextAlign { /** * Aligns the text to the left. */ public static final String LEFT = Style.LEFT; /** * Aligns the text to the right. */ public static final String RIGHT = "right"; /** * Centers the text. */ public static final String CENTER = "center"; /** * Increases the spaces between words in order for lines to have the same width. */ public static final String JUSTIFY = "justify"; /** * This is a utility class so it has a private constructor. */ private TextAlign() { } } /** * The font-size property sets the size of a font. */ public static final class FontSize { /** * Default value. */ public static final String MEDIUM = "medium"; /** * This is a utility class so it has a private constructor. */ private FontSize() { } } /** * Default constructor. Needs to be protected because all instances are created from JavaScript. */ protected Style() { } /** * Some browsers expect the camel case form of a style property. For instance, the camel case form of "font-weight" * is "fontWeight". * * @param propertyName The name of style property. * @return The camel case form of the given property name. */ public static String toCamelCase(String propertyName) { int dashIndex = propertyName.indexOf('-'); if (dashIndex < 0 || dashIndex == propertyName.length() - 1) { return propertyName; } StringBuffer camelCase = new StringBuffer(propertyName.substring(0, dashIndex)); camelCase.append(propertyName.substring(dashIndex + 1, dashIndex + 2).toUpperCase()); camelCase.append(propertyName.substring(dashIndex + 2)); return camelCase.toString(); } }
xwiki-platform-web/xwiki-gwt-dom/src/main/java/org/xwiki/gwt/dom/client/Style.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.gwt.dom.client; /** * Extends the {@link com.google.gwt.dom.client.Style} to add constants for standard property names and values. * * @version $Id$ */ public class Style extends com.google.gwt.dom.client.Style { /** * The name of the style attribute. */ public static final String STYLE_ATTRIBUTE = "style"; /** * Sets how/if an element is displayed. */ public static final String DISPLAY = "display"; /** * Sets the background color of an element. */ public static final String BACKGROUND_COLOR = "backgroundColor"; /** * Sets the stack order of an element. An element with greater stack order is always in front of another element * with lower stack order.<br/> * Elements can have negative stack orders.<br/> * Z-index only works on elements that have been positioned (eg position:absolute;)! */ public static final String Z_INDEX = "zIndex"; /** * Sets how thick or thin characters in text should be displayed. */ public static final Property FONT_WEIGHT = new Property("font-weight", "fontWeight", true, false, FontWeight.NORMAL); /** * Sets the style of a font. */ public static final Property FONT_STYLE = new Property("font-style", "fontStyle", true, false, FontStyle.NORMAL); /** * Decorates the text. */ public static final Property TEXT_DECORATION = new Property("text-decoration", "textDecoration", false, true, TextDecoration.NONE); /** * The text-align property aligns the text in an element. */ public static final Property TEXT_ALIGN = new Property("text-align", "textAlign", true, false, ""); /** * The font-family property is a prioritized list of font family names and/or generic family names for an element. * The browser will use the first value it recognizes.<br/> * There are two types of font-family values: * <ul> * <li>family-name: "times", "courier", "arial", etc.</li> * <li>generic-family: "serif", "sans-serif", "cursive", "fantasy", "monospace".</li> * </ul> * Note: Separate each value with a comma, and always offer a generic-family name as the last alternative.<br/> * Note: If a family-name contains white-space, it should be quoted. Single quotes must be used when using the * "style" attribute in HTML. */ public static final Property FONT_FAMILY = new Property("font-family", "fontFamily", true, true, ""); /** * Sets the width of an element. */ public static final String WIDTH = "width"; /** * sets the height of an element. */ public static final String HEIGHT = "height"; /** * Sets how far the top edge of an element is above/below the top edge of the parent element. */ public static final String TOP = "top"; /** * Sets how far the left edge of an element is to the right/left of the left edge of the parent element. */ public static final String LEFT = "left"; /** * Places an element in a static, relative, absolute or fixed position. */ public static final String POSITION = "position"; /** * Standard values for {@link Style#DISPLAY}. */ public static final class Display { /** * Default. The element will be displayed as an inline element, with no line break before or after the element. */ public static final String INLINE = "inline"; /** * The element will be displayed as a block-level element, with a line break before and after the element. */ public static final String BLOCK = "block"; /** * The element will not be displayed. */ public static final String NONE = "none"; /** * This is a utility class so it has a private constructor. */ private Display() { } } /** * Standard values for {@link Style#FONT_WEIGHT}. */ public static final class FontWeight { /** * Default. Defines normal characters. */ public static final String NORMAL = FontStyle.NORMAL; /** * Defines thick characters. */ public static final String BOLD = "bold"; /** * Defines thicker characters. */ public static final String BOLDER = "bolder"; /** * This is a utility class so it has a private constructor. */ private FontWeight() { } } /** * Standard values for {@link Style#FONT_STYLE}. */ public static final class FontStyle { /** * Default. The browser displays a normal font. */ public static final String NORMAL = "normal"; /** * The browser displays an italic font. */ public static final String ITALIC = "italic"; /** * This is a utility class so it has a private constructor. */ private FontStyle() { } } /** * Standard values for {@link Style#TEXT_DECORATION}. */ public static final class TextDecoration { /** * Default. Defines a normal text. */ public static final String NONE = Display.NONE; /** * Defines a line through the text. */ public static final String LINE_THROUGH = "line-through"; /** * Defines a line under the text. */ public static final String UNDERLINE = "underline"; /** * This is a utility class so it has a private constructor. */ private TextDecoration() { } } /** * Standard values for {@link Style#POSITION}. */ public static final class Position { /** * Default. An element with position: static always has the position the normal flow of the page gives it (a * static element ignores any top, bottom, left, or right declarations). */ public static final String STATIC = "static"; /** * An element with position: relative moves an element relative to its normal position, so "left:20" adds 20 * pixels to the element's LEFT position. */ public static final String RELATIVE = "relative"; /** * An element with position: absolute is positioned at the specified coordinates relative to its containing * block. The element's position is specified with the "left", "top", "right", and "bottom" properties. */ public static final String ABSOLUTE = "absolute"; /** * An element with position: fixed is positioned at the specified coordinates relative to the browser window. * The element's position is specified with the "left", "top", "right", and "bottom" properties. The element * remains at that position regardless of scrolling. Works in IE7 (strict mode). */ public static final String FIXED = "fixed"; /** * This is a utility class so it has a private constructor. */ private Position() { } } /** * The text-align property aligns the text in an element. * * @see http://www.w3.org/TR/css3-text/#justification */ public static final class TextAlign { /** * Aligns the text to the left. */ public static final String LEFT = Style.LEFT; /** * Aligns the text to the right. */ public static final String RIGHT = "right"; /** * Centers the text. */ public static final String CENTER = "center"; /** * Increases the spaces between words in order for lines to have the same width. */ public static final String JUSTIFY = "justify"; /** * This is a utility class so it has a private constructor. */ private TextAlign() { } } /** * Default constructor. Needs to be protected because all instances are created from JavaScript. */ protected Style() { } /** * Some browsers expect the camel case form of a style property. For instance, the camel case form of "font-weight" * is "fontWeight". * * @param propertyName The name of style property. * @return The camel case form of the given property name. */ public static String toCamelCase(String propertyName) { int dashIndex = propertyName.indexOf('-'); if (dashIndex < 0 || dashIndex == propertyName.length() - 1) { return propertyName; } StringBuffer camelCase = new StringBuffer(propertyName.substring(0, dashIndex)); camelCase.append(propertyName.substring(dashIndex + 1, dashIndex + 2).toUpperCase()); camelCase.append(propertyName.substring(dashIndex + 2)); return camelCase.toString(); } }
XWIKI-3442: Review the font plugin * Added the font-size property git-svn-id: 04343649e741710b2e0f622af6defd1ac33e5ca5@18914 f329d543-caf0-0310-9063-dda96c69346f
xwiki-platform-web/xwiki-gwt-dom/src/main/java/org/xwiki/gwt/dom/client/Style.java
XWIKI-3442: Review the font plugin * Added the font-size property
<ide><path>wiki-platform-web/xwiki-gwt-dom/src/main/java/org/xwiki/gwt/dom/client/Style.java <ide> public static final Property FONT_FAMILY = new Property("font-family", "fontFamily", true, true, ""); <ide> <ide> /** <add> * The font-size property sets the size of a font. <add> */ <add> public static final Property FONT_SIZE = new Property("font-size", "fontSize", true, false, FontSize.MEDIUM); <add> <add> /** <ide> * Sets the width of an element. <ide> */ <ide> public static final String WIDTH = "width"; <ide> * This is a utility class so it has a private constructor. <ide> */ <ide> private TextAlign() <add> { <add> } <add> } <add> <add> /** <add> * The font-size property sets the size of a font. <add> */ <add> public static final class FontSize <add> { <add> /** <add> * Default value. <add> */ <add> public static final String MEDIUM = "medium"; <add> <add> /** <add> * This is a utility class so it has a private constructor. <add> */ <add> private FontSize() <ide> { <ide> } <ide> }
Java
apache-2.0
0706073d19c9f539c952efdd351c1d3b61a38c82
0
ruks/carbon-apimgt,wso2/carbon-apimgt,malinthaprasan/carbon-apimgt,tharindu1st/carbon-apimgt,chamilaadhi/carbon-apimgt,tharikaGitHub/carbon-apimgt,bhathiya/carbon-apimgt,jaadds/carbon-apimgt,malinthaprasan/carbon-apimgt,nuwand/carbon-apimgt,bhathiya/carbon-apimgt,isharac/carbon-apimgt,chamindias/carbon-apimgt,prasa7/carbon-apimgt,tharindu1st/carbon-apimgt,tharikaGitHub/carbon-apimgt,chamindias/carbon-apimgt,nuwand/carbon-apimgt,jaadds/carbon-apimgt,jaadds/carbon-apimgt,prasa7/carbon-apimgt,chamilaadhi/carbon-apimgt,praminda/carbon-apimgt,wso2/carbon-apimgt,malinthaprasan/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,Rajith90/carbon-apimgt,chamilaadhi/carbon-apimgt,isharac/carbon-apimgt,chamilaadhi/carbon-apimgt,tharikaGitHub/carbon-apimgt,tharindu1st/carbon-apimgt,fazlan-nazeem/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,ruks/carbon-apimgt,Rajith90/carbon-apimgt,wso2/carbon-apimgt,praminda/carbon-apimgt,tharikaGitHub/carbon-apimgt,nuwand/carbon-apimgt,malinthaprasan/carbon-apimgt,uvindra/carbon-apimgt,bhathiya/carbon-apimgt,isharac/carbon-apimgt,ruks/carbon-apimgt,wso2/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,uvindra/carbon-apimgt,chamindias/carbon-apimgt,Rajith90/carbon-apimgt,fazlan-nazeem/carbon-apimgt,ruks/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,isharac/carbon-apimgt,prasa7/carbon-apimgt,uvindra/carbon-apimgt,prasa7/carbon-apimgt,praminda/carbon-apimgt,tharindu1st/carbon-apimgt,bhathiya/carbon-apimgt,fazlan-nazeem/carbon-apimgt,Rajith90/carbon-apimgt,nuwand/carbon-apimgt,chamindias/carbon-apimgt,jaadds/carbon-apimgt,fazlan-nazeem/carbon-apimgt,uvindra/carbon-apimgt
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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. */ package org.wso2.carbon.apimgt.rest.api.endpoint.registry.impl; import graphql.schema.GraphQLSchema; import graphql.schema.idl.SchemaParser; import graphql.schema.idl.TypeDefinitionRegistry; import graphql.schema.idl.UnExecutableSchemaGenerator; import graphql.schema.idl.errors.SchemaProblem; import graphql.schema.validation.SchemaValidationError; import graphql.schema.validation.SchemaValidator; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.cxf.jaxrs.ext.MessageContext; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException; import org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse; import org.wso2.carbon.apimgt.api.EndpointRegistry; import org.wso2.carbon.apimgt.api.model.EndpointRegistryEntry; import org.wso2.carbon.apimgt.api.model.EndpointRegistryInfo; import org.wso2.carbon.apimgt.impl.EndpointRegistryConstants; import org.wso2.carbon.apimgt.impl.EndpointRegistryImpl; import org.wso2.carbon.apimgt.impl.definitions.OASParserUtil; import org.wso2.carbon.apimgt.impl.importexport.utils.CommonUtil; import org.wso2.carbon.apimgt.impl.utils.APIMWSDLReader; import org.wso2.carbon.apimgt.rest.api.endpoint.registry.RegistriesApi; import org.wso2.carbon.apimgt.rest.api.endpoint.registry.RegistriesApiService; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.wso2.carbon.apimgt.rest.api.endpoint.registry.dto.RegistryArrayDTO; import org.wso2.carbon.apimgt.rest.api.endpoint.registry.dto.RegistryDTO; import org.wso2.carbon.apimgt.rest.api.endpoint.registry.dto.RegistryEntryArrayDTO; import org.wso2.carbon.apimgt.rest.api.endpoint.registry.dto.RegistryEntryDTO; import org.wso2.carbon.apimgt.rest.api.endpoint.registry.util.EndpointRegistryMappingUtils; import org.wso2.carbon.apimgt.rest.api.util.RestApiConstants; import org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @RequestScoped public class RegistriesApiServiceImpl implements RegistriesApiService { private static final Log log = LogFactory.getLog(RegistriesApiServiceImpl.class); private static final Log audit = CarbonConstants.AUDIT_LOG; @Override public Response getAllEntriesInRegistry(String registryId, String query, RegistriesApi.SortByEntryEnum sortByEntry, RegistriesApi.SortEntryEnum sortEntry, Integer limit, Integer offset, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); RegistryEntryArrayDTO registryEntryArray = new RegistryEntryArrayDTO(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); try { EndpointRegistryInfo endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT; offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT; sortOrder = sortOrder != null ? sortOrder : RestApiConstants.DEFAULT_SORT_ORDER; sortBy = EndpointRegistryMappingUtils.getRegistryEntriesSortByField(sortBy); List<EndpointRegistryEntry> endpointRegistryEntryList = registryProvider.getEndpointRegistryEntries(sortBy, sortOrder, limit, offset, registryId); for (EndpointRegistryEntry endpointRegistryEntry : endpointRegistryEntryList) { registryEntryArray.add(EndpointRegistryMappingUtils.fromRegistryEntryToDTO(endpointRegistryEntry)); } } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while retrieving entries of endpoint registry " + "given by id: " + registryId, e, log); } return Response.ok().entity(registryEntryArray).build(); } @Override public Response getRegistryByUUID(String registryId, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); RegistryDTO registryDTO = null; EndpointRegistry registryProvider = new EndpointRegistryImpl(); try { EndpointRegistryInfo endpointRegistryInfo = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistryInfo != null) { registryDTO = EndpointRegistryMappingUtils.fromEndpointRegistryToDTO(endpointRegistryInfo); } else { RestApiUtil.handleResourceNotFoundError("Endpoint Registry with the id: " + registryId + " is not found", log); } } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while retrieving details of endpoint registry by id: " + registryId, e, log); } return Response.ok().entity(registryDTO).build(); } @Override public Response getRegistries(String query, RegistriesApi.SortByRegistryEnum sortByRegistry, RegistriesApi .SortOrderEnum sortOrder, Integer limit, Integer offset, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); RegistryArrayDTO registryDTOList = new RegistryArrayDTO(); limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT; offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT; String sortOrderStr = sortOrder != null ? sortOrder.toString() : RegistriesApi.SortOrderEnum.asc.toString(); String sortBy = sortByRegistry != null ? EndpointRegistryConstants.COLUMN_REG_NAME : EndpointRegistryConstants.COLUMN_ID; try { List<EndpointRegistryInfo> endpointRegistryInfoList = registryProvider.getEndpointRegistries(sortBy, sortOrderStr, limit, offset, tenantDomain); for (EndpointRegistryInfo endpointRegistryInfo: endpointRegistryInfoList) { registryDTOList.add(EndpointRegistryMappingUtils.fromEndpointRegistryToDTO(endpointRegistryInfo)); } } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while retrieving details of endpoint registries", e, log); } return Response.ok().entity(registryDTOList).build(); } @Override public Response addRegistry(RegistryDTO body, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String user = RestApiUtil.getLoggedInUsername(); EndpointRegistryInfo registry = EndpointRegistryMappingUtils.fromDTOtoEndpointRegistry(body, user); EndpointRegistryInfo createdRegistry = null; try { EndpointRegistry registryProvider = new EndpointRegistryImpl(); String registryId = registryProvider.addEndpointRegistry(registry); createdRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); } catch (APIMgtResourceAlreadyExistsException e) { RestApiUtil.handleResourceAlreadyExistsError("Endpoint Registry with name '" + body.getName() + "' already exists", e, log); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while adding new endpoint registry: " + registry.getName(), e, log); } audit.info("Successfully created endpoint registry " + createdRegistry.getName() + " with id :" + createdRegistry.getUuid() + " by :" + user); return Response.ok().entity(EndpointRegistryMappingUtils.fromEndpointRegistryToDTO(createdRegistry)).build(); } @Override public Response createRegistryEntry(String registryId, RegistryEntryDTO registryEntry, InputStream definitionFileInputStream, Attachment definitionFileDetail, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String user = RestApiUtil.getLoggedInUsername(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); EndpointRegistryEntry createdEntry = null; try { EndpointRegistryInfo endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } InputStream definitionFile = null; if ((definitionFileInputStream != null || registryEntry.getDefinitionUrl() != null) && registryEntry.getDefinitionType() == null) { RestApiUtil.handleBadRequest("Missing definitionType parameter", log); } if (definitionFileInputStream == null || definitionFileDetail == null) { // Retrieve the endpoint definition from URL try { URL definitionURL = new URL(registryEntry.getDefinitionUrl()); if (!isValidEndpointDefinition(definitionURL, null, registryEntry.getDefinitionType().toString())) { RestApiUtil.handleBadRequest("Error while validating the endpoint URL definition of " + "the new registry entry with registry id: " + registryId, log); } } catch (MalformedURLException e) { RestApiUtil.handleBadRequest("The definition url provided is invalid for the new " + "Endpoint Registry Entry with Registry Id: " + registryId, e, log); } catch (IOException e) { RestApiUtil.handleInternalServerError("Error while reaching the " + "definition url: " + registryEntry.getDefinitionUrl() + " given for the new " + "Endpoint Registry with Registry Id: " + registryId, e, log); } } else { byte[] definitionFileByteArray = getDefinitionFromInput(definitionFileInputStream); if (!isValidEndpointDefinition(null, definitionFileByteArray, registryEntry.getDefinitionType().toString())) { RestApiUtil.handleBadRequest("Error while validating the endpoint definition of " + "the new registry entry with registry id: " + registryId, log); } definitionFileByteArray = transformDefinitionContent(definitionFileByteArray, registryEntry.getDefinitionType()); definitionFile = new ByteArrayInputStream(definitionFileByteArray); } EndpointRegistryEntry entryToAdd = EndpointRegistryMappingUtils.fromDTOToRegistryEntry(registryEntry, null, definitionFile, endpointRegistry.getRegistryId()); String entryId = registryProvider.addEndpointRegistryEntry(entryToAdd); createdEntry = registryProvider.getEndpointRegistryEntryByUUID(registryId, entryId); } catch (APIMgtResourceAlreadyExistsException e) { RestApiUtil.handleResourceAlreadyExistsError("Endpoint Registry Entry with name '" + registryEntry.getEntryName() + "' already exists", e, log); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while adding new entry for the endpoint registry " + "with id: " + registryId, e, log); } catch (IOException e) { RestApiUtil.handleInternalServerError("Error in reading endpoint definition file content", e, log); } audit.info("Successfully created endpoint registry entry with id :" + createdEntry.getEntryId() + " in :" + registryId + " by:" + user); return Response.ok().entity(EndpointRegistryMappingUtils.fromRegistryEntryToDTO(createdEntry)).build(); } @Override public Response updateRegistry(String registryId, RegistryDTO body, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String user = RestApiUtil.getLoggedInUsername(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); EndpointRegistryInfo registryToUpdate = EndpointRegistryMappingUtils.fromDTOtoEndpointRegistry(body, user); EndpointRegistryInfo updatedEndpointRegistry = null; EndpointRegistryInfo endpointRegistry = null; try { endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } registryProvider.updateEndpointRegistry(registryId, endpointRegistry.getName(), registryToUpdate); updatedEndpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); } catch (APIMgtResourceAlreadyExistsException e) { RestApiUtil.handleResourceAlreadyExistsError("Endpoint Registry with name '" + endpointRegistry.getName() + "' already exists", e, log); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while updating the endpoint registry " + "with id: " + registryId, e, log); } audit.info("Successfully updated endpoint registry of id :" + updatedEndpointRegistry.getUuid() + " by :" + user); return Response.ok().entity(EndpointRegistryMappingUtils.fromEndpointRegistryToDTO(updatedEndpointRegistry)). build(); } @Override public Response deleteRegistry(String registryId, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String user = RestApiUtil.getLoggedInUsername(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); try { EndpointRegistryInfo endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } registryProvider.deleteEndpointRegistry(registryId); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while deleting the endpoint registry " + "with id: " + registryId, e, log); } audit.info("Successfully deleted endpoint registry of id :" + registryId + " by :" + user); return Response.ok().entity("Successfully deleted the endpoint registry").build(); } @Override public Response getRegistryEntryByUuid(String registryId, String entryId, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); EndpointRegistryEntry endpointRegistryEntry = null; try { EndpointRegistryInfo endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } endpointRegistryEntry = registryProvider.getEndpointRegistryEntryByUUID(registryId, entryId); if (endpointRegistryEntry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry entry with the id: " + entryId + " is not found", log); } } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while fetching endpoint registry entry: " + entryId, e, log); } return Response.ok().entity(EndpointRegistryMappingUtils.fromRegistryEntryToDTO(endpointRegistryEntry)) .build(); } @Override public Response updateRegistryEntry(String registryId, String entryId, RegistryEntryDTO registryEntry, InputStream definitionFileInputStream, Attachment definitionFileDetail, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String user = RestApiUtil.getLoggedInUsername(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); EndpointRegistryEntry updatedEntry = null; InputStream definitionFile = null; try { EndpointRegistryInfo endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } EndpointRegistryEntry endpointRegistryEntry = registryProvider.getEndpointRegistryEntryByUUID(registryId, entryId); if (endpointRegistryEntry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry entry with the id: " + entryId + " is not found", log); } if ((definitionFileInputStream != null || registryEntry.getDefinitionUrl() != null) && registryEntry.getDefinitionType() == null) { RestApiUtil.handleBadRequest("Missing definitionType of the registry " + "entry with id: " + entryId, log); } if (definitionFileInputStream == null || definitionFileDetail == null) { // Retrieve the endpoint definition from URL try { URL definitionURL = new URL(registryEntry.getDefinitionUrl()); if (!isValidEndpointDefinition(definitionURL, null, registryEntry.getDefinitionType().toString())) { RestApiUtil.handleBadRequest("Error while validating the endpoint URL definition of " + "the registry entry with id: " + entryId, log); } } catch (MalformedURLException e) { RestApiUtil.handleBadRequest("The definition url provided is invalid for the endpoint " + "registry entry with id: " + entryId, e, log); } catch (IOException e) { RestApiUtil.handleInternalServerError("Error while reaching the definition url: " + registryEntry.getDefinitionUrl() + " given for the Endpoint Registry Entry with Id: " + entryId, e, log); } } else { byte[] definitionFileByteArray = getDefinitionFromInput(definitionFileInputStream); if (!isValidEndpointDefinition(null, definitionFileByteArray, registryEntry.getDefinitionType().toString())) { RestApiUtil.handleBadRequest("Error while validating the endpoint definition of " + "the registry entry with id: " + entryId, log); } definitionFileByteArray = transformDefinitionContent(definitionFileByteArray, registryEntry.getDefinitionType()); definitionFile = new ByteArrayInputStream(definitionFileByteArray); } EndpointRegistryEntry entryToUpdate = EndpointRegistryMappingUtils.fromDTOToRegistryEntry(registryEntry, entryId, definitionFile, endpointRegistry.getRegistryId()); registryProvider.updateEndpointRegistryEntry(entryToUpdate); updatedEntry = registryProvider.getEndpointRegistryEntryByUUID(registryId, entryId); } catch (APIMgtResourceAlreadyExistsException e) { RestApiUtil.handleResourceAlreadyExistsError("Endpoint Registry Entry with name '" + registryEntry.getEntryName() + "' already exists", e, log); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while updating the endpoint registry entry " + "with id: " + entryId, e, log); } catch (IOException e) { RestApiUtil.handleInternalServerError("Error in reading endpoint definition file content", e, log); } audit.info("Successfully updated endpoint registry entry with id :" + entryId + " in :" + registryId + " by:" + user); return Response.ok().entity(EndpointRegistryMappingUtils.fromRegistryEntryToDTO(updatedEntry)).build(); } @Override public Response deleteRegistryEntry(String registryId, String entryId, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String user = RestApiUtil.getLoggedInUsername(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); try { EndpointRegistryInfo endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } EndpointRegistryEntry endpointRegistryEntry = registryProvider.getEndpointRegistryEntryByUUID(registryId, entryId); if (endpointRegistryEntry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry entry with the id: " + entryId + " is not found", log); } registryProvider.deleteEndpointRegistryEntry(entryId); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while deleting the endpoint registry entry " + "with id: " + registryId, e, log); } audit.info("Successfully deleted endpoint registry entry with id :" + entryId + " in :" + registryId + " by:" + user); return Response.ok().entity("Successfully deleted the endpoint registry entry").build(); } private boolean isValidEndpointDefinition(URL definitionURL, byte[] definitionFileByteArray, String definitionType) { String definitionContent = null; try { // definition file is given priority than the definition url if (definitionFileByteArray != null) { definitionContent = new String(definitionFileByteArray); } else if (definitionURL != null) { if (isDefinitionUrlParameterized(definitionURL.toString())) { // if parameterized skip content validation return true; } definitionContent = IOUtils.toString(definitionURL.openStream()); } } catch (IOException e) { log.error("Error in reading endpoint definition content", e); return false; } if (StringUtils.isEmpty(definitionContent)) { log.error("No endpoint definition content found"); return false; } boolean isValid = false; if (RegistryEntryDTO.DefinitionTypeEnum.OAS.toString().equals(definitionType)) { // Validate OpenAPI definitions try { APIDefinitionValidationResponse response = OASParserUtil.validateAPIDefinition(definitionContent,false); isValid = response.isValid(); } catch (APIManagementException | ClassCastException e) { log.error("Unable to parse the OpenAPI endpoint definition", e); } } else if (RegistryEntryDTO.DefinitionTypeEnum.WSDL1.toString().equals(definitionType) || RegistryEntryDTO.DefinitionTypeEnum.WSDL2.toString().equals(definitionType)) { // Validate WSDL1 and WSDL2 definitions try { if (definitionFileByteArray != null) { ByteArrayInputStream definitionFileByteStream = new ByteArrayInputStream(definitionFileByteArray); isValid = APIMWSDLReader.validateWSDLFile(definitionFileByteStream).isValid(); } else { isValid = APIMWSDLReader.validateWSDLUrl(definitionURL).isValid(); } } catch (APIManagementException e) { log.error("Unable to parse the WSDL endpoint definition", e); } } else if (RegistryEntryDTO.DefinitionTypeEnum.GQL_SDL.toString().equals(definitionType)) { // Validate GraphQL definitions try { SchemaParser schemaParser = new SchemaParser(); TypeDefinitionRegistry typeRegistry = schemaParser.parse(definitionContent); GraphQLSchema graphQLSchema = UnExecutableSchemaGenerator.makeUnExecutableSchema(typeRegistry); SchemaValidator schemaValidation = new SchemaValidator(); Set<SchemaValidationError> validationErrors = schemaValidation.validateSchema(graphQLSchema); isValid = (validationErrors.toArray().length == 0); } catch (SchemaProblem e) { log.error("Unable to parse the GraphQL endpoint definition", e); } } return isValid; } private boolean isDefinitionUrlParameterized(String url) { if (url.contains("{") && url.contains("}")) { return true; } return false; } @Override public Response getEndpointDefinition(String registryId, String entryId, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String contentType = StringUtils.EMPTY; EndpointRegistry registryProvider = new EndpointRegistryImpl(); InputStream endpointDefinition = null; try { EndpointRegistryInfo endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } EndpointRegistryEntry registryEntry = registryProvider.getEndpointRegistryEntryByUUID(registryId, entryId); if (registryEntry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry entry with the id: " + entryId + " is not found", log); } String type = registryEntry.getDefinitionType(); if (RegistryEntryDTO.DefinitionTypeEnum.OAS.equals(RegistryEntryDTO.DefinitionTypeEnum.fromValue(type)) || RegistryEntryDTO.DefinitionTypeEnum.GQL_SDL.equals(RegistryEntryDTO.DefinitionTypeEnum .fromValue(type))) { contentType = MediaType.APPLICATION_JSON; } else if (RegistryEntryDTO.DefinitionTypeEnum.WSDL1.equals(RegistryEntryDTO.DefinitionTypeEnum .fromValue(type)) || RegistryEntryDTO.DefinitionTypeEnum.WSDL2.equals(RegistryEntryDTO .DefinitionTypeEnum.fromValue(type))) { contentType = MediaType.TEXT_XML; } endpointDefinition = registryEntry.getEndpointDefinition(); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while retrieving the endpoint definition of registry " + "entry with id: " + entryId, e, log); } if (endpointDefinition == null) { RestApiUtil.handleResourceNotFoundError("Endpoint definition not found for entry with ID: " + entryId, log); } return Response.ok(endpointDefinition).type(contentType).build(); } private byte[] getDefinitionFromInput(InputStream definitionFileInputStream) throws IOException { ByteArrayOutputStream definitionFileOutputByteStream = new ByteArrayOutputStream(); IOUtils.copy(definitionFileInputStream, definitionFileOutputByteStream); return definitionFileOutputByteStream.toByteArray(); } private byte[] transformDefinitionContent(byte[] definitionFileByteArray, RegistryEntryDTO.DefinitionTypeEnum type) throws IOException { if (RegistryEntryDTO.DefinitionTypeEnum.OAS.equals(type)) { String oasContent = new String(definitionFileByteArray); if (!oasContent.trim().startsWith("{")) { String jsonContent = CommonUtil.yamlToJson(oasContent); return jsonContent.getBytes(StandardCharsets.UTF_8); } } return definitionFileByteArray; } }
components/apimgt/org.wso2.carbon.apimgt.rest.api.endpoint.registry/src/main/java/org/wso2/carbon/apimgt/rest/api/endpoint/registry/impl/RegistriesApiServiceImpl.java
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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. */ package org.wso2.carbon.apimgt.rest.api.endpoint.registry.impl; import graphql.schema.GraphQLSchema; import graphql.schema.idl.SchemaParser; import graphql.schema.idl.TypeDefinitionRegistry; import graphql.schema.idl.UnExecutableSchemaGenerator; import graphql.schema.idl.errors.SchemaProblem; import graphql.schema.validation.SchemaValidationError; import graphql.schema.validation.SchemaValidator; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.cxf.jaxrs.ext.MessageContext; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException; import org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse; import org.wso2.carbon.apimgt.api.EndpointRegistry; import org.wso2.carbon.apimgt.api.model.EndpointRegistryEntry; import org.wso2.carbon.apimgt.api.model.EndpointRegistryInfo; import org.wso2.carbon.apimgt.impl.EndpointRegistryImpl; import org.wso2.carbon.apimgt.impl.definitions.OASParserUtil; import org.wso2.carbon.apimgt.impl.importexport.utils.CommonUtil; import org.wso2.carbon.apimgt.impl.utils.APIMWSDLReader; import org.wso2.carbon.apimgt.rest.api.endpoint.registry.RegistriesApiService; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.wso2.carbon.apimgt.rest.api.endpoint.registry.dto.RegistryArrayDTO; import org.wso2.carbon.apimgt.rest.api.endpoint.registry.dto.RegistryDTO; import org.wso2.carbon.apimgt.rest.api.endpoint.registry.dto.RegistryEntryArrayDTO; import org.wso2.carbon.apimgt.rest.api.endpoint.registry.dto.RegistryEntryDTO; import org.wso2.carbon.apimgt.rest.api.endpoint.registry.util.EndpointRegistryMappingUtils; import org.wso2.carbon.apimgt.rest.api.util.RestApiConstants; import org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @RequestScoped public class RegistriesApiServiceImpl implements RegistriesApiService { private static final Log log = LogFactory.getLog(RegistriesApiServiceImpl.class); private static final Log audit = CarbonConstants.AUDIT_LOG; @Override public Response getAllEntriesInRegistry(String registryId, String query, String sortBy, String sortOrder, Integer limit, Integer offset, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); RegistryEntryArrayDTO registryEntryArray = new RegistryEntryArrayDTO(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); try { EndpointRegistryInfo endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT; offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT; sortOrder = sortOrder != null ? sortOrder : RestApiConstants.DEFAULT_SORT_ORDER; sortBy = EndpointRegistryMappingUtils.getRegistryEntriesSortByField(sortBy); List<EndpointRegistryEntry> endpointRegistryEntryList = registryProvider.getEndpointRegistryEntries(sortBy, sortOrder, limit, offset, registryId); for (EndpointRegistryEntry endpointRegistryEntry : endpointRegistryEntryList) { registryEntryArray.add(EndpointRegistryMappingUtils.fromRegistryEntryToDTO(endpointRegistryEntry)); } } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while retrieving entries of endpoint registry " + "given by id: " + registryId, e, log); } return Response.ok().entity(registryEntryArray).build(); } @Override public Response getRegistryByUUID(String registryId, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); RegistryDTO registryDTO = null; EndpointRegistry registryProvider = new EndpointRegistryImpl(); try { EndpointRegistryInfo endpointRegistryInfo = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistryInfo != null) { registryDTO = EndpointRegistryMappingUtils.fromEndpointRegistryToDTO(endpointRegistryInfo); } else { RestApiUtil.handleResourceNotFoundError("Endpoint Registry with the id: " + registryId + " is not found", log); } } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while retrieving details of endpoint registry by id: " + registryId, e, log); } return Response.ok().entity(registryDTO).build(); } @Override public Response getRegistries(String query, String sortBy, String sortOrder, Integer limit, Integer offset, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); RegistryArrayDTO registryDTOList = new RegistryArrayDTO(); limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT; offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT; sortOrder = sortOrder != null ? sortOrder : RestApiConstants.DEFAULT_SORT_ORDER; sortBy = EndpointRegistryMappingUtils.getRegistriesSortByField(sortBy); try { List<EndpointRegistryInfo> endpointRegistryInfoList = registryProvider.getEndpointRegistries(sortBy, sortOrder, limit, offset, tenantDomain); for (EndpointRegistryInfo endpointRegistryInfo: endpointRegistryInfoList) { registryDTOList.add(EndpointRegistryMappingUtils.fromEndpointRegistryToDTO(endpointRegistryInfo)); } } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while retrieving details of endpoint registries", e, log); } return Response.ok().entity(registryDTOList).build(); } @Override public Response addRegistry(RegistryDTO body, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String user = RestApiUtil.getLoggedInUsername(); EndpointRegistryInfo registry = EndpointRegistryMappingUtils.fromDTOtoEndpointRegistry(body, user); EndpointRegistryInfo createdRegistry = null; try { EndpointRegistry registryProvider = new EndpointRegistryImpl(); String registryId = registryProvider.addEndpointRegistry(registry); createdRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); } catch (APIMgtResourceAlreadyExistsException e) { RestApiUtil.handleResourceAlreadyExistsError("Endpoint Registry with name '" + body.getName() + "' already exists", e, log); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while adding new endpoint registry: " + registry.getName(), e, log); } audit.info("Successfully created endpoint registry " + createdRegistry.getName() + " with id :" + createdRegistry.getUuid() + " by :" + user); return Response.ok().entity(EndpointRegistryMappingUtils.fromEndpointRegistryToDTO(createdRegistry)).build(); } @Override public Response createRegistryEntry(String registryId, RegistryEntryDTO registryEntry, InputStream definitionFileInputStream, Attachment definitionFileDetail, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String user = RestApiUtil.getLoggedInUsername(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); EndpointRegistryEntry createdEntry = null; try { EndpointRegistryInfo endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } InputStream definitionFile = null; if ((definitionFileInputStream != null || registryEntry.getDefinitionUrl() != null) && registryEntry.getDefinitionType() == null) { RestApiUtil.handleBadRequest("Missing definitionType parameter", log); } if (definitionFileInputStream == null || definitionFileDetail == null) { // Retrieve the endpoint definition from URL try { URL definitionURL = new URL(registryEntry.getDefinitionUrl()); if (!isValidEndpointDefinition(definitionURL, null, registryEntry.getDefinitionType().toString())) { RestApiUtil.handleBadRequest("Error while validating the endpoint URL definition of " + "the new registry entry with registry id: " + registryId, log); } } catch (MalformedURLException e) { RestApiUtil.handleBadRequest("The definition url provided is invalid for the new " + "Endpoint Registry Entry with Registry Id: " + registryId, e, log); } catch (IOException e) { RestApiUtil.handleInternalServerError("Error while reaching the " + "definition url: " + registryEntry.getDefinitionUrl() + " given for the new " + "Endpoint Registry with Registry Id: " + registryId, e, log); } } else { byte[] definitionFileByteArray = getDefinitionFromInput(definitionFileInputStream); if (!isValidEndpointDefinition(null, definitionFileByteArray, registryEntry.getDefinitionType().toString())) { RestApiUtil.handleBadRequest("Error while validating the endpoint definition of " + "the new registry entry with registry id: " + registryId, log); } definitionFileByteArray = transformDefinitionContent(definitionFileByteArray, registryEntry.getDefinitionType()); definitionFile = new ByteArrayInputStream(definitionFileByteArray); } EndpointRegistryEntry entryToAdd = EndpointRegistryMappingUtils.fromDTOToRegistryEntry(registryEntry, null, definitionFile, endpointRegistry.getRegistryId()); String entryId = registryProvider.addEndpointRegistryEntry(entryToAdd); createdEntry = registryProvider.getEndpointRegistryEntryByUUID(registryId, entryId); } catch (APIMgtResourceAlreadyExistsException e) { RestApiUtil.handleResourceAlreadyExistsError("Endpoint Registry Entry with name '" + registryEntry.getEntryName() + "' already exists", e, log); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while adding new entry for the endpoint registry " + "with id: " + registryId, e, log); } catch (IOException e) { RestApiUtil.handleInternalServerError("Error in reading endpoint definition file content", e, log); } audit.info("Successfully created endpoint registry entry with id :" + createdEntry.getEntryId() + " in :" + registryId + " by:" + user); return Response.ok().entity(EndpointRegistryMappingUtils.fromRegistryEntryToDTO(createdEntry)).build(); } @Override public Response updateRegistry(String registryId, RegistryDTO body, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String user = RestApiUtil.getLoggedInUsername(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); EndpointRegistryInfo registryToUpdate = EndpointRegistryMappingUtils.fromDTOtoEndpointRegistry(body, user); EndpointRegistryInfo updatedEndpointRegistry = null; EndpointRegistryInfo endpointRegistry = null; try { endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } registryProvider.updateEndpointRegistry(registryId, endpointRegistry.getName(), registryToUpdate); updatedEndpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); } catch (APIMgtResourceAlreadyExistsException e) { RestApiUtil.handleResourceAlreadyExistsError("Endpoint Registry with name '" + endpointRegistry.getName() + "' already exists", e, log); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while updating the endpoint registry " + "with id: " + registryId, e, log); } audit.info("Successfully updated endpoint registry of id :" + updatedEndpointRegistry.getUuid() + " by :" + user); return Response.ok().entity(EndpointRegistryMappingUtils.fromEndpointRegistryToDTO(updatedEndpointRegistry)). build(); } @Override public Response deleteRegistry(String registryId, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String user = RestApiUtil.getLoggedInUsername(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); try { EndpointRegistryInfo endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } registryProvider.deleteEndpointRegistry(registryId); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while deleting the endpoint registry " + "with id: " + registryId, e, log); } audit.info("Successfully deleted endpoint registry of id :" + registryId + " by :" + user); return Response.ok().entity("Successfully deleted the endpoint registry").build(); } @Override public Response getRegistryEntryByUuid(String registryId, String entryId, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); EndpointRegistryEntry endpointRegistryEntry = null; try { EndpointRegistryInfo endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } endpointRegistryEntry = registryProvider.getEndpointRegistryEntryByUUID(registryId, entryId); if (endpointRegistryEntry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry entry with the id: " + entryId + " is not found", log); } } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while fetching endpoint registry entry: " + entryId, e, log); } return Response.ok().entity(EndpointRegistryMappingUtils.fromRegistryEntryToDTO(endpointRegistryEntry)) .build(); } @Override public Response updateRegistryEntry(String registryId, String entryId, RegistryEntryDTO registryEntry, InputStream definitionFileInputStream, Attachment definitionFileDetail, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String user = RestApiUtil.getLoggedInUsername(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); EndpointRegistryEntry updatedEntry = null; InputStream definitionFile = null; try { EndpointRegistryInfo endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } EndpointRegistryEntry endpointRegistryEntry = registryProvider.getEndpointRegistryEntryByUUID(registryId, entryId); if (endpointRegistryEntry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry entry with the id: " + entryId + " is not found", log); } if ((definitionFileInputStream != null || registryEntry.getDefinitionUrl() != null) && registryEntry.getDefinitionType() == null) { RestApiUtil.handleBadRequest("Missing definitionType of the registry " + "entry with id: " + entryId, log); } if (definitionFileInputStream == null || definitionFileDetail == null) { // Retrieve the endpoint definition from URL try { URL definitionURL = new URL(registryEntry.getDefinitionUrl()); if (!isValidEndpointDefinition(definitionURL, null, registryEntry.getDefinitionType().toString())) { RestApiUtil.handleBadRequest("Error while validating the endpoint URL definition of " + "the registry entry with id: " + entryId, log); } } catch (MalformedURLException e) { RestApiUtil.handleBadRequest("The definition url provided is invalid for the endpoint " + "registry entry with id: " + entryId, e, log); } catch (IOException e) { RestApiUtil.handleInternalServerError("Error while reaching the definition url: " + registryEntry.getDefinitionUrl() + " given for the Endpoint Registry Entry with Id: " + entryId, e, log); } } else { byte[] definitionFileByteArray = getDefinitionFromInput(definitionFileInputStream); if (!isValidEndpointDefinition(null, definitionFileByteArray, registryEntry.getDefinitionType().toString())) { RestApiUtil.handleBadRequest("Error while validating the endpoint definition of " + "the registry entry with id: " + entryId, log); } definitionFileByteArray = transformDefinitionContent(definitionFileByteArray, registryEntry.getDefinitionType()); definitionFile = new ByteArrayInputStream(definitionFileByteArray); } EndpointRegistryEntry entryToUpdate = EndpointRegistryMappingUtils.fromDTOToRegistryEntry(registryEntry, entryId, definitionFile, endpointRegistry.getRegistryId()); registryProvider.updateEndpointRegistryEntry(entryToUpdate); updatedEntry = registryProvider.getEndpointRegistryEntryByUUID(registryId, entryId); } catch (APIMgtResourceAlreadyExistsException e) { RestApiUtil.handleResourceAlreadyExistsError("Endpoint Registry Entry with name '" + registryEntry.getEntryName() + "' already exists", e, log); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while updating the endpoint registry entry " + "with id: " + entryId, e, log); } catch (IOException e) { RestApiUtil.handleInternalServerError("Error in reading endpoint definition file content", e, log); } audit.info("Successfully updated endpoint registry entry with id :" + entryId + " in :" + registryId + " by:" + user); return Response.ok().entity(EndpointRegistryMappingUtils.fromRegistryEntryToDTO(updatedEntry)).build(); } @Override public Response deleteRegistryEntry(String registryId, String entryId, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String user = RestApiUtil.getLoggedInUsername(); EndpointRegistry registryProvider = new EndpointRegistryImpl(); try { EndpointRegistryInfo endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } EndpointRegistryEntry endpointRegistryEntry = registryProvider.getEndpointRegistryEntryByUUID(registryId, entryId); if (endpointRegistryEntry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry entry with the id: " + entryId + " is not found", log); } registryProvider.deleteEndpointRegistryEntry(entryId); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while deleting the endpoint registry entry " + "with id: " + registryId, e, log); } audit.info("Successfully deleted endpoint registry entry with id :" + entryId + " in :" + registryId + " by:" + user); return Response.ok().entity("Successfully deleted the endpoint registry entry").build(); } private boolean isValidEndpointDefinition(URL definitionURL, byte[] definitionFileByteArray, String definitionType) { String definitionContent = null; try { // definition file is given priority than the definition url if (definitionFileByteArray != null) { definitionContent = new String(definitionFileByteArray); } else if (definitionURL != null) { if (isDefinitionUrlParameterized(definitionURL.toString())) { // if parameterized skip content validation return true; } definitionContent = IOUtils.toString(definitionURL.openStream()); } } catch (IOException e) { log.error("Error in reading endpoint definition content", e); return false; } if (StringUtils.isEmpty(definitionContent)) { log.error("No endpoint definition content found"); return false; } boolean isValid = false; if (RegistryEntryDTO.DefinitionTypeEnum.OAS.toString().equals(definitionType)) { // Validate OpenAPI definitions try { APIDefinitionValidationResponse response = OASParserUtil.validateAPIDefinition(definitionContent,false); isValid = response.isValid(); } catch (APIManagementException | ClassCastException e) { log.error("Unable to parse the OpenAPI endpoint definition", e); } } else if (RegistryEntryDTO.DefinitionTypeEnum.WSDL1.toString().equals(definitionType) || RegistryEntryDTO.DefinitionTypeEnum.WSDL2.toString().equals(definitionType)) { // Validate WSDL1 and WSDL2 definitions try { if (definitionFileByteArray != null) { ByteArrayInputStream definitionFileByteStream = new ByteArrayInputStream(definitionFileByteArray); isValid = APIMWSDLReader.validateWSDLFile(definitionFileByteStream).isValid(); } else { isValid = APIMWSDLReader.validateWSDLUrl(definitionURL).isValid(); } } catch (APIManagementException e) { log.error("Unable to parse the WSDL endpoint definition", e); } } else if (RegistryEntryDTO.DefinitionTypeEnum.GQL_SDL.toString().equals(definitionType)) { // Validate GraphQL definitions try { SchemaParser schemaParser = new SchemaParser(); TypeDefinitionRegistry typeRegistry = schemaParser.parse(definitionContent); GraphQLSchema graphQLSchema = UnExecutableSchemaGenerator.makeUnExecutableSchema(typeRegistry); SchemaValidator schemaValidation = new SchemaValidator(); Set<SchemaValidationError> validationErrors = schemaValidation.validateSchema(graphQLSchema); isValid = (validationErrors.toArray().length == 0); } catch (SchemaProblem e) { log.error("Unable to parse the GraphQL endpoint definition", e); } } return isValid; } private boolean isDefinitionUrlParameterized(String url) { if (url.contains("{") && url.contains("}")) { return true; } return false; } @Override public Response getEndpointDefinition(String registryId, String entryId, MessageContext messageContext) { String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); String contentType = StringUtils.EMPTY; EndpointRegistry registryProvider = new EndpointRegistryImpl(); InputStream endpointDefinition = null; try { EndpointRegistryInfo endpointRegistry = registryProvider.getEndpointRegistryByUUID(registryId, tenantDomain); if (endpointRegistry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry with the id: " + registryId + " is not found", log); } EndpointRegistryEntry registryEntry = registryProvider.getEndpointRegistryEntryByUUID(registryId, entryId); if (registryEntry == null) { RestApiUtil.handleResourceNotFoundError("Endpoint registry entry with the id: " + entryId + " is not found", log); } String type = registryEntry.getDefinitionType(); if (RegistryEntryDTO.DefinitionTypeEnum.OAS.equals(RegistryEntryDTO.DefinitionTypeEnum.fromValue(type)) || RegistryEntryDTO.DefinitionTypeEnum.GQL_SDL.equals(RegistryEntryDTO.DefinitionTypeEnum .fromValue(type))) { contentType = MediaType.APPLICATION_JSON; } else if (RegistryEntryDTO.DefinitionTypeEnum.WSDL1.equals(RegistryEntryDTO.DefinitionTypeEnum .fromValue(type)) || RegistryEntryDTO.DefinitionTypeEnum.WSDL2.equals(RegistryEntryDTO .DefinitionTypeEnum.fromValue(type))) { contentType = MediaType.TEXT_XML; } endpointDefinition = registryEntry.getEndpointDefinition(); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while retrieving the endpoint definition of registry " + "entry with id: " + entryId, e, log); } if (endpointDefinition == null) { RestApiUtil.handleResourceNotFoundError("Endpoint definition not found for entry with ID: " + entryId, log); } return Response.ok(endpointDefinition).type(contentType).build(); } private byte[] getDefinitionFromInput(InputStream definitionFileInputStream) throws IOException { ByteArrayOutputStream definitionFileOutputByteStream = new ByteArrayOutputStream(); IOUtils.copy(definitionFileInputStream, definitionFileOutputByteStream); return definitionFileOutputByteStream.toByteArray(); } private byte[] transformDefinitionContent(byte[] definitionFileByteArray, RegistryEntryDTO.DefinitionTypeEnum type) throws IOException { if (RegistryEntryDTO.DefinitionTypeEnum.OAS.equals(type)) { String oasContent = new String(definitionFileByteArray); if (!oasContent.trim().startsWith("{")) { String jsonContent = CommonUtil.yamlToJson(oasContent); return jsonContent.getBytes(StandardCharsets.UTF_8); } } return definitionFileByteArray; } }
Fix issue in service impl
components/apimgt/org.wso2.carbon.apimgt.rest.api.endpoint.registry/src/main/java/org/wso2/carbon/apimgt/rest/api/endpoint/registry/impl/RegistriesApiServiceImpl.java
Fix issue in service impl
<ide><path>omponents/apimgt/org.wso2.carbon.apimgt.rest.api.endpoint.registry/src/main/java/org/wso2/carbon/apimgt/rest/api/endpoint/registry/impl/RegistriesApiServiceImpl.java <ide> import org.wso2.carbon.apimgt.api.EndpointRegistry; <ide> import org.wso2.carbon.apimgt.api.model.EndpointRegistryEntry; <ide> import org.wso2.carbon.apimgt.api.model.EndpointRegistryInfo; <add>import org.wso2.carbon.apimgt.impl.EndpointRegistryConstants; <ide> import org.wso2.carbon.apimgt.impl.EndpointRegistryImpl; <ide> import org.wso2.carbon.apimgt.impl.definitions.OASParserUtil; <ide> import org.wso2.carbon.apimgt.impl.importexport.utils.CommonUtil; <ide> import org.wso2.carbon.apimgt.impl.utils.APIMWSDLReader; <add>import org.wso2.carbon.apimgt.rest.api.endpoint.registry.RegistriesApi; <ide> import org.wso2.carbon.apimgt.rest.api.endpoint.registry.RegistriesApiService; <ide> <ide> import org.apache.cxf.jaxrs.ext.multipart.Attachment; <ide> <ide> <ide> @Override <del> public Response getAllEntriesInRegistry(String registryId, String query, String sortBy, String sortOrder, <del> Integer limit, Integer offset, MessageContext messageContext) { <add> public Response getAllEntriesInRegistry(String registryId, String query, RegistriesApi.SortByEntryEnum sortByEntry, <add> RegistriesApi.SortEntryEnum sortEntry, Integer limit, Integer offset, <add> MessageContext messageContext) { <ide> String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); <ide> RegistryEntryArrayDTO registryEntryArray = new RegistryEntryArrayDTO(); <ide> EndpointRegistry registryProvider = new EndpointRegistryImpl(); <ide> } <ide> <ide> @Override <del> public Response getRegistries(String query, String sortBy, String sortOrder, Integer limit, Integer offset, <del> MessageContext messageContext) { <add> public Response getRegistries(String query, RegistriesApi.SortByRegistryEnum sortByRegistry, RegistriesApi <add> .SortOrderEnum sortOrder, Integer limit, Integer offset, MessageContext messageContext) { <ide> String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); <ide> EndpointRegistry registryProvider = new EndpointRegistryImpl(); <ide> RegistryArrayDTO registryDTOList = new RegistryArrayDTO(); <ide> <ide> limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT; <ide> offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT; <del> sortOrder = sortOrder != null ? sortOrder : RestApiConstants.DEFAULT_SORT_ORDER; <del> sortBy = EndpointRegistryMappingUtils.getRegistriesSortByField(sortBy); <add> String sortOrderStr = sortOrder != null ? sortOrder.toString() : RegistriesApi.SortOrderEnum.asc.toString(); <add> String sortBy = sortByRegistry != null ? EndpointRegistryConstants.COLUMN_REG_NAME : <add> EndpointRegistryConstants.COLUMN_ID; <ide> <ide> try { <ide> List<EndpointRegistryInfo> endpointRegistryInfoList = <del> registryProvider.getEndpointRegistries(sortBy, sortOrder, limit, offset, tenantDomain); <add> registryProvider.getEndpointRegistries(sortBy, sortOrderStr, limit, offset, tenantDomain); <ide> for (EndpointRegistryInfo endpointRegistryInfo: endpointRegistryInfoList) { <ide> registryDTOList.add(EndpointRegistryMappingUtils.fromEndpointRegistryToDTO(endpointRegistryInfo)); <ide> }
Java
apache-2.0
597e436da7b377d1742cbfbadb90aa0014658909
0
apache/pdfbox,kalaspuffar/pdfbox,apache/pdfbox,kalaspuffar/pdfbox
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.pdfbox.tools; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.concurrent.Callable; import org.apache.pdfbox.Loader; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDocument; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.pdfwriter.compress.CompressParameters; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.common.PDStream; import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; /** * load document and write with all streams decoded. * * @author Michael Traut */ @Command(name = "writedecodeddoc", header = "Writes a PDF document with all streams decoded", versionProvider = Version.class, mixinStandardHelpOptions = true) public class WriteDecodedDoc implements Callable<Integer> { // Expected for CLI app to write to System.out/Sytem.err @SuppressWarnings("squid:S106") private static final PrintStream SYSERR = System.err; @Option(names = "-password", description = "the password to decrypt the document", arity = "0..1", interactive = true) private String password; @Option(names = "-skipImages", description = "don't uncompress images") private boolean skipImages; @Parameters(paramLabel = "inputfile", index="0", description = "the PDF document to be decompressed") private File infile; @Parameters(paramLabel = "outputfile", arity = "0..1", description = "the PDF file to save to.") private File outfile; /** * Constructor. */ public WriteDecodedDoc() { super(); } /** * This will perform the document reading, decoding and writing. * * @param in The filename used for input. * @param out The filename used for output. * @param password The password to open the document. * @param skipImages Whether to skip decoding images. * * @throws IOException if the output could not be written */ public void doIt(String in, String out, String password, boolean skipImages) throws IOException { try (PDDocument doc = Loader.loadPDF(new File(in), password)) { doc.setAllSecurityToBeRemoved(true); COSDocument cosDocument = doc.getDocument(); cosDocument.getXrefTable().keySet().stream() .forEach(o -> processObject(cosDocument.getObjectFromPool(o), skipImages)); doc.getDocumentCatalog(); doc.getDocument().setIsXRefStream(false); doc.save(out, CompressParameters.NO_COMPRESSION); } } private void processObject(COSObject cosObject, boolean skipImages) { COSBase base = cosObject.getObject(); if (base instanceof COSStream) { COSStream stream = (COSStream) base; if (skipImages && COSName.XOBJECT.equals(stream.getItem(COSName.TYPE)) && COSName.IMAGE.equals(stream.getItem(COSName.SUBTYPE))) { return; } try { byte[] bytes = new PDStream(stream).toByteArray(); stream.removeItem(COSName.FILTER); try (OutputStream streamOut = stream.createOutputStream()) { streamOut.write(bytes); } } catch (IOException ex) { SYSERR.println("skip " + cosObject.getObjectNumber() + " " + cosObject.getGenerationNumber() + " obj: " + ex.getMessage()); } } } /** * This will write a PDF document with completely decoded streams. * <br> * see usage() for commandline * * @param args command line arguments */ public static void main(String[] args) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new WriteDecodedDoc()).execute(args); System.exit(exitCode); } public Integer call() { String outputFilename; if (outfile == null) { outputFilename = calculateOutputFilename(infile.getAbsolutePath()); } else { outputFilename = outfile.getAbsolutePath(); } try { doIt(infile.getAbsolutePath(), outputFilename, password, skipImages); } catch (IOException ioe) { SYSERR.println( "Error writing decoded PDF [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } return 0; } private static String calculateOutputFilename(String filename) { String outputFilename; if (filename.toLowerCase().endsWith(".pdf")) { outputFilename = filename.substring(0,filename.length()-4); } else { outputFilename = filename; } outputFilename += "_unc.pdf"; return outputFilename; } }
tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.pdfbox.tools; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.concurrent.Callable; import org.apache.pdfbox.Loader; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDocument; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.common.PDStream; import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; /** * load document and write with all streams decoded. * * @author Michael Traut */ @Command(name = "writedecodeddoc", header = "Writes a PDF document with all streams decoded", versionProvider = Version.class, mixinStandardHelpOptions = true) public class WriteDecodedDoc implements Callable<Integer> { // Expected for CLI app to write to System.out/Sytem.err @SuppressWarnings("squid:S106") private static final PrintStream SYSERR = System.err; @Option(names = "-password", description = "the password to decrypt the document", arity = "0..1", interactive = true) private String password; @Option(names = "-skipImages", description = "don't uncompress images") private boolean skipImages; @Parameters(paramLabel = "inputfile", index="0", description = "the PDF document to be decompressed") private File infile; @Parameters(paramLabel = "outputfile", arity = "0..1", description = "the PDF file to save to.") private File outfile; /** * Constructor. */ public WriteDecodedDoc() { super(); } /** * This will perform the document reading, decoding and writing. * * @param in The filename used for input. * @param out The filename used for output. * @param password The password to open the document. * @param skipImages Whether to skip decoding images. * * @throws IOException if the output could not be written */ public void doIt(String in, String out, String password, boolean skipImages) throws IOException { try (PDDocument doc = Loader.loadPDF(new File(in), password)) { doc.setAllSecurityToBeRemoved(true); COSDocument cosDocument = doc.getDocument(); cosDocument.getXrefTable().keySet().stream() .forEach(o -> processObject(cosDocument.getObjectFromPool(o), skipImages)); doc.getDocumentCatalog(); doc.getDocument().setIsXRefStream(false); doc.save( out ); } } private void processObject(COSObject cosObject, boolean skipImages) { COSBase base = cosObject.getObject(); if (base instanceof COSStream) { COSStream stream = (COSStream) base; if (skipImages && COSName.XOBJECT.equals(stream.getItem(COSName.TYPE)) && COSName.IMAGE.equals(stream.getItem(COSName.SUBTYPE))) { return; } try { byte[] bytes = new PDStream(stream).toByteArray(); stream.removeItem(COSName.FILTER); try (OutputStream streamOut = stream.createOutputStream()) { streamOut.write(bytes); } } catch (IOException ex) { SYSERR.println("skip " + cosObject.getObjectNumber() + " " + cosObject.getGenerationNumber() + " obj: " + ex.getMessage()); } } } /** * This will write a PDF document with completely decoded streams. * <br> * see usage() for commandline * * @param args command line arguments */ public static void main(String[] args) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new WriteDecodedDoc()).execute(args); System.exit(exitCode); } public Integer call() { String outputFilename; if (outfile == null) { outputFilename = calculateOutputFilename(infile.getAbsolutePath()); } else { outputFilename = outfile.getAbsolutePath(); } try { doIt(infile.getAbsolutePath(), outputFilename, password, skipImages); } catch (IOException ioe) { SYSERR.println( "Error writing decoded PDF [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } return 0; } private static String calculateOutputFilename(String filename) { String outputFilename; if (filename.toLowerCase().endsWith(".pdf")) { outputFilename = filename.substring(0,filename.length()-4); } else { outputFilename = filename; } outputFilename += "_unc.pdf"; return outputFilename; } }
PDFBOX-4952: save document with no compression git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1885016 13f79535-47bb-0310-9956-ffa450edef68
tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java
PDFBOX-4952: save document with no compression
<ide><path>ools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java <ide> import org.apache.pdfbox.cos.COSName; <ide> import org.apache.pdfbox.cos.COSObject; <ide> import org.apache.pdfbox.cos.COSStream; <add>import org.apache.pdfbox.pdfwriter.compress.CompressParameters; <ide> import org.apache.pdfbox.pdmodel.PDDocument; <ide> import org.apache.pdfbox.pdmodel.common.PDStream; <ide> <ide> .forEach(o -> processObject(cosDocument.getObjectFromPool(o), skipImages)); <ide> doc.getDocumentCatalog(); <ide> doc.getDocument().setIsXRefStream(false); <del> doc.save( out ); <add> doc.save(out, CompressParameters.NO_COMPRESSION); <ide> } <ide> } <ide>
Java
mit
error: pathspec 'src/Test/ListOrphans.java' did not match any file(s) known to git
77e190ad68522a33367109e1c417c03ca05a8a83
1
mdadariy/Team_3_Project
package Test; import Model.Individual; /** * Created by dinever on 11/30/15. */ public class ListOrphans { public static void list(Individual ind) { if (ind.getFather() != null && ind.getMother() != null) if (ind.getAge() <= 18.0 && ind.getFather().getDeathDate() != null && ind.getMother().getDeathDate() != null) { System.out.println("Name: " + ind.getName()); } } }
src/Test/ListOrphans.java
[User Story 20] List orphans
src/Test/ListOrphans.java
[User Story 20] List orphans
<ide><path>rc/Test/ListOrphans.java <add>package Test; <add> <add>import Model.Individual; <add> <add>/** <add> * Created by dinever on 11/30/15. <add> */ <add>public class ListOrphans { <add> public static void list(Individual ind) { <add> if (ind.getFather() != null && ind.getMother() != null) <add> if (ind.getAge() <= 18.0 && ind.getFather().getDeathDate() != null && ind.getMother().getDeathDate() != null) { <add> System.out.println("Name: " + ind.getName()); <add> } <add> } <add>}
Java
apache-2.0
85a4b5bf8b03bcbfb4f7d502e2e9e2410b4bedec
0
evanji/gitdemo
package test; /** * Created by 烦 on 2017/5/17. */ public class Demo { public static void main(String[] args) { System.out.println("我是b"); System.out.println("ksajdhas"); System.out.println("sss"); System.out.println(); } }
Demo1/src/test/Demo.java
package test; /** * Created by 烦 on 2017/5/17. */ public class Demo { public static void main(String[] args) { System.out.println("我是A"); System.out.println("ksajdhas"); System.out.println("sss"); System.out.println(); } }
lalaal
Demo1/src/test/Demo.java
lalaal
<ide><path>emo1/src/test/Demo.java <ide> */ <ide> public class Demo { <ide> public static void main(String[] args) { <del> System.out.println("我是A"); <add> System.out.println("我是b"); <ide> System.out.println("ksajdhas"); <ide> System.out.println("sss"); <ide> System.out.println(); <add> <ide> } <ide> }
Java
apache-2.0
2269f3851abbf4febd8e71458d81286e8908c4de
0
dans123456/pnc,pgier/pnc,rnc/pnc,ruhan1/pnc,jbartece/pnc,thauser/pnc,alexcreasy/pnc,matejonnet/pnc,jdcasey/pnc,project-ncl/pnc,ruhan1/pnc,mareknovotny/pnc,michalszynkiewicz/pnc,dans123456/pnc,mareknovotny/pnc,emmettu/pnc,mareknovotny/pnc,dans123456/pnc,psakar/pnc,michalszynkiewicz/pnc,pgier/pnc,alexcreasy/pnc,jdcasey/pnc,thauser/pnc,psakar/pnc,michalszynkiewicz/pnc,ahmedlawi92/pnc,thauser/pnc,michalszynkiewicz/pnc,jsenko/pnc,psakar/pnc,ahmedlawi92/pnc,jsenko/pnc,jbartece/pnc,ahmedlawi92/pnc,ahmedlawi92/pnc,pkocandr/pnc,jsenko/pnc,jdcasey/pnc,alexcreasy/pnc,matedo1/pnc,emmettu/pnc,mareknovotny/pnc,psakar/pnc,emmettu/pnc,pgier/pnc,matedo1/pnc,jbartece/pnc,ruhan1/pnc,emmettu/pnc,pgier/pnc,matedo1/pnc,thescouser89/pnc
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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. */ package org.jboss.pnc.model; import java.sql.Timestamp; import java.time.Instant; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PreRemove; import javax.validation.constraints.NotNull; import org.hibernate.annotations.ForeignKey; import org.hibernate.annotations.Type; /** * Created by <a href="mailto:[email protected]">Matej Lazar</a> on 2014-11-23. * <p> * This class contains the build result of a project configuration, and contains additional metadata, as the build script, the * starting and ending time of a build, the status of the build, the sources url used, the user that triggered the build, plus * all the Artifacts that were built and all the Artifacts that were used for the final build. It stores also the buildDriverID * that was used to run the build, the system Image where is was run in, and is mapped to a BuildRecordSet, that encapsulates * the set of buildRecord that compose a Product */ @Entity public class BuildRecord implements GenericEntity<Integer> { private static final long serialVersionUID = -5472083609387609797L; public static final String SEQUENCE_NAME = "build_record_id_seq"; @Id private Integer id; @NotNull @ManyToOne(cascade = { CascadeType.REFRESH }, fetch = FetchType.LAZY) @JoinColumn(name = "buildconfiguration_id", insertable = false, updatable = false) @ForeignKey(name = "fk_buildrecord_buildconfiguration") private BuildConfiguration latestBuildConfiguration; // TODO do we need latest and audited build configuration @NotNull @ManyToOne(cascade = { CascadeType.REFRESH }) @JoinColumns({ @JoinColumn(name = "buildconfiguration_id", referencedColumnName = "id"), @JoinColumn(name = "buildconfiguration_rev", referencedColumnName = "rev") }) @ForeignKey(name = "fk_buildrecord_buildconfiguration_aud") private BuildConfigurationAudited buildConfigurationAudited; private String buildContentId; @NotNull private Timestamp startTime; @NotNull private Timestamp endTime; // @NotNull //TODO uncomment @ManyToOne @ForeignKey(name = "fk_buildrecord_user") private User user; @Lob // Type below is compatible with Oracle and PostgreSQL ("org.hibernate.type.TextType" not with Oracle) // Use "org.hibernate.type.MaterializedClobType" from Hibernate 4.2.x @Type(type = "org.hibernate.type.StringClobType") private String buildLog; @Enumerated(value = EnumType.STRING) private BuildStatus status; @OneToMany(mappedBy = "buildRecord", cascade = CascadeType.ALL) private List<Artifact> builtArtifacts; @OneToMany(mappedBy = "buildRecord", cascade = CascadeType.ALL) private List<Artifact> dependencies; /** * Driver that was used to run the build. */ private String buildDriverId; /** * Image that was used to instantiate a build server. */ @ManyToOne @ForeignKey(name = "fk_buildrecord_systemimage") private SystemImage systemImage; // bi-directional many-to-many association to buildRecordSet /** * Sets of related build records in which this build record is included */ @ManyToMany(mappedBy = "buildRecords") private List<BuildRecordSet> buildRecordSets; /** * If this build was executed as part of a set, this will contain the link to the overall results of the set. Otherwise, * this field will be null. */ @ManyToOne @ForeignKey(name = "fk_buildrecord_buildconfigsetrecord") private BuildConfigSetRecord buildConfigSetRecord; /** * Instantiates a new project build result. */ public BuildRecord() { startTime = Timestamp.from(Instant.now()); buildRecordSets = new ArrayList<>(); dependencies = new ArrayList<>(); builtArtifacts = new ArrayList<>(); } @PreRemove private void removeBuildRecordFromSets() { for (BuildRecordSet brs : buildRecordSets) { brs.getBuildRecords().remove(this); } } /** * Gets the id. * * @return the id */ public Integer getId() { return id; } /** * Sets the id. * * @param id the new id */ public void setId(Integer id) { this.id = id; } /** * Gets the start time. * * @return the start time */ public Timestamp getStartTime() { return startTime; } /** * Sets the start time. * * @param startTime the new start time */ public void setStartTime(Timestamp startTime) { this.startTime = startTime; } /** * Gets the end time. * * @return the end time */ public Timestamp getEndTime() { return endTime; } /** * Sets the end time. * * @param endTime the new end time */ public void setEndTime(Timestamp endTime) { this.endTime = endTime; } /** * Gets the user. * * @return the user */ public User getUser() { return user; } /** * Sets the user. * * @param user the new user */ public void setUser(User user) { this.user = user; } /** * Gets the builds the log. * * @return the builds the log */ public String getBuildLog() { return buildLog; } /** * Sets the builds the log. * * @param buildLog the new builds the log */ public void setBuildLog(String buildLog) { this.buildLog = buildLog; } /** * Gets the status. * * @return the status */ public BuildStatus getStatus() { return status; } /** * Sets the status. * * @param status the new status */ public void setStatus(BuildStatus status) { this.status = status; } /** * Gets the built artifacts. * * @return the built artifacts */ public List<Artifact> getBuiltArtifacts() { return builtArtifacts; } /** * Sets the built artifacts. * * @param builtArtifacts the new built artifacts */ public void setBuiltArtifacts(List<Artifact> builtArtifacts) { this.builtArtifacts = builtArtifacts; } /** * Gets the dependencies. * * @return the dependencies */ public List<Artifact> getDependencies() { return dependencies; } /** * Sets the dependencies. * * @param dependencies the new dependencies */ public void setDependencies(List<Artifact> dependencies) { this.dependencies = dependencies; } /** * Gets the builds the driver id. * * @return the builds the driver id */ public String getBuildDriverId() { return buildDriverId; } /** * Sets the builds the driver id. * * @param buildDriverId the new builds the driver id */ public void setBuildDriverId(String buildDriverId) { this.buildDriverId = buildDriverId; } /** * Gets the system image. * * @return the system image */ public SystemImage getSystemImage() { return systemImage; } /** * Sets the system image. * * @param systemImage the new system image */ public void setSystemImage(SystemImage systemImage) { this.systemImage = systemImage; } /** * @return The latest version of the build configuration used to create this build record */ public BuildConfiguration getLatestBuildConfiguration() { return latestBuildConfiguration; } public void setLatestBuildConfiguration(BuildConfiguration latestBuildConfiguration) { this.latestBuildConfiguration = latestBuildConfiguration; } /** * @return The audited version of the build configuration used to create this build record */ public BuildConfigurationAudited getBuildConfigurationAudited() { return buildConfigurationAudited; } public void setBuildConfigurationAudited(BuildConfigurationAudited buildConfigurationAudited) { this.buildConfigurationAudited = buildConfigurationAudited; } /** * @return the buildRecordSets */ public List<BuildRecordSet> getBuildRecordSets() { return buildRecordSets; } /** * @param buildRecordSets the buildRecordSets to set */ public void setBuildRecordSets(List<BuildRecordSet> buildRecordSets) { this.buildRecordSets = buildRecordSets; } public String getBuildContentId() { return buildContentId; } /** * @param buildContentId The identifier to use when accessing repository or other content stored via external services. */ public void setBuildContentId(String buildContentId) { this.buildContentId = buildContentId; } public BuildConfigSetRecord getBuildConfigSetRecord() { return buildConfigSetRecord; } public void setBuildConfigSetRecord(BuildConfigSetRecord buildConfigSetRecord) { this.buildConfigSetRecord = buildConfigSetRecord; } @Override public String toString() { return "BuildRecord [id=" + id + ", project=" + buildConfigurationAudited.getProject().getName() + ", buildConfiguration=" + buildConfigurationAudited + "]"; } public static class Builder { private Integer id; private String buildContentId; private Timestamp startTime; private Timestamp endTime; private BuildConfiguration latestBuildConfiguration; private BuildConfigurationAudited buildConfigurationAudited; private User user; private String buildLog; private BuildStatus status; private List<Artifact> builtArtifacts; private List<Artifact> dependencies; private String buildDriverId; private SystemImage systemImage; private List<BuildRecordSet> buildRecordSets; private BuildConfigSetRecord buildConfigSetRecord; public Builder() { startTime = Timestamp.from(Instant.now()); buildRecordSets = new ArrayList<>(); dependencies = new ArrayList<>(); builtArtifacts = new ArrayList<>(); } public static Builder newBuilder() { return new Builder(); } public BuildRecord build() { BuildRecord buildRecord = new BuildRecord(); buildRecord.setId(id); buildRecord.setBuildContentId(buildContentId); buildRecord.setStartTime(startTime); buildRecord.setEndTime(endTime); if (latestBuildConfiguration != null) { latestBuildConfiguration.addBuildRecord(buildRecord); buildRecord.setLatestBuildConfiguration(latestBuildConfiguration); } buildRecord.setBuildConfigurationAudited(buildConfigurationAudited); buildRecord.setUser(user); buildRecord.setBuildLog(buildLog); buildRecord.setStatus(status); buildRecord.setBuildDriverId(buildDriverId); buildRecord.setSystemImage(systemImage); // Set the bi-directional mapping for (Artifact artifact : builtArtifacts) { artifact.setBuildRecord(buildRecord); } buildRecord.setBuiltArtifacts(builtArtifacts); // Set the bi-directional mapping for (Artifact artifact : dependencies) { artifact.setBuildRecord(buildRecord); } buildRecord.setDependencies(dependencies); // Set the bi-directional mapping for (BuildRecordSet buildRecordSet : buildRecordSets) { buildRecordSet.getBuildRecords().add(buildRecord); } buildRecord.setBuildRecordSets(buildRecordSets); return buildRecord; } public Builder id(Integer id) { this.id = id; return this; } public Builder buildContentId(String buildContentId) { this.buildContentId = buildContentId; return this; } public Builder startTime(Timestamp startTime) { this.startTime = startTime; return this; } public Builder endTime(Timestamp endTime) { this.endTime = endTime; return this; } public Builder latestBuildConfiguration(BuildConfiguration latestBuildConfiguration) { this.latestBuildConfiguration = latestBuildConfiguration; return this; } public Builder buildConfigurationAudited(BuildConfigurationAudited buildConfigurationAudited) { this.buildConfigurationAudited = buildConfigurationAudited; return this; } public Builder user(User user) { this.user = user; return this; } public Builder buildLog(String buildLog) { this.buildLog = buildLog; return this; } public Builder status(BuildStatus status) { this.status = status; return this; } public Builder builtArtifact(Artifact builtArtifact) { this.builtArtifacts.add(builtArtifact); return this; } public Builder builtArtifacts(List<Artifact> builtArtifacts) { this.builtArtifacts = builtArtifacts; return this; } public Builder dependency(Artifact builtArtifact) { this.dependencies.add(builtArtifact); return this; } public Builder dependencies(List<Artifact> dependencies) { this.dependencies = dependencies; return this; } public Builder buildDriverId(String buildDriverId) { this.buildDriverId = buildDriverId; return this; } public Builder systemImage(SystemImage systemImage) { this.systemImage = systemImage; return this; } public Builder buildRecordSets(List<BuildRecordSet> buildRecordSets) { this.buildRecordSets = buildRecordSets; return this; } public Builder buildConfigSetRecord(BuildConfigSetRecord buildConfigSetRecord) { this.buildConfigSetRecord = buildConfigSetRecord; return this; } } }
model/src/main/java/org/jboss/pnc/model/BuildRecord.java
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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. */ package org.jboss.pnc.model; import java.sql.Timestamp; import java.time.Instant; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PreRemove; import javax.validation.constraints.NotNull; import org.hibernate.annotations.ForeignKey; import org.hibernate.annotations.Type; /** * Created by <a href="mailto:[email protected]">Matej Lazar</a> on 2014-11-23. * <p> * This class contains the build result of a project configuration, and contains additional metadata, as the build script, the * starting and ending time of a build, the status of the build, the sources url used, the user that triggered the build, plus * all the Artifacts that were built and all the Artifacts that were used for the final build. It stores also the buildDriverID * that was used to run the build, the system Image where is was run in, and is mapped to a BuildRecordSet, that encapsulates * the set of buildRecord that compose a Product */ @Entity public class BuildRecord implements GenericEntity<Integer> { private static final long serialVersionUID = -5472083609387609797L; public static final String SEQUENCE_NAME = "build_record_id_seq"; // public static final String PREPARED_STATEMENT_INSERT = "INSERT INTO buildrecord (" // + "id, buildcontentid, builddriverid, buildlog, endtime, starttime, " // + "status, buildconfiguration_id, buildconfiguration_rev, user_id, systemimage_id, buildconfigsetrecord_id) " // + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; @Id private Integer id; @NotNull @ManyToOne(cascade = { CascadeType.REFRESH }, fetch = FetchType.LAZY) @JoinColumn(name = "buildconfiguration_id", insertable = false, updatable = false) @ForeignKey(name = "fk_buildrecord_buildconfiguration") private BuildConfiguration latestBuildConfiguration; // TODO do we need latest and audited build configuration @NotNull @ManyToOne(cascade = { CascadeType.REFRESH }) @JoinColumns({ @JoinColumn(name = "buildconfiguration_id", referencedColumnName = "id"), @JoinColumn(name = "buildconfiguration_rev", referencedColumnName = "rev") }) @ForeignKey(name = "fk_buildrecord_buildconfiguration_aud") private BuildConfigurationAudited buildConfigurationAudited; private String buildContentId; @NotNull private Timestamp startTime; @NotNull private Timestamp endTime; // @NotNull //TODO uncomment @ManyToOne @ForeignKey(name = "fk_buildrecord_user") private User user; @Lob // Type below is compatible with Oracle and PostgreSQL ("org.hibernate.type.TextType" not with Oracle) // Use "org.hibernate.type.MaterializedClobType" from Hibernate 4.2.x @Type(type = "org.hibernate.type.StringClobType") private String buildLog; @Enumerated(value = EnumType.STRING) private BuildStatus status; @OneToMany(mappedBy = "buildRecord", cascade = CascadeType.ALL) private List<Artifact> builtArtifacts; @OneToMany(mappedBy = "buildRecord", cascade = CascadeType.ALL) private List<Artifact> dependencies; /** * Driver that was used to run the build. */ private String buildDriverId; /** * Image that was used to instantiate a build server. */ @ManyToOne @ForeignKey(name = "fk_buildrecord_systemimage") private SystemImage systemImage; // bi-directional many-to-many association to buildRecordSet /** * Sets of related build records in which this build record is included */ @ManyToMany(mappedBy = "buildRecords") private List<BuildRecordSet> buildRecordSets; /** * If this build was executed as part of a set, this will contain the link to the overall results of the set. Otherwise, * this field will be null. */ @ManyToOne @ForeignKey(name = "fk_buildrecord_buildconfigsetrecord") private BuildConfigSetRecord buildConfigSetRecord; /** * Instantiates a new project build result. */ public BuildRecord() { startTime = Timestamp.from(Instant.now()); buildRecordSets = new ArrayList<>(); dependencies = new ArrayList<>(); builtArtifacts = new ArrayList<>(); } @PreRemove private void removeBuildRecordFromSets() { for (BuildRecordSet brs : buildRecordSets) { brs.getBuildRecords().remove(this); } } /** * Gets the id. * * @return the id */ public Integer getId() { return id; } /** * Sets the id. * * @param id the new id */ public void setId(Integer id) { this.id = id; } /** * Gets the start time. * * @return the start time */ public Timestamp getStartTime() { return startTime; } /** * Sets the start time. * * @param startTime the new start time */ public void setStartTime(Timestamp startTime) { this.startTime = startTime; } /** * Gets the end time. * * @return the end time */ public Timestamp getEndTime() { return endTime; } /** * Sets the end time. * * @param endTime the new end time */ public void setEndTime(Timestamp endTime) { this.endTime = endTime; } /** * Gets the user. * * @return the user */ public User getUser() { return user; } /** * Sets the user. * * @param user the new user */ public void setUser(User user) { this.user = user; } /** * Gets the builds the log. * * @return the builds the log */ public String getBuildLog() { return buildLog; } /** * Sets the builds the log. * * @param buildLog the new builds the log */ public void setBuildLog(String buildLog) { this.buildLog = buildLog; } /** * Gets the status. * * @return the status */ public BuildStatus getStatus() { return status; } /** * Sets the status. * * @param status the new status */ public void setStatus(BuildStatus status) { this.status = status; } /** * Gets the built artifacts. * * @return the built artifacts */ public List<Artifact> getBuiltArtifacts() { return builtArtifacts; } /** * Sets the built artifacts. * * @param builtArtifacts the new built artifacts */ public void setBuiltArtifacts(List<Artifact> builtArtifacts) { this.builtArtifacts = builtArtifacts; } /** * Gets the dependencies. * * @return the dependencies */ public List<Artifact> getDependencies() { return dependencies; } /** * Sets the dependencies. * * @param dependencies the new dependencies */ public void setDependencies(List<Artifact> dependencies) { this.dependencies = dependencies; } /** * Gets the builds the driver id. * * @return the builds the driver id */ public String getBuildDriverId() { return buildDriverId; } /** * Sets the builds the driver id. * * @param buildDriverId the new builds the driver id */ public void setBuildDriverId(String buildDriverId) { this.buildDriverId = buildDriverId; } /** * Gets the system image. * * @return the system image */ public SystemImage getSystemImage() { return systemImage; } /** * Sets the system image. * * @param systemImage the new system image */ public void setSystemImage(SystemImage systemImage) { this.systemImage = systemImage; } /** * @return The latest version of the build configuration used to create this build record */ public BuildConfiguration getLatestBuildConfiguration() { return latestBuildConfiguration; } public void setLatestBuildConfiguration(BuildConfiguration latestBuildConfiguration) { this.latestBuildConfiguration = latestBuildConfiguration; } /** * @return The audited version of the build configuration used to create this build record */ public BuildConfigurationAudited getBuildConfigurationAudited() { return buildConfigurationAudited; } public void setBuildConfigurationAudited(BuildConfigurationAudited buildConfigurationAudited) { this.buildConfigurationAudited = buildConfigurationAudited; } /** * @return the buildRecordSets */ public List<BuildRecordSet> getBuildRecordSets() { return buildRecordSets; } /** * @param buildRecordSets the buildRecordSets to set */ public void setBuildRecordSets(List<BuildRecordSet> buildRecordSets) { this.buildRecordSets = buildRecordSets; } public String getBuildContentId() { return buildContentId; } /** * @param buildContentId The identifier to use when accessing repository or other content stored via external services. */ public void setBuildContentId(String buildContentId) { this.buildContentId = buildContentId; } public BuildConfigSetRecord getBuildConfigSetRecord() { return buildConfigSetRecord; } public void setBuildConfigSetRecord(BuildConfigSetRecord buildConfigSetRecord) { this.buildConfigSetRecord = buildConfigSetRecord; } @Override public String toString() { return "BuildRecord [id=" + id + ", project=" + buildConfigurationAudited.getProject().getName() + ", buildConfiguration=" + buildConfigurationAudited + "]"; } public static class Builder { private Integer id; private String buildContentId; private Timestamp startTime; private Timestamp endTime; private BuildConfiguration latestBuildConfiguration; private BuildConfigurationAudited buildConfigurationAudited; private User user; private String buildLog; private BuildStatus status; private List<Artifact> builtArtifacts; private List<Artifact> dependencies; private String buildDriverId; private SystemImage systemImage; private List<BuildRecordSet> buildRecordSets; private BuildConfigSetRecord buildConfigSetRecord; public Builder() { startTime = Timestamp.from(Instant.now()); buildRecordSets = new ArrayList<>(); dependencies = new ArrayList<>(); builtArtifacts = new ArrayList<>(); } public static Builder newBuilder() { return new Builder(); } public BuildRecord build() { BuildRecord buildRecord = new BuildRecord(); buildRecord.setId(id); buildRecord.setBuildContentId(buildContentId); buildRecord.setStartTime(startTime); buildRecord.setEndTime(endTime); if (latestBuildConfiguration != null) { latestBuildConfiguration.addBuildRecord(buildRecord); buildRecord.setLatestBuildConfiguration(latestBuildConfiguration); } buildRecord.setBuildConfigurationAudited(buildConfigurationAudited); buildRecord.setUser(user); buildRecord.setBuildLog(buildLog); buildRecord.setStatus(status); buildRecord.setBuildDriverId(buildDriverId); buildRecord.setSystemImage(systemImage); // Set the bi-directional mapping for (Artifact artifact : builtArtifacts) { artifact.setBuildRecord(buildRecord); } buildRecord.setBuiltArtifacts(builtArtifacts); // Set the bi-directional mapping for (Artifact artifact : dependencies) { artifact.setBuildRecord(buildRecord); } buildRecord.setDependencies(dependencies); // Set the bi-directional mapping for (BuildRecordSet buildRecordSet : buildRecordSets) { buildRecordSet.getBuildRecords().add(buildRecord); } buildRecord.setBuildRecordSets(buildRecordSets); return buildRecord; } public Builder id(Integer id) { this.id = id; return this; } public Builder buildContentId(String buildContentId) { this.buildContentId = buildContentId; return this; } public Builder startTime(Timestamp startTime) { this.startTime = startTime; return this; } public Builder endTime(Timestamp endTime) { this.endTime = endTime; return this; } public Builder latestBuildConfiguration(BuildConfiguration latestBuildConfiguration) { this.latestBuildConfiguration = latestBuildConfiguration; return this; } public Builder buildConfigurationAudited(BuildConfigurationAudited buildConfigurationAudited) { this.buildConfigurationAudited = buildConfigurationAudited; return this; } public Builder user(User user) { this.user = user; return this; } public Builder buildLog(String buildLog) { this.buildLog = buildLog; return this; } public Builder status(BuildStatus status) { this.status = status; return this; } public Builder builtArtifact(Artifact builtArtifact) { this.builtArtifacts.add(builtArtifact); return this; } public Builder builtArtifacts(List<Artifact> builtArtifacts) { this.builtArtifacts = builtArtifacts; return this; } public Builder dependency(Artifact builtArtifact) { this.dependencies.add(builtArtifact); return this; } public Builder dependencies(List<Artifact> dependencies) { this.dependencies = dependencies; return this; } public Builder buildDriverId(String buildDriverId) { this.buildDriverId = buildDriverId; return this; } public Builder systemImage(SystemImage systemImage) { this.systemImage = systemImage; return this; } public Builder buildRecordSets(List<BuildRecordSet> buildRecordSets) { this.buildRecordSets = buildRecordSets; return this; } public Builder buildConfigSetRecord(BuildConfigSetRecord buildConfigSetRecord) { this.buildConfigSetRecord = buildConfigSetRecord; return this; } } }
Polishing of leftovers
model/src/main/java/org/jboss/pnc/model/BuildRecord.java
Polishing of leftovers
<ide><path>odel/src/main/java/org/jboss/pnc/model/BuildRecord.java <ide> private static final long serialVersionUID = -5472083609387609797L; <ide> <ide> public static final String SEQUENCE_NAME = "build_record_id_seq"; <del> // public static final String PREPARED_STATEMENT_INSERT = "INSERT INTO buildrecord (" <del> // + "id, buildcontentid, builddriverid, buildlog, endtime, starttime, " <del> // + "status, buildconfiguration_id, buildconfiguration_rev, user_id, systemimage_id, buildconfigsetrecord_id) " <del> // + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; <ide> <ide> @Id <ide> private Integer id;
Java
mit
6692e0395b9033e4c6406e6feac6b9a58f90f4dc
0
agpartha/java
package io.anand.springboot; import java.util.Arrays; import java.util.List; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @Api(value="/users", description="Operations pertaining to Users") public class UserController { @Autowired private UserService userService; // @RequestMapping(method=RequestMethod.GET, value="/users") @GetMapping("/users") @ApiOperation(value = "Returns list of users", notes = "") public List<User> getUsers () { return userService.getUsers(); } // @RequestMapping(method=RequestMethod.GET, value="/users/{name}") @GetMapping("/users/{name}") @ApiOperation(value = "Lookup an user information by name", notes = "") public User getUser (@PathVariable String name) { return userService.getUser(name); } @RequestMapping(method=RequestMethod.PUT, value="/users/{name}") @PutMapping("/users/{name}") @ApiOperation(value = "Update an user information", notes = "") public User updUser (@PathVariable String name, @RequestBody User newUser) { return userService.updUser(name, newUser); } @RequestMapping(method=RequestMethod.POST, value="/users/") @PostMapping("/users") @ApiOperation(value = "Create a new user", notes = "") public boolean addUser (@RequestBody User user) { return userService.addUser(user); } @RequestMapping(method=RequestMethod.DELETE, value="/users/{name}") @DeleteMapping("/users/{name}") @ApiOperation(value = "Delete a new user", notes = "") public boolean remUser (@RequestBody User user) { return userService.remUser(user); } }
simplerest/src/main/java/io/anand/springboot/UserController.java
package io.anand.springboot; import java.util.Arrays; import java.util.List; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @Api(value="/users", description="Operations pertaining to Users") public class UserController { @Autowired private UserService userService; // @RequestMapping(method=RequestMethod.GET, value="/users") @GetMapping("/users") @ApiOperation(value = "Returns list of users", notes = "") public List<User> getUsers () { return userService.getUsers(); } @RequestMapping(method=RequestMethod.GET, value="/users/{name}") @ApiOperation(value = "Lookup an user information by name", notes = "") public User getUser (@PathVariable String name) { return userService.getUser(name); } @RequestMapping(method=RequestMethod.PUT, value="/users/{name}") @ApiOperation(value = "Update an user information", notes = "") public User updUser (@PathVariable String name, @RequestBody User newUser) { return userService.updUser(name, newUser); } @RequestMapping(method=RequestMethod.POST, value="/users/") @ApiOperation(value = "Create a new user", notes = "") public boolean addUser (@RequestBody User user) { return userService.addUser(user); } @RequestMapping(method=RequestMethod.DELETE, value="/users/{name}") @ApiOperation(value = "Delete a new user", notes = "") public boolean remUser (@RequestBody User user) { return userService.remUser(user); } }
move to method specific mapping annotations
simplerest/src/main/java/io/anand/springboot/UserController.java
move to method specific mapping annotations
<ide><path>implerest/src/main/java/io/anand/springboot/UserController.java <ide> return userService.getUsers(); <ide> } <ide> <del> @RequestMapping(method=RequestMethod.GET, value="/users/{name}") <add>// @RequestMapping(method=RequestMethod.GET, value="/users/{name}") <add> @GetMapping("/users/{name}") <ide> @ApiOperation(value = "Lookup an user information by name", <ide> notes = "") <ide> public User getUser (@PathVariable String name) { <ide> } <ide> <ide> @RequestMapping(method=RequestMethod.PUT, value="/users/{name}") <add> @PutMapping("/users/{name}") <ide> @ApiOperation(value = "Update an user information", <ide> notes = "") <ide> public User updUser (@PathVariable String name, @RequestBody User newUser) { <ide> } <ide> <ide> @RequestMapping(method=RequestMethod.POST, value="/users/") <add> @PostMapping("/users") <ide> @ApiOperation(value = "Create a new user", <ide> notes = "") <ide> public boolean addUser (@RequestBody User user) { <ide> } <ide> <ide> @RequestMapping(method=RequestMethod.DELETE, value="/users/{name}") <add> @DeleteMapping("/users/{name}") <ide> @ApiOperation(value = "Delete a new user", <ide> notes = "") <ide> public boolean remUser (@RequestBody User user) {
Java
apache-2.0
713356baf4e938f80bddf170876337487eee7d03
0
stephanenicolas/toothpick,stephanenicolas/toothpick,stephanenicolas/toothpick
package toothpick.compiler.factory; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.inject.Inject; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.JavaFileObject; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.tools.Diagnostic.Kind.ERROR; @SupportedAnnotationTypes({ "javax.inject.Inject" }) public class FactoryProcessor extends AbstractProcessor { private Elements elementUtils; private Types typeUtils; private Filer filer; @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); System.out.println("coucou"); elementUtils = processingEnv.getElementUtils(); typeUtils = processingEnv.getTypeUtils(); filer = processingEnv.getFiler(); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { System.out.println("coucou"); Map<TypeElement, FactoryInjectionTarget> targetClassMap = findAndParseTargets(roundEnv); for (Map.Entry<TypeElement, FactoryInjectionTarget> entry : targetClassMap.entrySet()) { TypeElement typeElement = entry.getKey(); FactoryInjectionTarget factoryInjectionTarget = entry.getValue(); Writer writer = null; // Generate the ExtraInjector try { FactoryGenerator factoryGenerator = new FactoryGenerator(factoryInjectionTarget); JavaFileObject jfo = filer.createSourceFile(factoryGenerator.getFqcn(), typeElement); writer = jfo.openWriter(); writer.write(factoryGenerator.brewJava()); } catch (IOException e) { error(typeElement, "Unable to write factory for type %s: %s", typeElement, e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { error(typeElement, "Unable to close factory source file for type %s: %s", typeElement, e.getMessage()); } } } } return true; } private Map<TypeElement, FactoryInjectionTarget> findAndParseTargets(RoundEnvironment roundEnv) { Map<TypeElement, FactoryInjectionTarget> targetClassMap = new LinkedHashMap<>(); for (Element element : roundEnv.getElementsAnnotatedWith(Inject.class)) { if (element.getKind() == ElementKind.CONSTRUCTOR) { try { parseInject(element, targetClassMap); } catch (Exception e) { StringWriter stackTrace = new StringWriter(); e.printStackTrace(new PrintWriter(stackTrace)); error(element, "Unable to generate factory when parsing @Inject.\n\n%s", stackTrace.toString()); } } } return targetClassMap; } private void parseInject(Element element, Map<TypeElement, FactoryInjectionTarget> targetClassMap) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify common generated code restrictions. if (!isValidInjectConstructor(element)) { return; } // Another constructor already used for the class. if (targetClassMap.containsKey(enclosingElement)) { throw new IllegalStateException( String.format("@%s class %s must not have more than one " + "annotated constructor.", Inject.class.getSimpleName(), element.getSimpleName())); } targetClassMap.put(enclosingElement, createInjectionTarget(element)); } private boolean isValidInjectConstructor(Element element) { boolean valid = true; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify modifiers. Set<Modifier> modifiers = element.getModifiers(); if (modifiers.contains(PRIVATE)) { error(element, "@%s constructors must not be private. (%s)", Inject.class.getSimpleName(), enclosingElement.getQualifiedName()); valid = false; } // Verify parent modifiers. Set<Modifier> parentModifiers = enclosingElement.getModifiers(); //TODO should not be a non static inner class neither if (parentModifiers.contains(PRIVATE)) { error(element, "@%s class %s must not be private or static.", Inject.class.getSimpleName(), element.getSimpleName()); valid = false; } return valid; } private FactoryInjectionTarget createInjectionTarget(Element element) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); final String classPackage = getPackageName(enclosingElement); final String className = getClassName(enclosingElement, classPackage); final String targetClass = enclosingElement.getQualifiedName().toString(); final boolean hasSingletonAnnotation = hasAnnotationWithName(enclosingElement, "Singleton"); final boolean hasProducesSingletonAnnotation = hasAnnotationWithName(enclosingElement, "ProvidesSingleton"); boolean needsMemberInjection = false; while (!"java.lang.Object".equals(enclosingElement.getQualifiedName().toString())) { List<? extends Element> enclosedElements = enclosingElement.getEnclosedElements(); for (Element enclosedElement : enclosedElements) { if (enclosedElement.getAnnotation(Inject.class) != null && enclosedElement.getKind() == ElementKind.FIELD) { needsMemberInjection = true; break; } } enclosingElement = (TypeElement) ((DeclaredType) enclosingElement.getSuperclass()).asElement(); } FactoryInjectionTarget factoryInjectionTarget = new FactoryInjectionTarget(classPackage, className, targetClass, hasSingletonAnnotation, hasProducesSingletonAnnotation, needsMemberInjection); addParameters(element, factoryInjectionTarget); return factoryInjectionTarget; } private void addParameters(Element element, FactoryInjectionTarget factoryInjectionTarget) { ExecutableElement executableElement = (ExecutableElement) element; for (VariableElement variableElement : executableElement.getParameters()) { factoryInjectionTarget.parameters.add(variableElement.asType()); } } private String getPackageName(TypeElement type) { return elementUtils.getPackageOf(type).getQualifiedName().toString(); } private static String getClassName(TypeElement type, String packageName) { int packageLen = packageName.length() + 1; return type.getQualifiedName().toString().substring(packageLen).replace('.', '$'); } /** * Returns {@code true} if the an annotation is found on the given element with the given class * name (not fully qualified). */ private static boolean hasAnnotationWithName(Element element, String simpleName) { for (AnnotationMirror mirror : element.getAnnotationMirrors()) { final Element annnotationElement = mirror.getAnnotationType().asElement(); String annotationName = annnotationElement.getSimpleName().toString(); if (simpleName.equals(annotationName)) { return true; } } return false; } private void error(Element element, String message, Object... args) { processingEnv.getMessager().printMessage(ERROR, String.format(message, args), element); } }
toothpick-compiler/src/main/java/toothpick/compiler/factory/FactoryProcessor.java
package toothpick.compiler.factory; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.inject.Inject; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.JavaFileObject; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.tools.Diagnostic.Kind.ERROR; @SupportedAnnotationTypes({ "javax.inject.Inject" }) public class FactoryProcessor extends AbstractProcessor { private Elements elementUtils; private Types typeUtils; private Filer filer; @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); System.out.println("coucou"); elementUtils = processingEnv.getElementUtils(); typeUtils = processingEnv.getTypeUtils(); filer = processingEnv.getFiler(); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { System.out.println("coucou"); Map<TypeElement, FactoryInjectionTarget> targetClassMap = findAndParseTargets(roundEnv); for (Map.Entry<TypeElement, FactoryInjectionTarget> entry : targetClassMap.entrySet()) { TypeElement typeElement = entry.getKey(); FactoryInjectionTarget factoryInjectionTarget = entry.getValue(); Writer writer = null; // Generate the ExtraInjector try { FactoryGenerator factoryGenerator = new FactoryGenerator(factoryInjectionTarget); JavaFileObject jfo = filer.createSourceFile(factoryGenerator.getFqcn(), typeElement); writer = jfo.openWriter(); writer.write(factoryGenerator.brewJava()); } catch (IOException e) { error(typeElement, "Unable to write factory for type %s: %s", typeElement, e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { error(typeElement, "Unable to close factory source file for type %s: %s", typeElement, e.getMessage()); } } } } return true; } private Map<TypeElement, FactoryInjectionTarget> findAndParseTargets(RoundEnvironment roundEnv) { Map<TypeElement, FactoryInjectionTarget> targetClassMap = new LinkedHashMap<>(); for (Element element : roundEnv.getElementsAnnotatedWith(Inject.class)) { if (element.getKind() == ElementKind.CONSTRUCTOR) { try { parseInject(element, targetClassMap); } catch (Exception e) { StringWriter stackTrace = new StringWriter(); e.printStackTrace(new PrintWriter(stackTrace)); error(element, "Unable to generate factory when parsing @Inject.\n\n%s", stackTrace.toString()); } } } return targetClassMap; } private void parseInject(Element element, Map<TypeElement, FactoryInjectionTarget> targetClassMap) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify common generated code restrictions. if (!isValidInjectConstructor(element)) { return; } // Another constructor already used for the class. if (targetClassMap.containsKey(enclosingElement)) { throw new IllegalStateException( String.format("@%s class %s must not have more than one " + "annotated constructor.", Inject.class.getSimpleName(), element.getSimpleName())); } targetClassMap.put(enclosingElement, createInjectionTarget(element)); } private boolean isValidInjectConstructor(Element element) { boolean valid = true; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify modifiers. Set<Modifier> modifiers = element.getModifiers(); if (modifiers.contains(PRIVATE)) { error(element, "@%s constructors must not be private. (%s)", Inject.class.getSimpleName(), enclosingElement.getQualifiedName()); valid = false; } // Verify parent modifiers. Set<Modifier> parentModifiers = enclosingElement.getModifiers(); //TODO should not be a non static inner class neither if (parentModifiers.contains(PRIVATE)) { error(element, "@%s class %s must not be private or static.", Inject.class.getSimpleName(), element.getSimpleName()); valid = false; } return valid; } private FactoryInjectionTarget createInjectionTarget(Element element) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); final String classPackage = getPackageName(enclosingElement); final String className = getClassName(enclosingElement, classPackage); final String targetClass = enclosingElement.getQualifiedName().toString(); final boolean hasSingletonAnnotation = hasAnnotationWithName(enclosingElement, "Singleton"); final boolean hasProducesSingletonAnnotation = hasAnnotationWithName(enclosingElement, "ProvidesSingleton"); boolean needsMemberInjection = false; List<? extends Element> enclosedElements = enclosingElement.getEnclosedElements(); for (Element enclosedElement : enclosedElements) { if (enclosedElement.getAnnotation(Inject.class) != null && enclosedElement.getKind() == ElementKind.FIELD) { needsMemberInjection = true; break; } } FactoryInjectionTarget factoryInjectionTarget = new FactoryInjectionTarget(classPackage, className, targetClass, hasSingletonAnnotation, hasProducesSingletonAnnotation, needsMemberInjection); addParameters(element, factoryInjectionTarget); return factoryInjectionTarget; } private void addParameters(Element element, FactoryInjectionTarget factoryInjectionTarget) { ExecutableElement executableElement = (ExecutableElement) element; for (VariableElement variableElement : executableElement.getParameters()) { factoryInjectionTarget.parameters.add(variableElement.asType()); } } private String getPackageName(TypeElement type) { return elementUtils.getPackageOf(type).getQualifiedName().toString(); } private static String getClassName(TypeElement type, String packageName) { int packageLen = packageName.length() + 1; return type.getQualifiedName().toString().substring(packageLen).replace('.', '$'); } /** * Returns {@code true} if the an annotation is found on the given element with the given class * name (not fully qualified). */ private static boolean hasAnnotationWithName(Element element, String simpleName) { for (AnnotationMirror mirror : element.getAnnotationMirrors()) { final Element annnotationElement = mirror.getAnnotationType().asElement(); String annotationName = annnotationElement.getSimpleName().toString(); if (simpleName.equals(annotationName)) { return true; } } return false; } private void error(Element element, String message, Object... args) { processingEnv.getMessager().printMessage(ERROR, String.format(message, args), element); } }
Support inheritance.
toothpick-compiler/src/main/java/toothpick/compiler/factory/FactoryProcessor.java
Support inheritance.
<ide><path>oothpick-compiler/src/main/java/toothpick/compiler/factory/FactoryProcessor.java <ide> import javax.lang.model.element.Modifier; <ide> import javax.lang.model.element.TypeElement; <ide> import javax.lang.model.element.VariableElement; <add>import javax.lang.model.type.DeclaredType; <ide> import javax.lang.model.util.Elements; <ide> import javax.lang.model.util.Types; <ide> import javax.tools.JavaFileObject; <ide> final boolean hasSingletonAnnotation = hasAnnotationWithName(enclosingElement, "Singleton"); <ide> final boolean hasProducesSingletonAnnotation = hasAnnotationWithName(enclosingElement, "ProvidesSingleton"); <ide> boolean needsMemberInjection = false; <del> List<? extends Element> enclosedElements = enclosingElement.getEnclosedElements(); <del> for (Element enclosedElement : enclosedElements) { <del> if (enclosedElement.getAnnotation(Inject.class) != null && enclosedElement.getKind() == ElementKind.FIELD) { <del> needsMemberInjection = true; <del> break; <del> } <add> while (!"java.lang.Object".equals(enclosingElement.getQualifiedName().toString())) { <add> List<? extends Element> enclosedElements = enclosingElement.getEnclosedElements(); <add> for (Element enclosedElement : enclosedElements) { <add> if (enclosedElement.getAnnotation(Inject.class) != null && enclosedElement.getKind() == ElementKind.FIELD) { <add> needsMemberInjection = true; <add> break; <add> } <add> } <add> enclosingElement = (TypeElement) ((DeclaredType) enclosingElement.getSuperclass()).asElement(); <ide> } <ide> <ide> FactoryInjectionTarget factoryInjectionTarget =
Java
apache-2.0
577462c2fef963d3ece207b9a80c20169d3618fa
0
javild/opencga,opencb/opencga,opencb/opencga,j-coll/opencga,j-coll/opencga,j-coll/opencga,opencb/opencga,opencb/opencga,javild/opencga,javild/opencga,javild/opencga,opencb/opencga,opencb/opencga,j-coll/opencga,j-coll/opencga,javild/opencga,javild/opencga,j-coll/opencga
/* * Copyright 2015 OpenCB * * 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. */ package org.opencb.opencga.storage.core.alignment.tasks; import org.opencb.biodata.formats.alignment.AlignmentUtils; import org.opencb.biodata.formats.sequence.fasta.dbadaptor.CellBaseSequenceDBAdaptor; import org.opencb.biodata.formats.sequence.fasta.dbadaptor.SequenceDBAdaptor; import org.opencb.biodata.models.alignment.Alignment; import org.opencb.biodata.models.alignment.AlignmentRegion; import org.opencb.biodata.models.alignment.exceptions.ShortReferenceSequenceException; import org.opencb.biodata.models.core.Region; import org.opencb.commons.run.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; /** * Date: 27/03/14 * @author Jacobo Coll Moragon <[email protected]> */ public class AlignmentRegionCompactorTask extends Task<AlignmentRegion> { private final SequenceDBAdaptor adaptor; protected static Logger logger = LoggerFactory.getLogger(AlignmentRegionCompactorTask.class); public AlignmentRegionCompactorTask() { this.adaptor = new CellBaseSequenceDBAdaptor(); } public AlignmentRegionCompactorTask(SequenceDBAdaptor adaptor) { this.adaptor = adaptor; } @Override public boolean pre(){ try { adaptor.open(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } @Override public boolean post(){ try { adaptor.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } @Override public boolean apply(List<AlignmentRegion> batch) throws IOException { for(AlignmentRegion alignmentRegion : batch){ Region region = alignmentRegion.getRegion(); long start = region.getStart(); if(start <= 0){ start = 1; region.setStart(1); } logger.info("Asking for sequence: " + region.toString() + " size = " + (region.getEnd()-region.getStart())); String sequence = adaptor.getSequence(region); for(Alignment alignment : alignmentRegion.getAlignments()){ try { AlignmentUtils.completeDifferencesFromReference(alignment, sequence, start); } catch (ShortReferenceSequenceException e) { logger.warn("NOT ENOUGH REFERENCE SEQUENCE. " + alignment.getChromosome()+":"+alignment.getUnclippedStart() + "-" + alignment.getUnclippedEnd(), e); } } } return true; } }
opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/alignment/tasks/AlignmentRegionCompactorTask.java
/* * Copyright 2015 OpenCB * * 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. */ package org.opencb.opencga.storage.core.alignment.tasks; import org.opencb.biodata.formats.alignment.AlignmentHelper; import org.opencb.biodata.formats.sequence.fasta.dbadaptor.CellBaseSequenceDBAdaptor; import org.opencb.biodata.formats.sequence.fasta.dbadaptor.SequenceDBAdaptor; import org.opencb.biodata.models.alignment.Alignment; import org.opencb.biodata.models.alignment.AlignmentRegion; import org.opencb.biodata.models.alignment.exceptions.ShortReferenceSequenceException; import org.opencb.biodata.models.core.Region; import org.opencb.commons.run.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; /** * Date: 27/03/14 * @author Jacobo Coll Moragon <[email protected]> */ public class AlignmentRegionCompactorTask extends Task<AlignmentRegion> { private final SequenceDBAdaptor adaptor; protected static Logger logger = LoggerFactory.getLogger(AlignmentRegionCompactorTask.class); public AlignmentRegionCompactorTask() { this.adaptor = new CellBaseSequenceDBAdaptor(); } public AlignmentRegionCompactorTask(SequenceDBAdaptor adaptor) { this.adaptor = adaptor; } @Override public boolean pre(){ try { adaptor.open(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } @Override public boolean post(){ try { adaptor.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } @Override public boolean apply(List<AlignmentRegion> batch) throws IOException { for(AlignmentRegion alignmentRegion : batch){ Region region = alignmentRegion.getRegion(); long start = region.getStart(); if(start <= 0){ start = 1; region.setStart(1); } logger.info("Asking for sequence: " + region.toString() + " size = " + (region.getEnd()-region.getStart())); String sequence = adaptor.getSequence(region); for(Alignment alignment : alignmentRegion.getAlignments()){ try { AlignmentHelper.completeDifferencesFromReference(alignment, sequence, start); } catch (ShortReferenceSequenceException e) { logger.warn("NOT ENOUGH REFERENCE SEQUENCE. " + alignment.getChromosome()+":"+alignment.getUnclippedStart() + "-" + alignment.getUnclippedEnd(), e); } } } return true; } }
storage: Biodata classname change, AlignmentHelper -> AlignmentUtils
opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/alignment/tasks/AlignmentRegionCompactorTask.java
storage: Biodata classname change, AlignmentHelper -> AlignmentUtils
<ide><path>pencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/alignment/tasks/AlignmentRegionCompactorTask.java <ide> <ide> package org.opencb.opencga.storage.core.alignment.tasks; <ide> <del>import org.opencb.biodata.formats.alignment.AlignmentHelper; <add>import org.opencb.biodata.formats.alignment.AlignmentUtils; <ide> import org.opencb.biodata.formats.sequence.fasta.dbadaptor.CellBaseSequenceDBAdaptor; <ide> import org.opencb.biodata.formats.sequence.fasta.dbadaptor.SequenceDBAdaptor; <ide> import org.opencb.biodata.models.alignment.Alignment; <ide> String sequence = adaptor.getSequence(region); <ide> for(Alignment alignment : alignmentRegion.getAlignments()){ <ide> try { <del> AlignmentHelper.completeDifferencesFromReference(alignment, sequence, start); <add> AlignmentUtils.completeDifferencesFromReference(alignment, sequence, start); <ide> } catch (ShortReferenceSequenceException e) { <ide> logger.warn("NOT ENOUGH REFERENCE SEQUENCE. " + alignment.getChromosome()+":"+alignment.getUnclippedStart() + "-" + alignment.getUnclippedEnd(), e); <ide> }
Java
mit
2b1d3221e3398c201a86ab4ab0a99cd2dbd6f71c
0
Instabug/instabug-reactnative,Instabug/instabug-reactnative,Instabug/instabug-reactnative,Instabug/instabug-reactnative,Instabug/instabug-reactnative
package com.instabug.reactlibrary; import android.app.Application; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import com.instabug.bug.BugReporting; import com.instabug.library.Feature; import com.instabug.library.Instabug; import com.instabug.library.InstabugColorTheme; import com.instabug.library.invocation.InstabugInvocationEvent; import com.instabug.library.invocation.util.InstabugFloatingButtonEdge; import com.instabug.library.visualusersteps.State; import com.instabug.reactlibrary.utils.InstabugUtil; import android.graphics.Color; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class RNInstabugReactnativePackage implements ReactPackage { private static final String TAG = RNInstabugReactnativePackage.class.getSimpleName(); private Application androidApplication; private String mAndroidApplicationToken; private Instabug mInstabug; private Instabug.Builder mBuilder; private ArrayList<InstabugInvocationEvent> invocationEvents = new ArrayList<>(); private InstabugColorTheme instabugColorTheme = InstabugColorTheme.InstabugColorThemeLight; public RNInstabugReactnativePackage(String androidApplicationToken, Application androidApplication, String[] invocationEventValues, String primaryColor, InstabugFloatingButtonEdge floatingButtonEdge, Integer offset, boolean crashReportingEnabled) { this.androidApplication = androidApplication; this.mAndroidApplicationToken = androidApplicationToken; //setting invocation event this.parseInvocationEvent(invocationEventValues); setBaseUrlForDeprecationLogs(); new Instabug.Builder(this.androidApplication, this.mAndroidApplicationToken) .setInvocationEvents(this.invocationEvents.toArray(new InstabugInvocationEvent[0])) .setCrashReportingState(crashReportingEnabled ? Feature.State.ENABLED: Feature.State.DISABLED) .setReproStepsState(State.DISABLED) .build(); if(primaryColor != null) Instabug.setPrimaryColor(Color.parseColor(primaryColor)); if(floatingButtonEdge != null) BugReporting.setFloatingButtonEdge(floatingButtonEdge); if(offset != null) BugReporting.setFloatingButtonOffset(offset); } public RNInstabugReactnativePackage(String androidApplicationToken, Application androidApplication, String[] invocationEventValues, String primaryColor) { new RNInstabugReactnativePackage(androidApplicationToken,androidApplication,invocationEventValues,primaryColor, InstabugFloatingButtonEdge.LEFT,250, true); } private void parseInvocationEvent(String[] invocationEventValues) { for (int i = 0; i < invocationEventValues.length; i++) { if (invocationEventValues[i].equals("button")) { this.invocationEvents.add(InstabugInvocationEvent.FLOATING_BUTTON); } else if (invocationEventValues[i].equals("swipe")) { this.invocationEvents.add(InstabugInvocationEvent.TWO_FINGER_SWIPE_LEFT); } else if (invocationEventValues[i].equals("shake")) { this.invocationEvents.add(InstabugInvocationEvent.SHAKE); } else if (invocationEventValues[i].equals("screenshot")) { this.invocationEvents.add(InstabugInvocationEvent.SCREENSHOT); } else if (invocationEventValues[i].equals("none")) { this.invocationEvents.add(InstabugInvocationEvent.NONE); } } if (invocationEvents.isEmpty()) { invocationEvents.add(InstabugInvocationEvent.SHAKE); } } private void setBaseUrlForDeprecationLogs() { try { Method method = InstabugUtil.getMethod(Class.forName("com.instabug.library.util.InstabugDeprecationLogger"), "setBaseUrl", String.class); if (method != null) { method.invoke(null, "https://docs.instabug.com/docs/react-native-sdk-migration-guide"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new RNInstabugReactnativeModule(reactContext, this.androidApplication, this.mInstabug)); return modules; } public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } public static class Builder { //FloatingButtonEdge private final String FLOATING_BUTTON_EDGE_RIGHT = "right"; private final String FLOATING_BUTTON_EDGE_LEFT = "left"; String androidApplicationToken; Application application; String[] invocationEvents; String primaryColor; InstabugFloatingButtonEdge floatingButtonEdge; int offset; boolean isCrashReportingEnabled = true; public Builder(String androidApplicationToken, Application application) { this.androidApplicationToken = androidApplicationToken; this.application = application; } public Builder setInvocationEvent(String... invocationEvents) { this.invocationEvents = invocationEvents; return this; } public Builder setCrashReportingEnabled(boolean enabled) { this.isCrashReportingEnabled = enabled; return this; } public Builder setPrimaryColor(String primaryColor) { this.primaryColor = primaryColor; return this; } public Builder setFloatingEdge(String floatingEdge) { this.floatingButtonEdge = getFloatingButtonEdge(floatingEdge); return this; } public Builder setFloatingButtonOffsetFromTop(int offset) { this.offset = offset; return this; } public RNInstabugReactnativePackage build() { return new RNInstabugReactnativePackage(androidApplicationToken,application,invocationEvents,primaryColor,floatingButtonEdge,offset, isCrashReportingEnabled); } private InstabugFloatingButtonEdge getFloatingButtonEdge(String floatingButtonEdgeValue) { InstabugFloatingButtonEdge floatingButtonEdge = InstabugFloatingButtonEdge.RIGHT; try { if (floatingButtonEdgeValue.equals(FLOATING_BUTTON_EDGE_LEFT)) { floatingButtonEdge = InstabugFloatingButtonEdge.LEFT; } else if (floatingButtonEdgeValue.equals(FLOATING_BUTTON_EDGE_RIGHT)) { floatingButtonEdge = InstabugFloatingButtonEdge.RIGHT; } return floatingButtonEdge; } catch(Exception e) { e.printStackTrace(); return floatingButtonEdge; } } } }
android/src/main/java/com/instabug/reactlibrary/RNInstabugReactnativePackage.java
package com.instabug.reactlibrary; import android.app.Application; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import com.instabug.bug.BugReporting; import com.instabug.library.Feature; import com.instabug.library.Instabug; import com.instabug.library.InstabugColorTheme; import com.instabug.library.invocation.InstabugInvocationEvent; import com.instabug.library.invocation.util.InstabugFloatingButtonEdge; import com.instabug.library.visualusersteps.State; import com.instabug.reactlibrary.utils.InstabugUtil; import android.graphics.Color; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class RNInstabugReactnativePackage implements ReactPackage { private static final String TAG = RNInstabugReactnativePackage.class.getSimpleName(); private Application androidApplication; private String mAndroidApplicationToken; private Instabug mInstabug; private Instabug.Builder mBuilder; private ArrayList<InstabugInvocationEvent> invocationEvents = new ArrayList<>(); private InstabugColorTheme instabugColorTheme = InstabugColorTheme.InstabugColorThemeLight; public RNInstabugReactnativePackage(String androidApplicationToken, Application androidApplication, String[] invocationEventValues, String primaryColor, InstabugFloatingButtonEdge floatingButtonEdge, Integer offset, boolean crashReportingEnabled) { this.androidApplication = androidApplication; this.mAndroidApplicationToken = androidApplicationToken; //setting invocation event this.parseInvocationEvent(invocationEventValues); setBaseUrlForDeprecationLogs(); new Instabug.Builder(this.androidApplication, this.mAndroidApplicationToken) .setInvocationEvents(this.invocationEvents.toArray(new InstabugInvocationEvent[0])) .setCrashReportingState(crashReportingEnabled ? Feature.State.ENABLED: Feature.State.DISABLED) .setReproStepsState(State.DISABLED) .build(); if(primaryColor != null) Instabug.setPrimaryColor(Color.parseColor(primaryColor)); if(floatingButtonEdge != null) BugReporting.setFloatingButtonEdge(floatingButtonEdge); if(offset != null) BugReporting.setFloatingButtonOffset(offset); } public RNInstabugReactnativePackage(String androidApplicationToken, Application androidApplication, String[] invocationEventValues, String primaryColor) { new RNInstabugReactnativePackage(androidApplicationToken,androidApplication,invocationEventValues,primaryColor, InstabugFloatingButtonEdge.LEFT,250, true); } private void parseInvocationEvent(String[] invocationEventValues) { for (int i = 0; i < invocationEventValues.length; i++) { if (invocationEventValues[i].equals("button")) { this.invocationEvents.add(InstabugInvocationEvent.FLOATING_BUTTON); } else if (invocationEventValues[i].equals("swipe")) { this.invocationEvents.add(InstabugInvocationEvent.TWO_FINGER_SWIPE_LEFT); } else if (invocationEventValues[i].equals("shake")) { this.invocationEvents.add(InstabugInvocationEvent.SHAKE); } else if (invocationEventValues[i].equals("none")) { this.invocationEvents.add(InstabugInvocationEvent.NONE); } } if (invocationEvents.isEmpty()) { invocationEvents.add(InstabugInvocationEvent.SHAKE); } } private void setBaseUrlForDeprecationLogs() { try { Method method = InstabugUtil.getMethod(Class.forName("com.instabug.library.util.InstabugDeprecationLogger"), "setBaseUrl", String.class); if (method != null) { method.invoke(null, "https://docs.instabug.com/docs/react-native-sdk-migration-guide"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new RNInstabugReactnativeModule(reactContext, this.androidApplication, this.mInstabug)); return modules; } public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } public static class Builder { //FloatingButtonEdge private final String FLOATING_BUTTON_EDGE_RIGHT = "right"; private final String FLOATING_BUTTON_EDGE_LEFT = "left"; String androidApplicationToken; Application application; String[] invocationEvents; String primaryColor; InstabugFloatingButtonEdge floatingButtonEdge; int offset; boolean isCrashReportingEnabled = true; public Builder(String androidApplicationToken, Application application) { this.androidApplicationToken = androidApplicationToken; this.application = application; } public Builder setInvocationEvent(String... invocationEvents) { this.invocationEvents = invocationEvents; return this; } public Builder setCrashReportingEnabled(boolean enabled) { this.isCrashReportingEnabled = enabled; return this; } public Builder setPrimaryColor(String primaryColor) { this.primaryColor = primaryColor; return this; } public Builder setFloatingEdge(String floatingEdge) { this.floatingButtonEdge = getFloatingButtonEdge(floatingEdge); return this; } public Builder setFloatingButtonOffsetFromTop(int offset) { this.offset = offset; return this; } public RNInstabugReactnativePackage build() { return new RNInstabugReactnativePackage(androidApplicationToken,application,invocationEvents,primaryColor,floatingButtonEdge,offset, isCrashReportingEnabled); } private InstabugFloatingButtonEdge getFloatingButtonEdge(String floatingButtonEdgeValue) { InstabugFloatingButtonEdge floatingButtonEdge = InstabugFloatingButtonEdge.RIGHT; try { if (floatingButtonEdgeValue.equals(FLOATING_BUTTON_EDGE_LEFT)) { floatingButtonEdge = InstabugFloatingButtonEdge.LEFT; } else if (floatingButtonEdgeValue.equals(FLOATING_BUTTON_EDGE_RIGHT)) { floatingButtonEdge = InstabugFloatingButtonEdge.RIGHT; } return floatingButtonEdge; } catch(Exception e) { e.printStackTrace(); return floatingButtonEdge; } } } }
parse screenshot invocation event type (#256) Fix the Android implementation is missing a branch in the `parseInvocationEvent` loop for the `InstabugInvocationEvent.SCREENSHOT` type. It prevents users from using the screenshot invocation on Android React Native apps.
android/src/main/java/com/instabug/reactlibrary/RNInstabugReactnativePackage.java
parse screenshot invocation event type (#256)
<ide><path>ndroid/src/main/java/com/instabug/reactlibrary/RNInstabugReactnativePackage.java <ide> <ide> } else if (invocationEventValues[i].equals("shake")) { <ide> this.invocationEvents.add(InstabugInvocationEvent.SHAKE); <add> <add> } else if (invocationEventValues[i].equals("screenshot")) { <add> this.invocationEvents.add(InstabugInvocationEvent.SCREENSHOT); <ide> <ide> } else if (invocationEventValues[i].equals("none")) { <ide> this.invocationEvents.add(InstabugInvocationEvent.NONE);
Java
apache-2.0
e24e2cd74d596584545644e1b995295f510afd4b
0
opencirclesolutions/dynamo,opencirclesolutions/dynamo
/* 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. */ package com.ocs.dynamo.domain.model.impl; import com.google.common.collect.Lists; import com.ocs.dynamo.constants.DynamoConstants; import com.ocs.dynamo.domain.AbstractEntity; import com.ocs.dynamo.domain.model.AttributeDateType; import com.ocs.dynamo.domain.model.AttributeModel; import com.ocs.dynamo.domain.model.AttributeSelectMode; import com.ocs.dynamo.domain.model.AttributeTextFieldMode; import com.ocs.dynamo.domain.model.AttributeType; import com.ocs.dynamo.domain.model.CheckboxMode; import com.ocs.dynamo.domain.model.EditableType; import com.ocs.dynamo.domain.model.EntityModel; import com.ocs.dynamo.domain.model.FieldFactory; import com.ocs.dynamo.domain.model.NumberSelectMode; import com.ocs.dynamo.exception.OCSRuntimeException; import com.ocs.dynamo.service.BaseService; import com.ocs.dynamo.service.MessageService; import com.ocs.dynamo.service.ServiceLocator; import com.ocs.dynamo.service.ServiceLocatorFactory; import com.ocs.dynamo.ui.component.EntityComboBox.SelectMode; import com.ocs.dynamo.ui.component.EntityLookupField; import com.ocs.dynamo.ui.component.FancyListSelect; import com.ocs.dynamo.ui.component.QuickAddEntityComboBox; import com.ocs.dynamo.ui.component.QuickAddListSelect; import com.ocs.dynamo.ui.component.SimpleTokenFieldSelect; import com.ocs.dynamo.ui.component.TimeField; import com.ocs.dynamo.ui.component.TokenFieldSelect; import com.ocs.dynamo.ui.component.URLField; import com.ocs.dynamo.ui.composite.form.CollectionTable; import com.ocs.dynamo.ui.composite.layout.FormOptions; import com.ocs.dynamo.ui.converter.BigDecimalToDoubleConverter; import com.ocs.dynamo.ui.converter.ConverterFactory; import com.ocs.dynamo.ui.converter.IntToDoubleConverter; import com.ocs.dynamo.ui.converter.LocalDateWeekCodeConverter; import com.ocs.dynamo.ui.converter.LongToDoubleConverter; import com.ocs.dynamo.ui.converter.WeekCodeConverter; import com.ocs.dynamo.ui.utils.VaadinUtils; import com.ocs.dynamo.ui.validator.URLValidator; import com.ocs.dynamo.util.SystemPropertyUtils; import com.ocs.dynamo.utils.DateUtils; import com.ocs.dynamo.utils.NumberUtils; import com.vaadin.data.Container; import com.vaadin.data.Container.Filter; import com.vaadin.data.Item; import com.vaadin.data.fieldgroup.DefaultFieldGroupFieldFactory; import com.vaadin.data.sort.SortOrder; import com.vaadin.data.validator.BeanValidator; import com.vaadin.data.validator.EmailValidator; import com.vaadin.shared.data.sort.SortDirection; import com.vaadin.shared.ui.combobox.FilteringMode; import com.vaadin.shared.ui.datefield.Resolution; import com.vaadin.ui.AbstractComponent; import com.vaadin.ui.AbstractField; import com.vaadin.ui.AbstractSelect; import com.vaadin.ui.AbstractTextField; import com.vaadin.ui.ComboBox; import com.vaadin.ui.Component; import com.vaadin.ui.DateField; import com.vaadin.ui.DefaultFieldFactory; import com.vaadin.ui.Field; import com.vaadin.ui.Slider; import com.vaadin.ui.TableFieldFactory; import com.vaadin.ui.TextArea; import com.vaadin.ui.TextField; import com.vaadin.ui.UI; import org.apache.commons.lang.StringUtils; import org.vaadin.teemu.switchui.Switch; import java.io.Serializable; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Extension of the standard Vaadin field factory for creating custom fields * * @author bas.rutten * @param <T> * the type of the entity for which to create a field */ public class ModelBasedFieldFactory<T> extends DefaultFieldGroupFieldFactory implements TableFieldFactory { private static final long serialVersionUID = -5684112523268959448L; private static final ConcurrentMap<String, ModelBasedFieldFactory<?>> nonValidatingInstances = new ConcurrentHashMap<>(); private static final ConcurrentMap<String, ModelBasedFieldFactory<?>> searchInstances = new ConcurrentHashMap<>(); private static final ConcurrentMap<String, ModelBasedFieldFactory<?>> validatingInstances = new ConcurrentHashMap<>(); private final MessageService messageService; private final EntityModel<T> model; private final ServiceLocator serviceLocator = ServiceLocatorFactory.getServiceLocator(); private final Collection<FieldFactory> fieldFactories; // indicates whether the system is in search mode. In search mode, // components for // some attributes are constructed differently (e.g. we render two search // fields to be able to // search for a range of integers) private final boolean search; // indicates whether extra validators must be added. This is the case when // using the field factory in an // editable table private final boolean validate; /** * Constructor * * @param model * the entity model * @param messageService * the message service * @param validate * whether to add extra validators (this is the case when the field * is displayed inside a table) * @param search * whether the fields are displayed inside a search form (this has an * effect on the construction of some fields) */ public ModelBasedFieldFactory(final EntityModel<T> model, final MessageService messageService, final boolean validate, final boolean search) { this.model = model; this.messageService = messageService; this.validate = validate; this.search = search; this.fieldFactories = serviceLocator.getServices(FieldFactory.class); } /** * Returns an appropriate instance from the pool, or creates a new one * * @param model * the entity model * @param messageService * @return */ @SuppressWarnings("unchecked") public static <T> ModelBasedFieldFactory<T> getInstance(final EntityModel<T> model, final MessageService messageService) { if (!nonValidatingInstances.containsKey(model.getReference())) { nonValidatingInstances.put(model.getReference(), new ModelBasedFieldFactory<>(model, messageService, false, false)); } return (ModelBasedFieldFactory<T>) nonValidatingInstances.get(model.getReference()); } /** * Returns an appropriate instance from the pool, or creates a new one * * @param model * @param messageService * @return */ @SuppressWarnings("unchecked") public static <T> ModelBasedFieldFactory<T> getSearchInstance(final EntityModel<T> model, final MessageService messageService) { if (!searchInstances.containsKey(model.getReference())) { searchInstances.put(model.getReference(), new ModelBasedFieldFactory<>(model, messageService, false, true)); } return (ModelBasedFieldFactory<T>) searchInstances.get(model.getReference()); } /** * Returns an appropriate instance from the pool, or creates a new one * * @param model * @param messageService * @return */ @SuppressWarnings("unchecked") public static <T> ModelBasedFieldFactory<T> getValidatingInstance(final EntityModel<T> model, final MessageService messageService) { if (!validatingInstances.containsKey(model.getReference())) { validatingInstances.put(model.getReference(), new ModelBasedFieldFactory<>(model, messageService, true, false)); } return (ModelBasedFieldFactory<T>) validatingInstances.get(model.getReference()); } /** * Construct a combo box that contains a list of String values * * @param values the list of values * @param am the attribute model * @return */ public static ComboBox constructStringListCombo(final List<String> values, final AttributeModel am) { final ComboBox cb = new ComboBox(); cb.setCaption(am.getDisplayName()); cb.addItems(values); cb.setFilteringMode(FilteringMode.CONTAINS); return cb; } /** * Constructs a combo box- the sort order will be taken from the entity model * * @param entityModel * the entity model to base the combo box on * @param attributeModel * the attribute model * @param filter * optional field filter - only items that match the filter will be * included * @return */ @SuppressWarnings("unchecked") public <ID extends Serializable, S extends AbstractEntity<ID>> AbstractField<?> constructComboBox( EntityModel<?> entityModel, final AttributeModel attributeModel, final Filter filter, final boolean search) { entityModel = resolveEntityModel(entityModel, attributeModel); final BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator .getServiceForEntity(entityModel.getEntityClass()); final SortOrder[] sos = constructSortOrder(entityModel); return new QuickAddEntityComboBox<>((EntityModel<S>) entityModel, attributeModel, service, SelectMode.FILTERED, filter, search, null, sos); } /** * Constructs a field based on an attribute model and possibly a field filter * * @param attributeModel * the attribute model * @param fieldFilters * the list of field filters * @param fieldEntityModel * the custom entity model for the field * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Field<?> constructField(final AttributeModel attributeModel, final Map<String, Filter> fieldFilters, final EntityModel<?> fieldEntityModel) { Field<?> field = null; // Are there any delegated component factories that can create this field? if (fieldFactories != null && !fieldFactories.isEmpty()) { for (final FieldFactory ff : fieldFactories) { final FieldFactoryContextImpl<?> c = new FieldFactoryContextImpl<>().setAttributeModel(attributeModel) .setFieldFilters(fieldFilters).setFieldEntityModel((EntityModel) fieldEntityModel); field = ff.constructField(c); if (field != null) { break; } } } if (field == null) { final Filter fieldFilter = fieldFilters == null ? null : fieldFilters.get(attributeModel.getPath()); if (fieldFilter != null) { if (AttributeType.MASTER.equals(attributeModel.getAttributeType())) { // create a combo box or lookup field field = constructSelectField(attributeModel, fieldEntityModel, fieldFilter); } else if (search && AttributeSelectMode.TOKEN.equals(attributeModel.getSearchSelectMode()) && AttributeType.BASIC.equals(attributeModel.getAttributeType())) { // simple token field (for distinct string values) field = constructSimpleTokenField( fieldEntityModel != null ? fieldEntityModel : attributeModel.getEntityModel(), attributeModel, attributeModel.getPath().substring(attributeModel.getPath().lastIndexOf('.') + 1), false, fieldFilter); } else { // detail relationship, render a multiple select field = this.constructCollectionSelect(fieldEntityModel, attributeModel, fieldFilter, true, search); } } else { field = this.createField(attributeModel.getPath(), fieldEntityModel); } } // Is it a required field? field.setRequired(search ? attributeModel.isRequiredForSearching() : attributeModel.isRequired()); // if (field instanceof AbstractComponent) { ((AbstractComponent) field).setImmediate(true); field.setCaption(attributeModel.getDisplayName()); } return field; } /** * Constructs a select component for selecting multiple values * * @param fieldEntityModel * the entity model of the entity to display in the field * @param attributeModel * the attribute model of the property that is displayed in the * ListSelect * @param fieldFilter * optional field filter * @param multipleSelect * is multiple select supported? * @param search * indicates whether the component is being used in a search screen * @return */ @SuppressWarnings("unchecked") public <ID extends Serializable, S extends AbstractEntity<ID>> Field<?> constructCollectionSelect( final EntityModel<?> fieldEntityModel, final AttributeModel attributeModel, final Filter fieldFilter, final boolean multipleSelect, final boolean search) { final EntityModel<?> em = resolveEntityModel(fieldEntityModel, attributeModel); final BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator.getServiceForEntity(em.getEntityClass()); final SortOrder[] sos = constructSortOrder(em); // mode depends on whether we are searching final AttributeSelectMode mode = search ? attributeModel.getSearchSelectMode() : attributeModel.getSelectMode(); if (AttributeSelectMode.LOOKUP.equals(mode)) { // lookup field - take care to NOT use the nested model here! return constructLookupField(fieldEntityModel, attributeModel, fieldFilter, search, true); } else if (AttributeSelectMode.FANCY_LIST.equals(mode)) { // fancy list select final FancyListSelect<ID, S> listSelect = new FancyListSelect<>(service, (EntityModel<S>) em, attributeModel, fieldFilter, search, sos); listSelect.setRows(SystemPropertyUtils.getDefaultListSelectRows()); return listSelect; } else if (AttributeSelectMode.LIST.equals(mode)) { // simple list select if everything else fails or is not applicable return new QuickAddListSelect<>((EntityModel<S>) em, attributeModel, service, fieldFilter, multipleSelect, SystemPropertyUtils.getDefaultListSelectRows(), sos); } else { // by default, use a token field return new TokenFieldSelect<>((EntityModel<S>) em, attributeModel, service, fieldFilter, search, sos); } } /** * Constructs a lookup field (field that brings up a popup search dialog) * * @param overruled * the entity model of the entity to display in the field * @param attributeModel * the attribute model of the property that is bound to the field * @param fieldFilter * optional field filter * @return */ @SuppressWarnings("unchecked") public <ID extends Serializable, S extends AbstractEntity<ID>> EntityLookupField<ID, S> constructLookupField( final EntityModel<?> overruled, final AttributeModel attributeModel, final Filter fieldFilter, final boolean search, final boolean multiSelect) { // for a lookup field, don't use the nested model but the base model - // this is // because the search in the popup screen is conducted on a "clean", // unnested entity list so // using a path from the parent entity makes no sense here final EntityModel<?> entityModel = overruled != null ? overruled : serviceLocator.getEntityModelFactory().getModel(attributeModel.getNormalizedType()); final BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator.getServiceForEntity( attributeModel.getMemberType() != null ? attributeModel.getMemberType() : entityModel.getEntityClass()); final SortOrder[] sos = constructSortOrder(entityModel); return new EntityLookupField<>(service, (EntityModel<S>) entityModel, attributeModel, fieldFilter, search, multiSelect, sos.length == 0 ? null : Lists.newArrayList(sos)); } /** * Create a combo box for searching on a boolean. This combo box contains three * values (yes, no, and null) * * @return */ public ComboBox constructSearchBooleanComboBox(final AttributeModel am) { final ComboBox cb = new ComboBox(); cb.addItem(Boolean.TRUE); cb.setItemCaption(Boolean.TRUE, am.getTrueRepresentation()); cb.addItem(Boolean.FALSE); cb.setItemCaption(Boolean.FALSE, am.getFalseRepresentation()); return cb; } /** * Constructs a token field for basic attributes (Strings) * * @param entityModel * the entity model to base the field on * @param attributeModel * the attribute model * @param distinctField * the field for which to return the distinct values * @param fieldFilter * field filter to apply in order to limit the search results * @return */ @SuppressWarnings("unchecked") private <ID extends Serializable, S extends AbstractEntity<ID>, O extends Comparable<O>> SimpleTokenFieldSelect<ID, S, O> constructSimpleTokenField( final EntityModel<?> entityModel, final AttributeModel attributeModel, final String distinctField, final boolean elementCollection, final Filter fieldFilter) { final BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator .getServiceForEntity(entityModel.getEntityClass()); final SortOrder[] sos; if (distinctField == null) { sos = constructSortOrder(entityModel); } else { sos = new SortOrder[] { new SortOrder(distinctField, SortDirection.ASCENDING) }; } return new SimpleTokenFieldSelect<>(service, (EntityModel<S>) entityModel, attributeModel, fieldFilter, distinctField, (Class<O>) attributeModel.getNormalizedType(), elementCollection, sos); } /** * Constructs the default sort order of a component based on an Entity Model * * @param entityModel * the entity model * @return */ private SortOrder[] constructSortOrder(final EntityModel<?> entityModel) { final SortOrder[] sos = new SortOrder[entityModel.getSortOrder().size()]; int i = 0; for (final AttributeModel am : entityModel.getSortOrder().keySet()) { sos[i++] = new SortOrder(am.getName(), entityModel.getSortOrder().get(am) ? SortDirection.ASCENDING : SortDirection.DESCENDING); } return sos; } /** * Creates a field for displaying an enumeration * * @param type * the type of enum the values to display * @param fieldType * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public <E extends Field<?>> E createEnumCombo(final Class<?> type, final Class<E> fieldType) { final AbstractSelect s = createCompatibleSelect((Class<? extends AbstractSelect>) fieldType); s.setNullSelectionAllowed(true); fillEnumField(s, (Class<? extends Enum>) type); return (E) s; } /** * Creates a field - overridden from the default field factory * * @param type * the type of the property that is bound to the field * @param fieldType * the type of the field * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public <F extends Field> F createField(final Class<?> type, final Class<F> fieldType) { if (Enum.class.isAssignableFrom(type)) { if (AbstractSelect.class.isAssignableFrom(fieldType)) { return createEnumCombo(type, fieldType); } else { final ComboBox cb = createEnumCombo(type, ComboBox.class); cb.setFilteringMode(FilteringMode.CONTAINS); return (F) cb; } } else if (AbstractEntity.class.isAssignableFrom(type)) { // inside a table, always use a combo box final EntityModel<?> entityModel = serviceLocator.getEntityModelFactory().getModel(type); return (F) constructComboBox(entityModel, null, null, search); } return super.createField(type, fieldType); } /** * Creates a field (called when creating the field inside a table) * * @param container * @param itemId * @param propertyId */ @Override public Field<?> createField(final Container container, final Object itemId, final Object propertyId, final Component uiContext) { return createField(propertyId.toString(), null); } /** * * Creates a field for a certain property ID * * @param propertyId * the property * @return */ public Field<?> createField(final String propertyId) { return createField(propertyId, null); } /** * Creates a field * * @param propertyId * the name of the property that can be edited by this field * @param fieldEntityModel * the custom entity model for the field * @return */ public Field<?> createField(final String propertyId, final EntityModel<?> fieldEntityModel) { // in case of a read-only field, return <code>null</code> so Vaadin will // render a label instead final AttributeModel attributeModel = model.getAttributeModel(propertyId); if (EditableType.READ_ONLY.equals(attributeModel.getEditableType()) && (!attributeModel.isUrl() && !AttributeType.DETAIL.equals(attributeModel.getAttributeType())) && !search) { return null; } Field<?> field = null; if (AttributeTextFieldMode.TEXTAREA.equals(attributeModel.getTextFieldMode()) && !search) { // text area field field = new TextArea(); } else if ((NumberUtils.isLong(attributeModel.getType()) || NumberUtils.isInteger(attributeModel.getType()) || BigDecimal.class.equals(attributeModel.getType())) && NumberSelectMode.SLIDER.equals(attributeModel.getNumberSelectMode())) { final Slider slider = new Slider(attributeModel.getDisplayName()); if (NumberUtils.isInteger(attributeModel.getType())) { slider.setConverter(new IntToDoubleConverter()); } else if (NumberUtils.isLong(attributeModel.getType())) { slider.setConverter(new LongToDoubleConverter()); } else { slider.setConverter(new BigDecimalToDoubleConverter()); slider.setResolution(attributeModel.getPrecision()); } if (attributeModel.getMinValue() != null) { slider.setMin(attributeModel.getMinValue()); } if (attributeModel.getMaxValue() != null) { slider.setMax(attributeModel.getMaxValue()); } field = slider; } else if (attributeModel.isWeek()) { // special case - week field in a table final TextField tf = new TextField(); tf.setConverter(Date.class.equals(attributeModel.getType()) ? new WeekCodeConverter() : new LocalDateWeekCodeConverter()); field = tf; } else if (search && AttributeSelectMode.TOKEN.equals(attributeModel.getSearchSelectMode()) && AttributeType.BASIC.equals(attributeModel.getAttributeType())) { // simple token field (for distinct string values) field = constructSimpleTokenField( fieldEntityModel != null ? fieldEntityModel : attributeModel.getEntityModel(), attributeModel, propertyId.substring(propertyId.lastIndexOf('.') + 1), false, null); } else if (search && (attributeModel.getType().equals(Boolean.class) || attributeModel.getType().equals(boolean.class))) { // in a search screen, we need to offer the true, false, and // undefined options field = constructSearchBooleanComboBox(attributeModel); } else if (AbstractEntity.class.isAssignableFrom(attributeModel.getType())) { // lookup or combo field for an entity field = constructSelectField(attributeModel, fieldEntityModel, null); } else if (AttributeType.ELEMENT_COLLECTION.equals(attributeModel.getAttributeType())) { if (!search) { // use a "collection table" for an element collection final FormOptions fo = new FormOptions().setShowRemoveButton(true); if (String.class.equals(attributeModel.getMemberType()) || Integer.class.equals(attributeModel.getMemberType()) || Long.class.equals(attributeModel.getMemberType()) || BigDecimal.class.equals(attributeModel.getMemberType())) { field = new CollectionTable<>(attributeModel, true, fo); } else { // other types not supported for now throw new OCSRuntimeException("Element collections of this type are currently not supported"); } } else { field = constructSimpleTokenField( fieldEntityModel != null ? fieldEntityModel : attributeModel.getEntityModel(), attributeModel, propertyId.substring(propertyId.lastIndexOf('.') + 1), true, null); } } else if (Collection.class.isAssignableFrom(attributeModel.getType())) { // render a multiple select component for a collection field = constructCollectionSelect(fieldEntityModel, attributeModel, null, true, search); } else if (LocalDate.class.equals(attributeModel.getType())) { final DateField df = new DateField(); df.setResolution(Resolution.DAY); df.setConverter(ConverterFactory.createLocalDateConverter()); df.setTimeZone(VaadinUtils.getTimeZone(UI.getCurrent())); field = df; } else if (LocalDateTime.class.equals(attributeModel.getType())) { final DateField df = new DateField(); df.setResolution(Resolution.SECOND); df.setConverter(ConverterFactory.createLocalDateTimeConverter()); df.setTimeZone(VaadinUtils.getTimeZone(UI.getCurrent())); field = df; } else if (ZonedDateTime.class.equals(attributeModel.getType())) { final DateField df = new DateField(); df.setResolution(Resolution.SECOND); df.setConverter(ConverterFactory.createZonedDateTimeConverter()); df.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())); field = df; } else if (AttributeDateType.TIME.equals(attributeModel.getDateType())) { // use custom time field, potentially with Java 8 date converter final TimeField tf = new TimeField(); tf.setResolution(Resolution.MINUTE); tf.setLocale(VaadinUtils.getLocale()); if (DateUtils.isJava8DateType(attributeModel.getType())) { tf.setConverter(ConverterFactory.createLocalTimeConverter()); } field = tf; } else if (attributeModel.isUrl()) { // URL field (offers clickable link in readonly mode) final TextField tf = (TextField) createField(attributeModel.getType(), Field.class); tf.addValidator(new URLValidator(messageService.getMessage("ocs.no.valid.url", VaadinUtils.getLocale()))); tf.setNullRepresentation(null); tf.setSizeFull(); // wrap text field in URL field field = new URLField(tf, attributeModel, false); field.setSizeFull(); } else if (Boolean.class.equals(attributeModel.getType()) && CheckboxMode.SWITCH.equals(attributeModel.getCheckboxMode())) { field = new Switch(); ((Switch) field).addStyleName("compact"); } else { // just a regular field field = createField(attributeModel.getType(), Field.class); } if (field instanceof DateField) { final DateField df = (DateField) field; final Locale dateLocale = VaadinUtils.getDateLocale(); df.setLocale(dateLocale); if (UI.getCurrent() != null) { df.setTimeZone(VaadinUtils.getTimeZone(UI.getCurrent())); } } field.setCaption(attributeModel.getDisplayName()); postProcessField(field, attributeModel); // add a field validator based on JSR-303 bean validation if (validate) { field.addValidator(new BeanValidator(model.getEntityClass(), propertyId)); // disable the field if it cannot be edited if (!attributeModel.isUrl()) { field.setEnabled(!EditableType.READ_ONLY.equals(attributeModel.getEditableType())); } if (attributeModel.isNumerical()) { field.addStyleName(DynamoConstants.CSS_NUMERICAL); } } return field; } /** * Add additional field settings to a field * * @param field * @param attributeModel */ private void postProcessField(final Field<?> field, final AttributeModel attributeModel) { if (field instanceof AbstractTextField) { final AbstractTextField textField = (AbstractTextField) field; textField.setDescription(attributeModel.getDescription()); textField.setNullSettingAllowed(true); textField.setNullRepresentation(""); if (!StringUtils.isEmpty(attributeModel.getPrompt())) { textField.setInputPrompt(attributeModel.getPrompt()); } // set converters setConverters(textField, attributeModel); // add email validator if (attributeModel.isEmail()) { field.addValidator( new EmailValidator(messageService.getMessage("ocs.no.valid.email", VaadinUtils.getLocale()))); } } else if (field instanceof DateField) { // set a separate format for a date field final DateField dateField = (DateField) field; if (attributeModel.getDisplayFormat() != null) { dateField.setDateFormat(attributeModel.getDisplayFormat()); } if (AttributeDateType.TIMESTAMP.equals(attributeModel.getDateType())) { dateField.setResolution(Resolution.SECOND); } } // set description for all fields if (field instanceof AbstractField) { ((AbstractField<?>) field).setDescription(attributeModel.getDescription()); } } /** * Creates a select field for a single-valued attribute * * @param attributeModel * the attribute * @param fieldEntityModel * the (overruled) entity model * @param fieldFilter * the field filter * @return */ protected Field<?> constructSelectField(final AttributeModel attributeModel, final EntityModel<?> fieldEntityModel, final Filter fieldFilter) { Field<?> field = null; final AttributeSelectMode selectMode = search ? attributeModel.getSearchSelectMode() : attributeModel.getSelectMode(); if (search && attributeModel.isMultipleSearch()) { // in case of multiple search, defer to the // "constructCollectionSelect" method field = this.constructCollectionSelect(fieldEntityModel, attributeModel, fieldFilter, true, search); } else if (AttributeSelectMode.COMBO.equals(selectMode)) { // combo box field = constructComboBox(fieldEntityModel, attributeModel, fieldFilter, search); } else if (AttributeSelectMode.LOOKUP.equals(selectMode)) { // single select lookup field field = constructLookupField(fieldEntityModel, attributeModel, fieldFilter, search, false); } else { // list select (single select) field = this.constructCollectionSelect(fieldEntityModel, attributeModel, fieldFilter, false, search); } return field; } /** * Fills an enumeration field with messages from the message bundle * * @param select * @param enumClass */ @SuppressWarnings("unchecked") private <E extends Enum<E>> void fillEnumField(final AbstractSelect select, final Class<E> enumClass) { select.removeAllItems(); for (final Object p : select.getContainerPropertyIds()) { select.removeContainerProperty(p); } select.addContainerProperty(CAPTION_PROPERTY_ID, String.class, ""); select.setItemCaptionPropertyId(CAPTION_PROPERTY_ID); // sort on the description final List<E> list = Arrays.asList(enumClass.getEnumConstants()); list.sort((a, b) -> { final String msg1 = messageService.getEnumMessage(enumClass, a, VaadinUtils.getLocale()); final String msg2 = messageService.getEnumMessage(enumClass, b, VaadinUtils.getLocale()); return msg1.compareToIgnoreCase(msg2); }); for (final E e : list) { final Item newItem = select.addItem(e); final String msg = messageService.getEnumMessage(enumClass, e, VaadinUtils.getLocale()); if (msg != null) { newItem.getItemProperty(CAPTION_PROPERTY_ID).setValue(msg); } else { newItem.getItemProperty(CAPTION_PROPERTY_ID) .setValue(DefaultFieldFactory.createCaptionByPropertyId(e.name())); } } } public EntityModel<T> getModel() { return model; } /** * Resolves an entity model by falling back first to the nested attribute model * and then to the default model for the normalized type of the property * * @param entityModel * the entity model * @param attributeModel * the attribute model * @return */ private EntityModel<?> resolveEntityModel(EntityModel<?> entityModel, final AttributeModel attributeModel) { if (entityModel == null) { if (attributeModel.getNestedEntityModel() != null) { entityModel = attributeModel.getNestedEntityModel(); } else { final Class<?> type = attributeModel.getNormalizedType(); entityModel = serviceLocator.getEntityModelFactory().getModel(type.asSubclass(AbstractEntity.class)); } } return entityModel; } /** * Set the appropriate converter on a text field * * @param textField * the field * @param attributeModel * the attribute model of the attribute to bind to the field */ protected void setConverters(final AbstractTextField textField, final AttributeModel am) { if (am.getType().equals(BigDecimal.class)) { textField.setConverter(ConverterFactory.createBigDecimalConverter(am.isCurrency(), am.isPercentage(), SystemPropertyUtils.useThousandsGroupingInEditMode(), am.getPrecision(), VaadinUtils.getCurrencySymbol())); } else if (NumberUtils.isInteger(am.getType())) { textField.setConverter(ConverterFactory .createIntegerConverter(SystemPropertyUtils.useThousandsGroupingInEditMode(), am.isPercentage())); } else if (NumberUtils.isLong(am.getType())) { textField.setConverter(ConverterFactory .createLongConverter(SystemPropertyUtils.useThousandsGroupingInEditMode(), am.isPercentage())); } } }
dynamo-frontend/src/main/java/com/ocs/dynamo/domain/model/impl/ModelBasedFieldFactory.java
/* 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. */ package com.ocs.dynamo.domain.model.impl; import java.io.Serializable; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.commons.lang.StringUtils; import org.vaadin.teemu.switchui.Switch; import com.google.common.collect.Lists; import com.ocs.dynamo.constants.DynamoConstants; import com.ocs.dynamo.domain.AbstractEntity; import com.ocs.dynamo.domain.model.AttributeDateType; import com.ocs.dynamo.domain.model.AttributeModel; import com.ocs.dynamo.domain.model.AttributeSelectMode; import com.ocs.dynamo.domain.model.AttributeTextFieldMode; import com.ocs.dynamo.domain.model.AttributeType; import com.ocs.dynamo.domain.model.CheckboxMode; import com.ocs.dynamo.domain.model.EditableType; import com.ocs.dynamo.domain.model.EntityModel; import com.ocs.dynamo.domain.model.FieldFactory; import com.ocs.dynamo.domain.model.NumberSelectMode; import com.ocs.dynamo.exception.OCSRuntimeException; import com.ocs.dynamo.service.BaseService; import com.ocs.dynamo.service.MessageService; import com.ocs.dynamo.service.ServiceLocator; import com.ocs.dynamo.service.ServiceLocatorFactory; import com.ocs.dynamo.ui.component.EntityComboBox.SelectMode; import com.ocs.dynamo.ui.component.EntityLookupField; import com.ocs.dynamo.ui.component.FancyListSelect; import com.ocs.dynamo.ui.component.QuickAddEntityComboBox; import com.ocs.dynamo.ui.component.QuickAddListSelect; import com.ocs.dynamo.ui.component.SimpleTokenFieldSelect; import com.ocs.dynamo.ui.component.TimeField; import com.ocs.dynamo.ui.component.TokenFieldSelect; import com.ocs.dynamo.ui.component.URLField; import com.ocs.dynamo.ui.composite.form.CollectionTable; import com.ocs.dynamo.ui.composite.layout.FormOptions; import com.ocs.dynamo.ui.converter.BigDecimalToDoubleConverter; import com.ocs.dynamo.ui.converter.ConverterFactory; import com.ocs.dynamo.ui.converter.IntToDoubleConverter; import com.ocs.dynamo.ui.converter.LocalDateWeekCodeConverter; import com.ocs.dynamo.ui.converter.LongToDoubleConverter; import com.ocs.dynamo.ui.converter.WeekCodeConverter; import com.ocs.dynamo.ui.utils.VaadinUtils; import com.ocs.dynamo.ui.validator.URLValidator; import com.ocs.dynamo.util.SystemPropertyUtils; import com.ocs.dynamo.utils.DateUtils; import com.ocs.dynamo.utils.NumberUtils; import com.vaadin.data.Container; import com.vaadin.data.Container.Filter; import com.vaadin.data.Item; import com.vaadin.data.fieldgroup.DefaultFieldGroupFieldFactory; import com.vaadin.data.sort.SortOrder; import com.vaadin.data.validator.BeanValidator; import com.vaadin.data.validator.EmailValidator; import com.vaadin.shared.data.sort.SortDirection; import com.vaadin.shared.ui.combobox.FilteringMode; import com.vaadin.shared.ui.datefield.Resolution; import com.vaadin.ui.AbstractComponent; import com.vaadin.ui.AbstractField; import com.vaadin.ui.AbstractSelect; import com.vaadin.ui.AbstractTextField; import com.vaadin.ui.ComboBox; import com.vaadin.ui.Component; import com.vaadin.ui.DateField; import com.vaadin.ui.DefaultFieldFactory; import com.vaadin.ui.Field; import com.vaadin.ui.Slider; import com.vaadin.ui.TableFieldFactory; import com.vaadin.ui.TextArea; import com.vaadin.ui.TextField; import com.vaadin.ui.UI; /** * Extension of the standard Vaadin field factory for creating custom fields * * @author bas.rutten * @param <T> * the type of the entity for which to create a field */ public class ModelBasedFieldFactory<T> extends DefaultFieldGroupFieldFactory implements TableFieldFactory { private static ConcurrentMap<String, ModelBasedFieldFactory<?>> nonValidatingInstances = new ConcurrentHashMap<>(); private static ConcurrentMap<String, ModelBasedFieldFactory<?>> searchInstances = new ConcurrentHashMap<>(); private static final long serialVersionUID = -5684112523268959448L; private static ConcurrentMap<String, ModelBasedFieldFactory<?>> validatingInstances = new ConcurrentHashMap<>(); private MessageService messageService; private EntityModel<T> model; private ServiceLocator serviceLocator = ServiceLocatorFactory.getServiceLocator(); private Collection<FieldFactory> fieldFactories; // indicates whether the system is in search mode. In search mode, // components for // some attributes are constructed differently (e.g. we render two search // fields to be able to // search for a range of integers) private boolean search; // indicates whether extra validators must be added. This is the case when // using the field factory in an // editable table private boolean validate; /** * Constructor * * @param model * the entity model * @param messageService * the message service * @param validate * whether to add extra validators (this is the case when the field * is displayed inside a table) * @param search * whether the fields are displayed inside a search form (this has an * effect on the construction of some fields) */ public ModelBasedFieldFactory(EntityModel<T> model, MessageService messageService, boolean validate, boolean search) { this.model = model; this.messageService = messageService; this.validate = validate; this.search = search; this.fieldFactories = serviceLocator.getServices(FieldFactory.class); } /** * Returns an appropriate instance from the pool, or creates a new one * * @param model * the entity model * @param messageService * @return */ @SuppressWarnings("unchecked") public static <T> ModelBasedFieldFactory<T> getInstance(EntityModel<T> model, MessageService messageService) { if (!nonValidatingInstances.containsKey(model.getReference())) { nonValidatingInstances.put(model.getReference(), new ModelBasedFieldFactory<>(model, messageService, false, false)); } return (ModelBasedFieldFactory<T>) nonValidatingInstances.get(model.getReference()); } /** * Returns an appropriate instance from the pool, or creates a new one * * @param model * @param messageService * @return */ @SuppressWarnings("unchecked") public static <T> ModelBasedFieldFactory<T> getSearchInstance(EntityModel<T> model, MessageService messageService) { if (!searchInstances.containsKey(model.getReference())) { searchInstances.put(model.getReference(), new ModelBasedFieldFactory<>(model, messageService, false, true)); } return (ModelBasedFieldFactory<T>) searchInstances.get(model.getReference()); } /** * Returns an appropriate instance from the pool, or creates a new one * * @param model * @param messageService * @return */ @SuppressWarnings("unchecked") public static <T> ModelBasedFieldFactory<T> getValidatingInstance(EntityModel<T> model, MessageService messageService) { if (!validatingInstances.containsKey(model.getReference())) { validatingInstances.put(model.getReference(), new ModelBasedFieldFactory<>(model, messageService, true, false)); } return (ModelBasedFieldFactory<T>) validatingInstances.get(model.getReference()); } /** * Constructs a combo box- the sort order will be taken from the entity model * * @param entityModel * the entity model to base the combo box on * @param attributeModel * the attribute model * @param filter * optional field filter - only items that match the filter will be * included * @return */ @SuppressWarnings("unchecked") public <ID extends Serializable, S extends AbstractEntity<ID>> AbstractField<?> constructComboBox( EntityModel<?> entityModel, AttributeModel attributeModel, Filter filter, boolean search) { entityModel = resolveEntityModel(entityModel, attributeModel); BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator .getServiceForEntity(entityModel.getEntityClass()); SortOrder[] sos = constructSortOrder(entityModel); return new QuickAddEntityComboBox<>((EntityModel<S>) entityModel, attributeModel, service, SelectMode.FILTERED, filter, search, null, sos); } /** * Constructs a field based on an attribute model and possibly a field filter * * @param attributeModel * the attribute model * @param fieldFilters * the list of field filters * @param fieldEntityModel * the custom entity model for the field * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Field<?> constructField(AttributeModel attributeModel, Map<String, Filter> fieldFilters, EntityModel<?> fieldEntityModel) { Field<?> field = null; // Are there any delegated component factories that can create this field? if (fieldFactories != null && !fieldFactories.isEmpty()) { for (FieldFactory ff : fieldFactories) { FieldFactoryContextImpl<?> c = new FieldFactoryContextImpl<>().setAttributeModel(attributeModel) .setFieldFilters(fieldFilters).setFieldEntityModel((EntityModel) fieldEntityModel); field = ff.constructField(c); if (field != null) { break; } } } if (field == null) { Filter fieldFilter = fieldFilters == null ? null : fieldFilters.get(attributeModel.getPath()); if (fieldFilter != null) { if (AttributeType.MASTER.equals(attributeModel.getAttributeType())) { // create a combo box or lookup field field = constructSelectField(attributeModel, fieldEntityModel, fieldFilter); } else if (search && AttributeSelectMode.TOKEN.equals(attributeModel.getSearchSelectMode()) && AttributeType.BASIC.equals(attributeModel.getAttributeType())) { // simple token field (for distinct string values) field = constructSimpleTokenField( fieldEntityModel != null ? fieldEntityModel : attributeModel.getEntityModel(), attributeModel, attributeModel.getPath().substring(attributeModel.getPath().lastIndexOf('.') + 1), false, fieldFilter); } else { // detail relationship, render a multiple select field = this.constructCollectionSelect(fieldEntityModel, attributeModel, fieldFilter, true, search); } } else { field = this.createField(attributeModel.getPath(), fieldEntityModel); } } // Is it a required field? field.setRequired(search ? attributeModel.isRequiredForSearching() : attributeModel.isRequired()); // if (field instanceof AbstractComponent) { ((AbstractComponent) field).setImmediate(true); field.setCaption(attributeModel.getDisplayName()); } return field; } /** * Constructs a select component for selecting multiple values * * @param fieldEntityModel * the entity model of the entity to display in the field * @param attributeModel * the attribute model of the property that is displayed in the * ListSelect * @param fieldFilter * optional field filter * @param multipleSelect * is multiple select supported? * @param search * indicates whether the component is being used in a search screen * @return */ @SuppressWarnings("unchecked") public <ID extends Serializable, S extends AbstractEntity<ID>> Field<?> constructCollectionSelect( EntityModel<?> fieldEntityModel, AttributeModel attributeModel, Filter fieldFilter, boolean multipleSelect, boolean search) { EntityModel<?> em = resolveEntityModel(fieldEntityModel, attributeModel); BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator.getServiceForEntity(em.getEntityClass()); SortOrder[] sos = constructSortOrder(em); // mode depends on whether we are searching AttributeSelectMode mode = search ? attributeModel.getSearchSelectMode() : attributeModel.getSelectMode(); if (AttributeSelectMode.LOOKUP.equals(mode)) { // lookup field - take care to NOT use the nested model here! return constructLookupField(fieldEntityModel, attributeModel, fieldFilter, search, true); } else if (AttributeSelectMode.FANCY_LIST.equals(mode)) { // fancy list select FancyListSelect<ID, S> listSelect = new FancyListSelect<>(service, (EntityModel<S>) em, attributeModel, fieldFilter, search, sos); listSelect.setRows(SystemPropertyUtils.getDefaultListSelectRows()); return listSelect; } else if (AttributeSelectMode.LIST.equals(mode)) { // simple list select if everything else fails or is not applicable return new QuickAddListSelect<>((EntityModel<S>) em, attributeModel, service, fieldFilter, multipleSelect, SystemPropertyUtils.getDefaultListSelectRows(), sos); } else { // by default, use a token field return new TokenFieldSelect<>((EntityModel<S>) em, attributeModel, service, fieldFilter, search, sos); } } /** * Constructs a lookup field (field that brings up a popup search dialog) * * @param overruled * the entity model of the entity to display in the field * @param attributeModel * the attribute model of the property that is bound to the field * @param fieldFilter * optional field filter * @return */ @SuppressWarnings("unchecked") public <ID extends Serializable, S extends AbstractEntity<ID>> EntityLookupField<ID, S> constructLookupField( EntityModel<?> overruled, AttributeModel attributeModel, Filter fieldFilter, boolean search, boolean multiSelect) { // for a lookup field, don't use the nested model but the base model - // this is // because the search in the popup screen is conducted on a "clean", // unnested entity list so // using a path from the parent entity makes no sense here EntityModel<?> entityModel = overruled != null ? overruled : serviceLocator.getEntityModelFactory().getModel(attributeModel.getNormalizedType()); BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator.getServiceForEntity( attributeModel.getMemberType() != null ? attributeModel.getMemberType() : entityModel.getEntityClass()); SortOrder[] sos = constructSortOrder(entityModel); return new EntityLookupField<>(service, (EntityModel<S>) entityModel, attributeModel, fieldFilter, search, multiSelect, sos.length == 0 ? null : Lists.newArrayList(sos)); } /** * Create a combo box for searching on a boolean. This combo box contains three * values (yes, no, and null) * * @return */ public ComboBox constructSearchBooleanComboBox(AttributeModel am) { ComboBox cb = new ComboBox(); cb.addItem(Boolean.TRUE); cb.setItemCaption(Boolean.TRUE, am.getTrueRepresentation()); cb.addItem(Boolean.FALSE); cb.setItemCaption(Boolean.FALSE, am.getFalseRepresentation()); return cb; } /** * Construct a combo box that contains a list of String values * * @param values * the list of values * @param am * the attribute model * @return */ public static ComboBox constructStringListCombo(List<String> values, AttributeModel am) { ComboBox cb = new ComboBox(); cb.setCaption(am.getDisplayName()); cb.addItems(values); cb.setFilteringMode(FilteringMode.CONTAINS); return cb; } /** * Constructs a token field for basic attributes (Strings) * * @param entityModel * the entity model to base the field on * @param attributeModel * the attribute model * @param distinctField * the field for which to return the distinct values * @param fieldFilter * field filter to apply in order to limit the search results * @return */ @SuppressWarnings("unchecked") private <ID extends Serializable, S extends AbstractEntity<ID>, O extends Comparable<O>> SimpleTokenFieldSelect<ID, S, O> constructSimpleTokenField( EntityModel<?> entityModel, AttributeModel attributeModel, String distinctField, boolean elementCollection, Filter fieldFilter) { BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator .getServiceForEntity(entityModel.getEntityClass()); SortOrder[] sos; if (distinctField == null) { sos = constructSortOrder(entityModel); } else { sos = new SortOrder[] { new SortOrder(distinctField, SortDirection.ASCENDING) }; } return new SimpleTokenFieldSelect<>(service, (EntityModel<S>) entityModel, attributeModel, fieldFilter, distinctField, (Class<O>) attributeModel.getNormalizedType(), elementCollection, sos); } /** * Constructs the default sort order of a component based on an Entity Model * * @param entityModel * the entity model * @return */ private SortOrder[] constructSortOrder(EntityModel<?> entityModel) { SortOrder[] sos = new SortOrder[entityModel.getSortOrder().size()]; int i = 0; for (AttributeModel am : entityModel.getSortOrder().keySet()) { sos[i++] = new SortOrder(am.getName(), entityModel.getSortOrder().get(am) ? SortDirection.ASCENDING : SortDirection.DESCENDING); } return sos; } /** * Creates a field for displaying an enumeration * * @param type * the type of enum the values to display * @param fieldType * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public <E extends Field<?>> E createEnumCombo(Class<?> type, Class<E> fieldType) { AbstractSelect s = createCompatibleSelect((Class<? extends AbstractSelect>) fieldType); s.setNullSelectionAllowed(true); fillEnumField(s, (Class<? extends Enum>) type); return (E) s; } /** * Creates a field - overridden from the default field factory * * @param type * the type of the property that is bound to the field * @param fieldType * the type of the field * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public <F extends Field> F createField(Class<?> type, Class<F> fieldType) { if (Enum.class.isAssignableFrom(type)) { if (AbstractSelect.class.isAssignableFrom(fieldType)) { return createEnumCombo(type, fieldType); } else { ComboBox cb = createEnumCombo(type, ComboBox.class); cb.setFilteringMode(FilteringMode.CONTAINS); return (F) cb; } } else if (AbstractEntity.class.isAssignableFrom(type)) { // inside a table, always use a combo box EntityModel<?> entityModel = serviceLocator.getEntityModelFactory().getModel(type); return (F) constructComboBox(entityModel, null, null, search); } return super.createField(type, fieldType); } /** * Creates a field (called when creating the field inside a table) * * @param container * @param itemId * @param propertyId */ @Override public Field<?> createField(Container container, Object itemId, Object propertyId, Component uiContext) { return createField(propertyId.toString(), null); } /** * * Creates a field for a certain property ID * * @param propertyId * the property * @return */ public Field<?> createField(String propertyId) { return createField(propertyId, null); } /** * Creates a field * * @param propertyId * the name of the property that can be edited by this field * @param fieldEntityModel * the custom entity model for the field * @return */ public Field<?> createField(String propertyId, EntityModel<?> fieldEntityModel) { // in case of a read-only field, return <code>null</code> so Vaadin will // render a label instead AttributeModel attributeModel = model.getAttributeModel(propertyId); if (EditableType.READ_ONLY.equals(attributeModel.getEditableType()) && (!attributeModel.isUrl() && !AttributeType.DETAIL.equals(attributeModel.getAttributeType())) && !search) { return null; } Field<?> field = null; if (AttributeTextFieldMode.TEXTAREA.equals(attributeModel.getTextFieldMode()) && !search) { // text area field field = new TextArea(); } else if ((NumberUtils.isLong(attributeModel.getType()) || NumberUtils.isInteger(attributeModel.getType()) || BigDecimal.class.equals(attributeModel.getType())) && NumberSelectMode.SLIDER.equals(attributeModel.getNumberSelectMode())) { Slider slider = new Slider(attributeModel.getDisplayName()); if (NumberUtils.isInteger(attributeModel.getType())) { slider.setConverter(new IntToDoubleConverter()); } else if (NumberUtils.isLong(attributeModel.getType())) { slider.setConverter(new LongToDoubleConverter()); } else { slider.setConverter(new BigDecimalToDoubleConverter()); slider.setResolution(attributeModel.getPrecision()); } if (attributeModel.getMinValue() != null) { slider.setMin(attributeModel.getMinValue()); } if (attributeModel.getMaxValue() != null) { slider.setMax(attributeModel.getMaxValue()); } field = slider; } else if (attributeModel.isWeek()) { // special case - week field in a table TextField tf = new TextField(); tf.setConverter(Date.class.equals(attributeModel.getType()) ? new WeekCodeConverter() : new LocalDateWeekCodeConverter()); field = tf; } else if (search && AttributeSelectMode.TOKEN.equals(attributeModel.getSearchSelectMode()) && AttributeType.BASIC.equals(attributeModel.getAttributeType())) { // simple token field (for distinct string values) field = constructSimpleTokenField( fieldEntityModel != null ? fieldEntityModel : attributeModel.getEntityModel(), attributeModel, propertyId.substring(propertyId.lastIndexOf('.') + 1), false, null); } else if (search && (attributeModel.getType().equals(Boolean.class) || attributeModel.getType().equals(boolean.class))) { // in a search screen, we need to offer the true, false, and // undefined options field = constructSearchBooleanComboBox(attributeModel); } else if (AbstractEntity.class.isAssignableFrom(attributeModel.getType())) { // lookup or combo field for an entity field = constructSelectField(attributeModel, fieldEntityModel, null); } else if (AttributeType.ELEMENT_COLLECTION.equals(attributeModel.getAttributeType())) { if (!search) { // use a "collection table" for an element collection FormOptions fo = new FormOptions().setShowRemoveButton(true); if (String.class.equals(attributeModel.getMemberType()) || Integer.class.equals(attributeModel.getMemberType()) || Long.class.equals(attributeModel.getMemberType()) || BigDecimal.class.equals(attributeModel.getMemberType())) { field = new CollectionTable<>(attributeModel, true, fo); } else { // other types not supported for now throw new OCSRuntimeException("Element collections of this type are currently not supported"); } } else { field = constructSimpleTokenField( fieldEntityModel != null ? fieldEntityModel : attributeModel.getEntityModel(), attributeModel, propertyId.substring(propertyId.lastIndexOf('.') + 1), true, null); } } else if (Collection.class.isAssignableFrom(attributeModel.getType())) { // render a multiple select component for a collection field = constructCollectionSelect(fieldEntityModel, attributeModel, null, true, search); } else if (LocalDate.class.equals(attributeModel.getType())) { DateField df = new DateField(); df.setResolution(Resolution.DAY); df.setConverter(ConverterFactory.createLocalDateConverter()); df.setTimeZone(VaadinUtils.getTimeZone(UI.getCurrent())); field = df; } else if (LocalDateTime.class.equals(attributeModel.getType())) { DateField df = new DateField(); df.setResolution(Resolution.SECOND); df.setConverter(ConverterFactory.createLocalDateTimeConverter()); df.setTimeZone(VaadinUtils.getTimeZone(UI.getCurrent())); field = df; } else if (ZonedDateTime.class.equals(attributeModel.getType())) { DateField df = new DateField(); df.setResolution(Resolution.SECOND); df.setConverter(ConverterFactory.createZonedDateTimeConverter()); df.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())); field = df; } else if (AttributeDateType.TIME.equals(attributeModel.getDateType())) { // use custom time field, potentially with Java 8 date converter TimeField tf = new TimeField(); tf.setResolution(Resolution.MINUTE); tf.setLocale(VaadinUtils.getLocale()); if (DateUtils.isJava8DateType(attributeModel.getType())) { tf.setConverter(ConverterFactory.createLocalTimeConverter()); } field = tf; } else if (attributeModel.isUrl()) { // URL field (offers clickable link in readonly mode) TextField tf = (TextField) createField(attributeModel.getType(), Field.class); tf.addValidator(new URLValidator(messageService.getMessage("ocs.no.valid.url", VaadinUtils.getLocale()))); tf.setNullRepresentation(null); tf.setSizeFull(); // wrap text field in URL field field = new URLField(tf, attributeModel, false); field.setSizeFull(); } else if (Boolean.class.equals(attributeModel.getType()) && CheckboxMode.SWITCH.equals(attributeModel.getCheckboxMode())) { field = new Switch(); ((Switch) field).addStyleName("compact"); } else { // just a regular field field = createField(attributeModel.getType(), Field.class); } if (field instanceof DateField) { DateField df = (DateField) field; Locale dateLocale = VaadinUtils.getDateLocale(); df.setLocale(dateLocale); if (UI.getCurrent() != null) { df.setTimeZone(VaadinUtils.getTimeZone(UI.getCurrent())); } } field.setCaption(attributeModel.getDisplayName()); postProcessField(field, attributeModel); // add a field validator based on JSR-303 bean validation if (validate) { field.addValidator(new BeanValidator(model.getEntityClass(), propertyId)); // disable the field if it cannot be edited if (!attributeModel.isUrl()) { field.setEnabled(!EditableType.READ_ONLY.equals(attributeModel.getEditableType())); } if (attributeModel.isNumerical()) { field.addStyleName(DynamoConstants.CSS_NUMERICAL); } } return field; } /** * Add additional field settings to a field * * @param field * @param attributeModel */ private void postProcessField(Field<?> field, AttributeModel attributeModel) { if (field instanceof AbstractTextField) { AbstractTextField textField = (AbstractTextField) field; textField.setDescription(attributeModel.getDescription()); textField.setNullSettingAllowed(true); textField.setNullRepresentation(""); if (!StringUtils.isEmpty(attributeModel.getPrompt())) { textField.setInputPrompt(attributeModel.getPrompt()); } // set converters setConverters(textField, attributeModel); // add email validator if (attributeModel.isEmail()) { field.addValidator( new EmailValidator(messageService.getMessage("ocs.no.valid.email", VaadinUtils.getLocale()))); } } else if (field instanceof DateField) { // set a separate format for a date field DateField dateField = (DateField) field; if (attributeModel.getDisplayFormat() != null) { dateField.setDateFormat(attributeModel.getDisplayFormat()); } if (AttributeDateType.TIMESTAMP.equals(attributeModel.getDateType())) { dateField.setResolution(Resolution.SECOND); } } } /** * Creates a select field for a single-valued attribute * * @param attributeModel * the attribute * @param fieldEntityModel * the (overruled) entity model * @param fieldFilter * the field filter * @return */ protected Field<?> constructSelectField(AttributeModel attributeModel, EntityModel<?> fieldEntityModel, Filter fieldFilter) { Field<?> field = null; AttributeSelectMode selectMode = search ? attributeModel.getSearchSelectMode() : attributeModel.getSelectMode(); if (search && attributeModel.isMultipleSearch()) { // in case of multiple search, defer to the // "constructCollectionSelect" method field = this.constructCollectionSelect(fieldEntityModel, attributeModel, fieldFilter, true, search); } else if (AttributeSelectMode.COMBO.equals(selectMode)) { // combo box field = constructComboBox(fieldEntityModel, attributeModel, fieldFilter, search); } else if (AttributeSelectMode.LOOKUP.equals(selectMode)) { // single select lookup field field = constructLookupField(fieldEntityModel, attributeModel, fieldFilter, search, false); } else { // list select (single select) field = this.constructCollectionSelect(fieldEntityModel, attributeModel, fieldFilter, false, search); } return field; } /** * Fills an enumeration field with messages from the message bundle * * @param select * @param enumClass */ @SuppressWarnings("unchecked") private <E extends Enum<E>> void fillEnumField(AbstractSelect select, Class<E> enumClass) { select.removeAllItems(); for (Object p : select.getContainerPropertyIds()) { select.removeContainerProperty(p); } select.addContainerProperty(CAPTION_PROPERTY_ID, String.class, ""); select.setItemCaptionPropertyId(CAPTION_PROPERTY_ID); // sort on the description List<E> list = Arrays.asList(enumClass.getEnumConstants()); list.sort((a, b) -> { String msg1 = messageService.getEnumMessage(enumClass, a, VaadinUtils.getLocale()); String msg2 = messageService.getEnumMessage(enumClass, b, VaadinUtils.getLocale()); return msg1.compareToIgnoreCase(msg2); }); for (E e : list) { Item newItem = select.addItem(e); String msg = messageService.getEnumMessage(enumClass, e, VaadinUtils.getLocale()); if (msg != null) { newItem.getItemProperty(CAPTION_PROPERTY_ID).setValue(msg); } else { newItem.getItemProperty(CAPTION_PROPERTY_ID) .setValue(DefaultFieldFactory.createCaptionByPropertyId(e.name())); } } } public EntityModel<T> getModel() { return model; } /** * Resolves an entity model by falling back first to the nested attribute model * and then to the default model for the normalized type of the property * * @param entityModel * the entity model * @param attributeModel * the attribute model * @return */ private EntityModel<?> resolveEntityModel(EntityModel<?> entityModel, AttributeModel attributeModel) { if (entityModel == null) { if (attributeModel.getNestedEntityModel() != null) { entityModel = attributeModel.getNestedEntityModel(); } else { Class<?> type = attributeModel.getNormalizedType(); entityModel = serviceLocator.getEntityModelFactory().getModel(type.asSubclass(AbstractEntity.class)); } } return entityModel; } /** * Set the appropriate converter on a text field * * @param textField * the field * @param attributeModel * the attribute model of the attribute to bind to the field */ protected void setConverters(AbstractTextField textField, AttributeModel am) { if (am.getType().equals(BigDecimal.class)) { textField.setConverter(ConverterFactory.createBigDecimalConverter(am.isCurrency(), am.isPercentage(), SystemPropertyUtils.useThousandsGroupingInEditMode(), am.getPrecision(), VaadinUtils.getCurrencySymbol())); } else if (NumberUtils.isInteger(am.getType())) { textField.setConverter(ConverterFactory .createIntegerConverter(SystemPropertyUtils.useThousandsGroupingInEditMode(), am.isPercentage())); } else if (NumberUtils.isLong(am.getType())) { textField.setConverter(ConverterFactory .createLongConverter(SystemPropertyUtils.useThousandsGroupingInEditMode(), am.isPercentage())); } } }
Tooltips
dynamo-frontend/src/main/java/com/ocs/dynamo/domain/model/impl/ModelBasedFieldFactory.java
Tooltips
<ide><path>ynamo-frontend/src/main/java/com/ocs/dynamo/domain/model/impl/ModelBasedFieldFactory.java <ide> limitations under the License. <ide> */ <ide> package com.ocs.dynamo.domain.model.impl; <del> <del>import java.io.Serializable; <del>import java.math.BigDecimal; <del>import java.time.LocalDate; <del>import java.time.LocalDateTime; <del>import java.time.ZoneId; <del>import java.time.ZonedDateTime; <del>import java.util.Arrays; <del>import java.util.Collection; <del>import java.util.Date; <del>import java.util.List; <del>import java.util.Locale; <del>import java.util.Map; <del>import java.util.TimeZone; <del>import java.util.concurrent.ConcurrentHashMap; <del>import java.util.concurrent.ConcurrentMap; <del> <del>import org.apache.commons.lang.StringUtils; <del>import org.vaadin.teemu.switchui.Switch; <ide> <ide> import com.google.common.collect.Lists; <ide> import com.ocs.dynamo.constants.DynamoConstants; <ide> import com.vaadin.ui.TextArea; <ide> import com.vaadin.ui.TextField; <ide> import com.vaadin.ui.UI; <add>import org.apache.commons.lang.StringUtils; <add>import org.vaadin.teemu.switchui.Switch; <add> <add>import java.io.Serializable; <add>import java.math.BigDecimal; <add>import java.time.LocalDate; <add>import java.time.LocalDateTime; <add>import java.time.ZoneId; <add>import java.time.ZonedDateTime; <add>import java.util.Arrays; <add>import java.util.Collection; <add>import java.util.Date; <add>import java.util.List; <add>import java.util.Locale; <add>import java.util.Map; <add>import java.util.TimeZone; <add>import java.util.concurrent.ConcurrentHashMap; <add>import java.util.concurrent.ConcurrentMap; <ide> <ide> /** <ide> * Extension of the standard Vaadin field factory for creating custom fields <ide> */ <ide> public class ModelBasedFieldFactory<T> extends DefaultFieldGroupFieldFactory implements TableFieldFactory { <ide> <del> private static ConcurrentMap<String, ModelBasedFieldFactory<?>> nonValidatingInstances = new ConcurrentHashMap<>(); <del> <del> private static ConcurrentMap<String, ModelBasedFieldFactory<?>> searchInstances = new ConcurrentHashMap<>(); <del> <ide> private static final long serialVersionUID = -5684112523268959448L; <del> <del> private static ConcurrentMap<String, ModelBasedFieldFactory<?>> validatingInstances = new ConcurrentHashMap<>(); <del> <del> private MessageService messageService; <del> <del> private EntityModel<T> model; <del> <del> private ServiceLocator serviceLocator = ServiceLocatorFactory.getServiceLocator(); <del> <del> private Collection<FieldFactory> fieldFactories; <add> private static final ConcurrentMap<String, ModelBasedFieldFactory<?>> nonValidatingInstances = new ConcurrentHashMap<>(); <add> private static final ConcurrentMap<String, ModelBasedFieldFactory<?>> searchInstances = new ConcurrentHashMap<>(); <add> private static final ConcurrentMap<String, ModelBasedFieldFactory<?>> validatingInstances = new ConcurrentHashMap<>(); <add> <add> private final MessageService messageService; <add> <add> private final EntityModel<T> model; <add> <add> private final ServiceLocator serviceLocator = ServiceLocatorFactory.getServiceLocator(); <add> <add> private final Collection<FieldFactory> fieldFactories; <ide> <ide> // indicates whether the system is in search mode. In search mode, <ide> // components for <ide> // some attributes are constructed differently (e.g. we render two search <ide> // fields to be able to <ide> // search for a range of integers) <del> private boolean search; <add> private final boolean search; <ide> <ide> // indicates whether extra validators must be added. This is the case when <ide> // using the field factory in an <ide> // editable table <del> private boolean validate; <add> private final boolean validate; <ide> <ide> /** <ide> * Constructor <ide> * whether the fields are displayed inside a search form (this has an <ide> * effect on the construction of some fields) <ide> */ <del> public ModelBasedFieldFactory(EntityModel<T> model, MessageService messageService, boolean validate, <del> boolean search) { <add> public ModelBasedFieldFactory(final EntityModel<T> model, final MessageService messageService, <add> final boolean validate, <add> final boolean search) { <ide> this.model = model; <ide> this.messageService = messageService; <ide> this.validate = validate; <ide> * @return <ide> */ <ide> @SuppressWarnings("unchecked") <del> public static <T> ModelBasedFieldFactory<T> getInstance(EntityModel<T> model, MessageService messageService) { <add> public static <T> ModelBasedFieldFactory<T> getInstance(final EntityModel<T> model, <add> final MessageService messageService) { <ide> if (!nonValidatingInstances.containsKey(model.getReference())) { <ide> nonValidatingInstances.put(model.getReference(), <ide> new ModelBasedFieldFactory<>(model, messageService, false, false)); <ide> * @return <ide> */ <ide> @SuppressWarnings("unchecked") <del> public static <T> ModelBasedFieldFactory<T> getSearchInstance(EntityModel<T> model, MessageService messageService) { <add> public static <T> ModelBasedFieldFactory<T> getSearchInstance(final EntityModel<T> model, <add> final MessageService messageService) { <ide> if (!searchInstances.containsKey(model.getReference())) { <ide> searchInstances.put(model.getReference(), new ModelBasedFieldFactory<>(model, messageService, false, true)); <ide> } <ide> * @return <ide> */ <ide> @SuppressWarnings("unchecked") <del> public static <T> ModelBasedFieldFactory<T> getValidatingInstance(EntityModel<T> model, <del> MessageService messageService) { <add> public static <T> ModelBasedFieldFactory<T> getValidatingInstance(final EntityModel<T> model, <add> final MessageService messageService) { <ide> if (!validatingInstances.containsKey(model.getReference())) { <ide> validatingInstances.put(model.getReference(), <ide> new ModelBasedFieldFactory<>(model, messageService, true, false)); <ide> } <ide> <ide> /** <add> * Construct a combo box that contains a list of String values <add> * <add> * @param values the list of values <add> * @param am the attribute model <add> * @return <add> */ <add> public static ComboBox constructStringListCombo(final List<String> values, final AttributeModel am) { <add> final ComboBox cb = new ComboBox(); <add> cb.setCaption(am.getDisplayName()); <add> cb.addItems(values); <add> cb.setFilteringMode(FilteringMode.CONTAINS); <add> return cb; <add> } <add> <add> /** <ide> * Constructs a combo box- the sort order will be taken from the entity model <del> * <add> * <ide> * @param entityModel <ide> * the entity model to base the combo box on <ide> * @param attributeModel <ide> */ <ide> @SuppressWarnings("unchecked") <ide> public <ID extends Serializable, S extends AbstractEntity<ID>> AbstractField<?> constructComboBox( <del> EntityModel<?> entityModel, AttributeModel attributeModel, Filter filter, boolean search) { <add> EntityModel<?> entityModel, final AttributeModel attributeModel, final Filter filter, final boolean search) { <ide> entityModel = resolveEntityModel(entityModel, attributeModel); <del> BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator <add> final BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator <ide> .getServiceForEntity(entityModel.getEntityClass()); <del> SortOrder[] sos = constructSortOrder(entityModel); <add> final SortOrder[] sos = constructSortOrder(entityModel); <ide> return new QuickAddEntityComboBox<>((EntityModel<S>) entityModel, attributeModel, service, SelectMode.FILTERED, <ide> filter, search, null, sos); <ide> } <ide> <ide> /** <ide> * Constructs a field based on an attribute model and possibly a field filter <del> * <add> * <ide> * @param attributeModel <ide> * the attribute model <ide> * @param fieldFilters <ide> * @return <ide> */ <ide> @SuppressWarnings({ "unchecked", "rawtypes" }) <del> public Field<?> constructField(AttributeModel attributeModel, Map<String, Filter> fieldFilters, <del> EntityModel<?> fieldEntityModel) { <add> public Field<?> constructField(final AttributeModel attributeModel, final Map<String, Filter> fieldFilters, <add> final EntityModel<?> fieldEntityModel) { <ide> <ide> Field<?> field = null; <ide> <ide> // Are there any delegated component factories that can create this field? <ide> if (fieldFactories != null && !fieldFactories.isEmpty()) { <del> for (FieldFactory ff : fieldFactories) { <del> FieldFactoryContextImpl<?> c = new FieldFactoryContextImpl<>().setAttributeModel(attributeModel) <add> for (final FieldFactory ff : fieldFactories) { <add> final FieldFactoryContextImpl<?> c = new FieldFactoryContextImpl<>().setAttributeModel(attributeModel) <ide> .setFieldFilters(fieldFilters).setFieldEntityModel((EntityModel) fieldEntityModel); <ide> field = ff.constructField(c); <ide> if (field != null) { <ide> } <ide> <ide> if (field == null) { <del> Filter fieldFilter = fieldFilters == null ? null : fieldFilters.get(attributeModel.getPath()); <add> final Filter fieldFilter = fieldFilters == null ? null : fieldFilters.get(attributeModel.getPath()); <ide> if (fieldFilter != null) { <ide> if (AttributeType.MASTER.equals(attributeModel.getAttributeType())) { <ide> // create a combo box or lookup field <ide> <ide> /** <ide> * Constructs a select component for selecting multiple values <del> * <add> * <ide> * @param fieldEntityModel <ide> * the entity model of the entity to display in the field <ide> * @param attributeModel <ide> */ <ide> @SuppressWarnings("unchecked") <ide> public <ID extends Serializable, S extends AbstractEntity<ID>> Field<?> constructCollectionSelect( <del> EntityModel<?> fieldEntityModel, AttributeModel attributeModel, Filter fieldFilter, boolean multipleSelect, <del> boolean search) { <del> EntityModel<?> em = resolveEntityModel(fieldEntityModel, attributeModel); <del> <del> BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator.getServiceForEntity(em.getEntityClass()); <del> SortOrder[] sos = constructSortOrder(em); <add> final EntityModel<?> fieldEntityModel, final AttributeModel attributeModel, final Filter fieldFilter, <add> final boolean multipleSelect, <add> final boolean search) { <add> final EntityModel<?> em = resolveEntityModel(fieldEntityModel, attributeModel); <add> <add> final BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator.getServiceForEntity(em.getEntityClass()); <add> final SortOrder[] sos = constructSortOrder(em); <ide> <ide> // mode depends on whether we are searching <del> AttributeSelectMode mode = search ? attributeModel.getSearchSelectMode() : attributeModel.getSelectMode(); <add> final AttributeSelectMode mode = search ? attributeModel.getSearchSelectMode() : attributeModel.getSelectMode(); <ide> <ide> if (AttributeSelectMode.LOOKUP.equals(mode)) { <ide> // lookup field - take care to NOT use the nested model here! <ide> return constructLookupField(fieldEntityModel, attributeModel, fieldFilter, search, true); <ide> } else if (AttributeSelectMode.FANCY_LIST.equals(mode)) { <ide> // fancy list select <del> FancyListSelect<ID, S> listSelect = new FancyListSelect<>(service, (EntityModel<S>) em, attributeModel, <add> final FancyListSelect<ID, S> listSelect = new FancyListSelect<>(service, (EntityModel<S>) em, attributeModel, <ide> fieldFilter, search, sos); <ide> listSelect.setRows(SystemPropertyUtils.getDefaultListSelectRows()); <ide> return listSelect; <ide> <ide> /** <ide> * Constructs a lookup field (field that brings up a popup search dialog) <del> * <add> * <ide> * @param overruled <ide> * the entity model of the entity to display in the field <ide> * @param attributeModel <ide> */ <ide> @SuppressWarnings("unchecked") <ide> public <ID extends Serializable, S extends AbstractEntity<ID>> EntityLookupField<ID, S> constructLookupField( <del> EntityModel<?> overruled, AttributeModel attributeModel, Filter fieldFilter, boolean search, <del> boolean multiSelect) { <add> final EntityModel<?> overruled, final AttributeModel attributeModel, final Filter fieldFilter, <add> final boolean search, <add> final boolean multiSelect) { <ide> <ide> // for a lookup field, don't use the nested model but the base model - <ide> // this is <ide> // because the search in the popup screen is conducted on a "clean", <ide> // unnested entity list so <ide> // using a path from the parent entity makes no sense here <del> EntityModel<?> entityModel = overruled != null ? overruled <add> final EntityModel<?> entityModel = overruled != null ? overruled <ide> : serviceLocator.getEntityModelFactory().getModel(attributeModel.getNormalizedType()); <ide> <del> BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator.getServiceForEntity( <add> final BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator.getServiceForEntity( <ide> attributeModel.getMemberType() != null ? attributeModel.getMemberType() : entityModel.getEntityClass()); <del> SortOrder[] sos = constructSortOrder(entityModel); <add> final SortOrder[] sos = constructSortOrder(entityModel); <ide> return new EntityLookupField<>(service, (EntityModel<S>) entityModel, attributeModel, fieldFilter, search, <ide> multiSelect, sos.length == 0 ? null : Lists.newArrayList(sos)); <ide> } <ide> /** <ide> * Create a combo box for searching on a boolean. This combo box contains three <ide> * values (yes, no, and null) <del> * <del> * @return <del> */ <del> public ComboBox constructSearchBooleanComboBox(AttributeModel am) { <del> ComboBox cb = new ComboBox(); <add> * <add> * @return <add> */ <add> public ComboBox constructSearchBooleanComboBox(final AttributeModel am) { <add> final ComboBox cb = new ComboBox(); <ide> cb.addItem(Boolean.TRUE); <ide> cb.setItemCaption(Boolean.TRUE, am.getTrueRepresentation()); <ide> cb.addItem(Boolean.FALSE); <ide> cb.setItemCaption(Boolean.FALSE, am.getFalseRepresentation()); <del> return cb; <del> } <del> <del> /** <del> * Construct a combo box that contains a list of String values <del> * <del> * @param values <del> * the list of values <del> * @param am <del> * the attribute model <del> * @return <del> */ <del> public static ComboBox constructStringListCombo(List<String> values, AttributeModel am) { <del> ComboBox cb = new ComboBox(); <del> cb.setCaption(am.getDisplayName()); <del> cb.addItems(values); <del> cb.setFilteringMode(FilteringMode.CONTAINS); <ide> return cb; <ide> } <ide> <ide> */ <ide> @SuppressWarnings("unchecked") <ide> private <ID extends Serializable, S extends AbstractEntity<ID>, O extends Comparable<O>> SimpleTokenFieldSelect<ID, S, O> constructSimpleTokenField( <del> EntityModel<?> entityModel, AttributeModel attributeModel, String distinctField, boolean elementCollection, <del> Filter fieldFilter) { <del> BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator <add> final EntityModel<?> entityModel, final AttributeModel attributeModel, final String distinctField, <add> final boolean elementCollection, <add> final Filter fieldFilter) { <add> final BaseService<ID, S> service = (BaseService<ID, S>) serviceLocator <ide> .getServiceForEntity(entityModel.getEntityClass()); <ide> <del> SortOrder[] sos; <add> final SortOrder[] sos; <ide> if (distinctField == null) { <ide> sos = constructSortOrder(entityModel); <ide> } else { <ide> * the entity model <ide> * @return <ide> */ <del> private SortOrder[] constructSortOrder(EntityModel<?> entityModel) { <del> SortOrder[] sos = new SortOrder[entityModel.getSortOrder().size()]; <add> private SortOrder[] constructSortOrder(final EntityModel<?> entityModel) { <add> final SortOrder[] sos = new SortOrder[entityModel.getSortOrder().size()]; <ide> int i = 0; <del> for (AttributeModel am : entityModel.getSortOrder().keySet()) { <add> for (final AttributeModel am : entityModel.getSortOrder().keySet()) { <ide> sos[i++] = new SortOrder(am.getName(), <ide> entityModel.getSortOrder().get(am) ? SortDirection.ASCENDING : SortDirection.DESCENDING); <ide> } <ide> * @return <ide> */ <ide> @SuppressWarnings({ "unchecked", "rawtypes" }) <del> public <E extends Field<?>> E createEnumCombo(Class<?> type, Class<E> fieldType) { <del> AbstractSelect s = createCompatibleSelect((Class<? extends AbstractSelect>) fieldType); <add> public <E extends Field<?>> E createEnumCombo(final Class<?> type, final Class<E> fieldType) { <add> final AbstractSelect s = createCompatibleSelect((Class<? extends AbstractSelect>) fieldType); <ide> s.setNullSelectionAllowed(true); <ide> fillEnumField(s, (Class<? extends Enum>) type); <ide> return (E) s; <ide> */ <ide> @SuppressWarnings({ "rawtypes", "unchecked" }) <ide> @Override <del> public <F extends Field> F createField(Class<?> type, Class<F> fieldType) { <add> public <F extends Field> F createField(final Class<?> type, final Class<F> fieldType) { <ide> if (Enum.class.isAssignableFrom(type)) { <ide> if (AbstractSelect.class.isAssignableFrom(fieldType)) { <ide> return createEnumCombo(type, fieldType); <ide> } else { <del> ComboBox cb = createEnumCombo(type, ComboBox.class); <add> final ComboBox cb = createEnumCombo(type, ComboBox.class); <ide> cb.setFilteringMode(FilteringMode.CONTAINS); <ide> return (F) cb; <ide> } <ide> } else if (AbstractEntity.class.isAssignableFrom(type)) { <ide> // inside a table, always use a combo box <del> EntityModel<?> entityModel = serviceLocator.getEntityModelFactory().getModel(type); <add> final EntityModel<?> entityModel = serviceLocator.getEntityModelFactory().getModel(type); <ide> return (F) constructComboBox(entityModel, null, null, search); <ide> } <ide> <ide> * @param propertyId <ide> */ <ide> @Override <del> public Field<?> createField(Container container, Object itemId, Object propertyId, Component uiContext) { <add> public Field<?> createField(final Container container, final Object itemId, final Object propertyId, final Component uiContext) { <ide> return createField(propertyId.toString(), null); <ide> } <ide> <ide> * the property <ide> * @return <ide> */ <del> public Field<?> createField(String propertyId) { <add> public Field<?> createField(final String propertyId) { <ide> return createField(propertyId, null); <ide> } <ide> <ide> * the custom entity model for the field <ide> * @return <ide> */ <del> public Field<?> createField(String propertyId, EntityModel<?> fieldEntityModel) { <add> public Field<?> createField(final String propertyId, final EntityModel<?> fieldEntityModel) { <ide> <ide> // in case of a read-only field, return <code>null</code> so Vaadin will <ide> // render a label instead <del> AttributeModel attributeModel = model.getAttributeModel(propertyId); <add> final AttributeModel attributeModel = model.getAttributeModel(propertyId); <ide> if (EditableType.READ_ONLY.equals(attributeModel.getEditableType()) <ide> && (!attributeModel.isUrl() && !AttributeType.DETAIL.equals(attributeModel.getAttributeType())) <ide> && !search) { <ide> } else if ((NumberUtils.isLong(attributeModel.getType()) || NumberUtils.isInteger(attributeModel.getType()) <ide> || BigDecimal.class.equals(attributeModel.getType())) <ide> && NumberSelectMode.SLIDER.equals(attributeModel.getNumberSelectMode())) { <del> Slider slider = new Slider(attributeModel.getDisplayName()); <add> final Slider slider = new Slider(attributeModel.getDisplayName()); <ide> <ide> if (NumberUtils.isInteger(attributeModel.getType())) { <ide> slider.setConverter(new IntToDoubleConverter()); <ide> field = slider; <ide> } else if (attributeModel.isWeek()) { <ide> // special case - week field in a table <del> TextField tf = new TextField(); <add> final TextField tf = new TextField(); <ide> tf.setConverter(Date.class.equals(attributeModel.getType()) ? new WeekCodeConverter() <ide> : new LocalDateWeekCodeConverter()); <ide> field = tf; <ide> } else if (AttributeType.ELEMENT_COLLECTION.equals(attributeModel.getAttributeType())) { <ide> if (!search) { <ide> // use a "collection table" for an element collection <del> FormOptions fo = new FormOptions().setShowRemoveButton(true); <add> final FormOptions fo = new FormOptions().setShowRemoveButton(true); <ide> if (String.class.equals(attributeModel.getMemberType()) <ide> || Integer.class.equals(attributeModel.getMemberType()) <ide> || Long.class.equals(attributeModel.getMemberType()) <ide> // render a multiple select component for a collection <ide> field = constructCollectionSelect(fieldEntityModel, attributeModel, null, true, search); <ide> } else if (LocalDate.class.equals(attributeModel.getType())) { <del> DateField df = new DateField(); <add> final DateField df = new DateField(); <ide> df.setResolution(Resolution.DAY); <ide> df.setConverter(ConverterFactory.createLocalDateConverter()); <ide> df.setTimeZone(VaadinUtils.getTimeZone(UI.getCurrent())); <ide> field = df; <ide> } else if (LocalDateTime.class.equals(attributeModel.getType())) { <del> DateField df = new DateField(); <add> final DateField df = new DateField(); <ide> df.setResolution(Resolution.SECOND); <ide> df.setConverter(ConverterFactory.createLocalDateTimeConverter()); <ide> df.setTimeZone(VaadinUtils.getTimeZone(UI.getCurrent())); <ide> field = df; <ide> } else if (ZonedDateTime.class.equals(attributeModel.getType())) { <del> DateField df = new DateField(); <add> final DateField df = new DateField(); <ide> df.setResolution(Resolution.SECOND); <ide> df.setConverter(ConverterFactory.createZonedDateTimeConverter()); <ide> df.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())); <ide> field = df; <ide> } else if (AttributeDateType.TIME.equals(attributeModel.getDateType())) { <ide> // use custom time field, potentially with Java 8 date converter <del> TimeField tf = new TimeField(); <add> final TimeField tf = new TimeField(); <ide> tf.setResolution(Resolution.MINUTE); <ide> tf.setLocale(VaadinUtils.getLocale()); <ide> if (DateUtils.isJava8DateType(attributeModel.getType())) { <ide> field = tf; <ide> } else if (attributeModel.isUrl()) { <ide> // URL field (offers clickable link in readonly mode) <del> TextField tf = (TextField) createField(attributeModel.getType(), Field.class); <add> final TextField tf = (TextField) createField(attributeModel.getType(), Field.class); <ide> tf.addValidator(new URLValidator(messageService.getMessage("ocs.no.valid.url", VaadinUtils.getLocale()))); <ide> tf.setNullRepresentation(null); <ide> tf.setSizeFull(); <ide> } <ide> <ide> if (field instanceof DateField) { <del> DateField df = (DateField) field; <del> Locale dateLocale = VaadinUtils.getDateLocale(); <add> final DateField df = (DateField) field; <add> final Locale dateLocale = VaadinUtils.getDateLocale(); <ide> df.setLocale(dateLocale); <ide> if (UI.getCurrent() != null) { <ide> df.setTimeZone(VaadinUtils.getTimeZone(UI.getCurrent())); <ide> * @param field <ide> * @param attributeModel <ide> */ <del> private void postProcessField(Field<?> field, AttributeModel attributeModel) { <add> private void postProcessField(final Field<?> field, final AttributeModel attributeModel) { <ide> if (field instanceof AbstractTextField) { <del> AbstractTextField textField = (AbstractTextField) field; <add> final AbstractTextField textField = (AbstractTextField) field; <ide> textField.setDescription(attributeModel.getDescription()); <ide> textField.setNullSettingAllowed(true); <ide> textField.setNullRepresentation(""); <ide> <ide> } else if (field instanceof DateField) { <ide> // set a separate format for a date field <del> DateField dateField = (DateField) field; <add> final DateField dateField = (DateField) field; <ide> if (attributeModel.getDisplayFormat() != null) { <ide> dateField.setDateFormat(attributeModel.getDisplayFormat()); <ide> } <ide> dateField.setResolution(Resolution.SECOND); <ide> } <ide> } <add> // set description for all fields <add> if (field instanceof AbstractField) { <add> ((AbstractField<?>) field).setDescription(attributeModel.getDescription()); <add> } <ide> } <ide> <ide> /** <ide> * Creates a select field for a single-valued attribute <del> * <add> * <ide> * @param attributeModel <ide> * the attribute <ide> * @param fieldEntityModel <ide> * the field filter <ide> * @return <ide> */ <del> protected Field<?> constructSelectField(AttributeModel attributeModel, EntityModel<?> fieldEntityModel, <del> Filter fieldFilter) { <add> protected Field<?> constructSelectField(final AttributeModel attributeModel, final EntityModel<?> fieldEntityModel, <add> final Filter fieldFilter) { <ide> Field<?> field = null; <ide> <del> AttributeSelectMode selectMode = search ? attributeModel.getSearchSelectMode() : attributeModel.getSelectMode(); <add> final AttributeSelectMode selectMode = search ? attributeModel.getSearchSelectMode() : attributeModel.getSelectMode(); <ide> <ide> if (search && attributeModel.isMultipleSearch()) { <ide> // in case of multiple search, defer to the <ide> * @param enumClass <ide> */ <ide> @SuppressWarnings("unchecked") <del> private <E extends Enum<E>> void fillEnumField(AbstractSelect select, Class<E> enumClass) { <add> private <E extends Enum<E>> void fillEnumField(final AbstractSelect select, final Class<E> enumClass) { <ide> select.removeAllItems(); <del> for (Object p : select.getContainerPropertyIds()) { <add> for (final Object p : select.getContainerPropertyIds()) { <ide> select.removeContainerProperty(p); <ide> } <ide> select.addContainerProperty(CAPTION_PROPERTY_ID, String.class, ""); <ide> select.setItemCaptionPropertyId(CAPTION_PROPERTY_ID); <ide> <ide> // sort on the description <del> List<E> list = Arrays.asList(enumClass.getEnumConstants()); <add> final List<E> list = Arrays.asList(enumClass.getEnumConstants()); <ide> list.sort((a, b) -> { <del> String msg1 = messageService.getEnumMessage(enumClass, a, VaadinUtils.getLocale()); <del> String msg2 = messageService.getEnumMessage(enumClass, b, VaadinUtils.getLocale()); <add> final String msg1 = messageService.getEnumMessage(enumClass, a, VaadinUtils.getLocale()); <add> final String msg2 = messageService.getEnumMessage(enumClass, b, VaadinUtils.getLocale()); <ide> return msg1.compareToIgnoreCase(msg2); <ide> }); <ide> <del> for (E e : list) { <del> Item newItem = select.addItem(e); <del> <del> String msg = messageService.getEnumMessage(enumClass, e, VaadinUtils.getLocale()); <add> for (final E e : list) { <add> final Item newItem = select.addItem(e); <add> <add> final String msg = messageService.getEnumMessage(enumClass, e, VaadinUtils.getLocale()); <ide> if (msg != null) { <ide> newItem.getItemProperty(CAPTION_PROPERTY_ID).setValue(msg); <ide> } else { <ide> * the attribute model <ide> * @return <ide> */ <del> private EntityModel<?> resolveEntityModel(EntityModel<?> entityModel, AttributeModel attributeModel) { <add> private EntityModel<?> resolveEntityModel(EntityModel<?> entityModel, final AttributeModel attributeModel) { <ide> if (entityModel == null) { <ide> if (attributeModel.getNestedEntityModel() != null) { <ide> entityModel = attributeModel.getNestedEntityModel(); <ide> } else { <del> Class<?> type = attributeModel.getNormalizedType(); <add> final Class<?> type = attributeModel.getNormalizedType(); <ide> entityModel = serviceLocator.getEntityModelFactory().getModel(type.asSubclass(AbstractEntity.class)); <ide> } <ide> } <ide> * @param attributeModel <ide> * the attribute model of the attribute to bind to the field <ide> */ <del> protected void setConverters(AbstractTextField textField, AttributeModel am) { <add> protected void setConverters(final AbstractTextField textField, final AttributeModel am) { <ide> if (am.getType().equals(BigDecimal.class)) { <ide> textField.setConverter(ConverterFactory.createBigDecimalConverter(am.isCurrency(), am.isPercentage(), <ide> SystemPropertyUtils.useThousandsGroupingInEditMode(), am.getPrecision(),
Java
apache-2.0
9eb025b71a4fdba05293a4c9560d95ee770f4d3d
0
cuba-platform/cuba,cuba-platform/cuba,cuba-platform/cuba
/* * Copyright (c) 2008-2016 Haulmont. * * 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. */ package com.haulmont.cuba.web.gui.components; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.haulmont.bali.events.Subscription; import com.haulmont.bali.util.Preconditions; import com.haulmont.chile.core.model.MetaClass; import com.haulmont.chile.core.model.MetaProperty; import com.haulmont.chile.core.model.MetaPropertyPath; import com.haulmont.cuba.client.sys.PersistenceManagerClient; import com.haulmont.cuba.core.app.keyvalue.KeyValueMetaClass; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.global.*; import com.haulmont.cuba.gui.components.*; import com.haulmont.cuba.gui.components.actions.BaseAction; import com.haulmont.cuba.gui.components.data.BindingState; import com.haulmont.cuba.gui.components.data.DataGridItems; import com.haulmont.cuba.gui.components.data.ValueSourceProvider; import com.haulmont.cuba.gui.components.data.meta.ContainerDataUnit; import com.haulmont.cuba.gui.components.data.meta.DatasourceDataUnit; import com.haulmont.cuba.gui.components.data.meta.EmptyDataUnit; import com.haulmont.cuba.gui.components.data.meta.EntityDataGridItems; import com.haulmont.cuba.gui.components.data.value.ContainerValueSource; import com.haulmont.cuba.gui.components.data.value.ContainerValueSourceProvider; import com.haulmont.cuba.gui.components.formatters.CollectionFormatter; import com.haulmont.cuba.gui.components.security.ActionsPermissions; import com.haulmont.cuba.gui.components.sys.ShortcutsDelegate; import com.haulmont.cuba.gui.components.sys.ShowInfoAction; import com.haulmont.cuba.gui.data.CollectionDatasource; import com.haulmont.cuba.gui.data.Datasource; import com.haulmont.cuba.gui.data.DsBuilder; import com.haulmont.cuba.gui.data.impl.DatasourceImplementation; import com.haulmont.cuba.gui.model.*; import com.haulmont.cuba.gui.model.impl.KeyValueContainerImpl; import com.haulmont.cuba.gui.screen.ScreenValidation; import com.haulmont.cuba.gui.sys.UiTestIds; import com.haulmont.cuba.gui.theme.ThemeConstants; import com.haulmont.cuba.gui.theme.ThemeConstantsManager; import com.haulmont.cuba.web.App; import com.haulmont.cuba.web.AppUI; import com.haulmont.cuba.web.gui.components.datagrid.DataGridDataProvider; import com.haulmont.cuba.web.gui.components.datagrid.DataGridItemsEventsDelegate; import com.haulmont.cuba.web.gui.components.datagrid.SortableDataGridDataProvider; import com.haulmont.cuba.web.gui.components.renderers.*; import com.haulmont.cuba.web.gui.components.util.ShortcutListenerDelegate; import com.haulmont.cuba.web.gui.components.valueproviders.*; import com.haulmont.cuba.web.gui.icons.IconResolver; import com.haulmont.cuba.web.widgets.CubaCssActionsLayout; import com.haulmont.cuba.web.widgets.CubaEnhancedGrid; import com.haulmont.cuba.web.widgets.CubaGridEditorFieldFactory; import com.haulmont.cuba.web.widgets.CubaUI; import com.haulmont.cuba.web.widgets.data.SortableDataProvider; import com.haulmont.cuba.web.widgets.grid.*; import com.vaadin.data.HasValue; import com.vaadin.data.SelectionModel; import com.vaadin.data.ValidationResult; import com.vaadin.data.ValueProvider; import com.vaadin.data.provider.DataProvider; import com.vaadin.data.provider.GridSortOrder; import com.vaadin.data.provider.ListDataProvider; import com.vaadin.event.ShortcutAction.KeyCode; import com.vaadin.event.ShortcutListener; import com.vaadin.event.selection.MultiSelectionEvent; import com.vaadin.shared.Registration; import com.vaadin.shared.ui.grid.HeightMode; import com.vaadin.ui.Component; import com.vaadin.ui.DescriptionGenerator; import com.vaadin.ui.*; import com.vaadin.ui.MenuBar.MenuItem; import com.vaadin.ui.components.grid.*; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import javax.annotation.Nullable; import javax.inject.Inject; import java.beans.PropertyChangeEvent; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import static com.haulmont.bali.util.Preconditions.checkNotNullArgument; import static com.haulmont.cuba.gui.ComponentsHelper.findActionById; import static com.haulmont.cuba.gui.components.Window.Lookup.LOOKUP_ENTER_PRESSED_ACTION_ID; import static com.haulmont.cuba.gui.components.Window.Lookup.LOOKUP_ITEM_CLICK_ACTION_ID; public abstract class WebAbstractDataGrid<C extends Grid<E> & CubaEnhancedGrid<E>, E extends Entity> extends WebAbstractComponent<C> implements DataGrid<E>, SecuredActionsHolder, LookupComponent.LookupSelectionChangeNotifier<E>, DataGridItemsEventsDelegate<E>, HasInnerComponents, InitializingBean { protected static final String HAS_TOP_PANEL_STYLE_NAME = "has-top-panel"; protected static final String TEXT_SELECTION_ENABLED_STYLE = "text-selection-enabled"; private static final Logger log = LoggerFactory.getLogger(WebAbstractDataGrid.class); /* Beans */ protected MetadataTools metadataTools; protected Security security; protected Messages messages; protected MessageTools messageTools; protected PersistenceManagerClient persistenceManagerClient; protected ApplicationContext applicationContext; protected ScreenValidation screenValidation; // Style names used by grid itself protected final List<String> internalStyles = new ArrayList<>(2); protected final Map<String, Column<E>> columns = new HashMap<>(); protected List<Column<E>> columnsOrder = new ArrayList<>(); protected final Map<String, ColumnGenerator<E, ?>> columnGenerators = new HashMap<>(); protected final List<Action> actionList = new ArrayList<>(); protected final ShortcutsDelegate<ShortcutListener> shortcutsDelegate; protected final ActionsPermissions actionsPermissions = new ActionsPermissions(this); protected CubaGridContextMenu<E> contextMenu; protected final List<ActionMenuItemWrapper> contextMenuItems = new ArrayList<>(); protected boolean settingsEnabled = true; protected boolean sortable = true; protected boolean columnsCollapsingAllowed = true; protected boolean textSelectionEnabled = false; protected boolean editorCrossFieldValidate = true; protected Action itemClickAction; protected Action enterPressAction; protected SelectionMode selectionMode; protected GridComposition componentComposition; protected HorizontalLayout topPanel; protected ButtonsPanel buttonsPanel; protected RowsCount rowsCount; protected List<Function<? super E, String>> rowStyleProviders; protected List<CellStyleProvider<? super E>> cellStyleProviders; protected Function<? super E, String> rowDescriptionProvider; protected CellDescriptionProvider<? super E> cellDescriptionProvider; protected DetailsGenerator<E> detailsGenerator = null; protected Registration columnCollapsingChangeListenerRegistration; protected Registration columnResizeListenerRegistration; protected Registration contextClickListenerRegistration; protected Document defaultSettings; protected Registration editorCancelListener; protected Registration editorOpenListener; protected Registration editorBeforeSaveListener; protected Registration editorSaveListener; protected final List<HeaderRow> headerRows = new ArrayList<>(); protected final List<FooterRow> footerRows = new ArrayList<>(); protected static final Map<Class<? extends Renderer>, Class<? extends Renderer>> rendererClasses; protected boolean showIconsForPopupMenuActions; protected DataGridDataProvider<E> dataBinding; protected Map<E, Object> itemDatasources; // lazily initialized WeakHashMap; protected Consumer<EmptyStateClickEvent<E>> emptyStateClickEventHandler; static { ImmutableMap.Builder<Class<? extends Renderer>, Class<? extends Renderer>> builder = new ImmutableMap.Builder<>(); builder.put(TextRenderer.class, WebTextRenderer.class); builder.put(ClickableTextRenderer.class, WebClickableTextRenderer.class); builder.put(HtmlRenderer.class, WebHtmlRenderer.class); builder.put(ProgressBarRenderer.class, WebProgressBarRenderer.class); builder.put(DateRenderer.class, WebDateRenderer.class); builder.put(LocalDateRenderer.class, WebLocalDateRenderer.class); builder.put(LocalDateTimeRenderer.class, WebLocalDateTimeRenderer.class); builder.put(NumberRenderer.class, WebNumberRenderer.class); builder.put(ButtonRenderer.class, WebButtonRenderer.class); builder.put(ImageRenderer.class, WebImageRenderer.class); builder.put(CheckBoxRenderer.class, WebCheckBoxRenderer.class); builder.put(ComponentRenderer.class, WebComponentRenderer.class); builder.put(IconRenderer.class, WebIconRenderer.class); rendererClasses = builder.build(); } public WebAbstractDataGrid() { component = createComponent(); componentComposition = createComponentComposition(); shortcutsDelegate = createShortcutsDelegate(); } protected GridComposition createComponentComposition() { return new GridComposition(); } protected abstract C createComponent(); protected ShortcutsDelegate<ShortcutListener> createShortcutsDelegate() { return new ShortcutsDelegate<ShortcutListener>() { @Override protected ShortcutListener attachShortcut(String actionId, KeyCombination keyCombination) { ShortcutListener shortcut = new ShortcutListenerDelegate(actionId, keyCombination.getKey().getCode(), KeyCombination.Modifier.codes(keyCombination.getModifiers()) ).withHandler((sender, target) -> { if (sender == componentComposition) { Action action = getAction(actionId); if (action != null && action.isEnabled() && action.isVisible()) { action.actionPerform(WebAbstractDataGrid.this); } } }); componentComposition.addShortcutListener(shortcut); return shortcut; } @Override protected void detachShortcut(Action action, ShortcutListener shortcutDescriptor) { componentComposition.removeShortcutListener(shortcutDescriptor); } @Override protected Collection<Action> getActions() { return WebAbstractDataGrid.this.getActions(); } }; } @Override public void afterPropertiesSet() throws Exception { initComponent(component); initComponentComposition(componentComposition); initHeaderRows(component); initFooterRows(component); initEditor(component); initContextMenu(); } @Inject public void setMetadataTools(MetadataTools metadataTools) { this.metadataTools = metadataTools; } @Inject public void setSecurity(Security security) { this.security = security; } @Inject public void setMessages(Messages messages) { this.messages = messages; } @Inject public void setMessageTools(MessageTools messageTools) { this.messageTools = messageTools; } @Inject public void setThemeConstantsManager(ThemeConstantsManager themeConstantsManager) { ThemeConstants theme = themeConstantsManager.getConstants(); this.showIconsForPopupMenuActions = theme.getBoolean("cuba.gui.showIconsForPopupMenuActions", false); } @Inject public void setPersistenceManagerClient(PersistenceManagerClient persistenceManagerClient) { this.persistenceManagerClient = persistenceManagerClient; } @Inject public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Inject protected void setScreenValidation(ScreenValidation screenValidation) { this.screenValidation = screenValidation; } @SuppressWarnings("unchecked") protected void initComponent(Grid<E> component) { setSelectionMode(SelectionMode.SINGLE); component.setColumnReorderingAllowed(true); component.addItemClickListener(this::onItemClick); component.addColumnReorderListener(this::onColumnReorder); component.addSortListener(this::onSort); component.setSizeUndefined(); component.setHeightMode(HeightMode.UNDEFINED); component.setStyleGenerator(this::getGeneratedRowStyle); ((CubaEnhancedGrid<E>) component).setCubaEditorFieldFactory(createEditorFieldFactory()); ((CubaEnhancedGrid<E>) component).setBeforeRefreshHandler(this::onBeforeRefreshGridData); initEmptyState(); } protected void onBeforeRefreshGridData(E item) { clearFieldDatasources(item); } protected CubaGridEditorFieldFactory<E> createEditorFieldFactory() { DataGridEditorFieldFactory fieldFactory = beanLocator.get(DataGridEditorFieldFactory.NAME); return new WebDataGridEditorFieldFactory<>(this, fieldFactory); } protected void initComponentComposition(GridComposition componentComposition) { componentComposition.setPrimaryStyleName("c-data-grid-composition"); componentComposition.setGrid(component); componentComposition.addComponent(component); componentComposition.setWidthUndefined(); componentComposition.addShortcutListener(createEnterShortcutListener()); } protected void onItemClick(Grid.ItemClick<E> e) { CubaUI ui = (CubaUI) component.getUI(); if (!ui.isAccessibleForUser(component)) { LoggerFactory.getLogger(WebDataGrid.class) .debug("Ignore click attempt because DataGrid is inaccessible for user"); return; } com.vaadin.shared.MouseEventDetails vMouseEventDetails = e.getMouseEventDetails(); if (vMouseEventDetails.isDoubleClick() && e.getItem() != null && !WebAbstractDataGrid.this.isEditorEnabled()) { // note: for now Grid doesn't send double click if editor is enabled, // but it's better to handle it manually handleDoubleClickAction(); } if (hasSubscriptions(ItemClickEvent.class)) { MouseEventDetails mouseEventDetails = WebWrapperUtils.toMouseEventDetails(vMouseEventDetails); E item = e.getItem(); if (item == null) { // this can happen if user clicked on an item which is removed from the // datasource, so we don't want to send such event because it's useless return; } Column<E> column = getColumnById(e.getColumn().getId()); ItemClickEvent<E> event = new ItemClickEvent<>(WebAbstractDataGrid.this, mouseEventDetails, item, item.getId(), column != null ? column.getId() : null); publish(ItemClickEvent.class, event); } } protected void onColumnReorder(Grid.ColumnReorderEvent e) { // Grid doesn't know about columns hidden by security permissions, // so we need to return them back to they previous positions columnsOrder = restoreColumnsOrder(getColumnsOrderInternal()); ColumnReorderEvent event = new ColumnReorderEvent(WebAbstractDataGrid.this, e.isUserOriginated()); publish(ColumnReorderEvent.class, event); } protected void onSort(com.vaadin.event.SortEvent<GridSortOrder<E>> e) { if (component.getDataProvider() instanceof SortableDataProvider) { //noinspection unchecked SortableDataProvider<E> dataProvider = (SortableDataProvider<E>) component.getDataProvider(); List<GridSortOrder<E>> sortOrders = e.getSortOrder(); if (sortOrders.isEmpty()) { dataProvider.resetSortOrder(); } else { GridSortOrder<E> sortOrder = sortOrders.get(0); Column<E> column = getColumnByGridColumn(sortOrder.getSorted()); if (column != null) { MetaPropertyPath propertyPath = column.getPropertyPath(); boolean ascending = com.vaadin.shared.data.sort.SortDirection.ASCENDING .equals(sortOrder.getDirection()); dataProvider.sort(new Object[]{propertyPath}, new boolean[]{ascending}); } } } List<SortOrder> sortOrders = convertToDataGridSortOrder(e.getSortOrder()); SortEvent event = new SortEvent(WebAbstractDataGrid.this, sortOrders, e.isUserOriginated()); publish(SortEvent.class, event); } protected void onSelectionChange(com.vaadin.event.selection.SelectionEvent<E> e) { DataGridItems<E> dataGridItems = getItems(); if (dataGridItems == null || dataGridItems.getState() == BindingState.INACTIVE) { return; } Set<E> selected = getSelected(); if (selected.isEmpty()) { dataGridItems.setSelectedItem(null); } else { // reset selection and select new item if (isMultiSelect()) { dataGridItems.setSelectedItem(null); } E newItem = selected.iterator().next(); E dsItem = dataGridItems.getSelectedItem(); dataGridItems.setSelectedItem(newItem); if (Objects.equals(dsItem, newItem)) { // in this case item change event will not be generated refreshActionsState(); } } fireSelectionEvent(e); LookupSelectionChangeEvent<E> selectionChangeEvent = new LookupSelectionChangeEvent<>(this); publish(LookupSelectionChangeEvent.class, selectionChangeEvent); } protected void fireSelectionEvent(com.vaadin.event.selection.SelectionEvent<E> e) { Set<E> oldSelection; if (e instanceof MultiSelectionEvent) { oldSelection = ((MultiSelectionEvent<E>) e).getOldSelection(); } else { //noinspection unchecked E oldValue = ((HasValue.ValueChangeEvent<E>) e).getOldValue(); oldSelection = oldValue != null ? Collections.singleton(oldValue) : Collections.emptySet(); } SelectionEvent<E> event = new SelectionEvent<>(WebAbstractDataGrid.this, oldSelection, e.isUserOriginated()); publish(SelectionEvent.class, event); } protected ShortcutListenerDelegate createEnterShortcutListener() { return new ShortcutListenerDelegate("dataGridEnter", KeyCode.ENTER, null) .withHandler((sender, target) -> { if (sender == componentComposition) { if (isEditorEnabled()) { // Prevent custom actions on Enter if DataGrid editor is enabled // since it's the default shortcut to open editor return; } CubaUI ui = (CubaUI) componentComposition.getUI(); if (!ui.isAccessibleForUser(componentComposition)) { LoggerFactory.getLogger(WebDataGrid.class) .debug("Ignore click attempt because DataGrid is inaccessible for user"); return; } if (enterPressAction != null) { enterPressAction.actionPerform(this); } else { handleDoubleClickAction(); } } }); } @Override public Collection<com.haulmont.cuba.gui.components.Component> getInnerComponents() { if (buttonsPanel != null) { return Collections.singletonList(buttonsPanel); } return Collections.emptyList(); } protected void initEditor(Grid<E> component) { component.getEditor().setSaveCaption(messages.getMainMessage("actions.Ok")); component.getEditor().setCancelCaption(messages.getMainMessage("actions.Cancel")); } protected void initHeaderRows(Grid<E> component) { for (int i = 0; i < component.getHeaderRowCount(); i++) { com.vaadin.ui.components.grid.HeaderRow headerRow = component.getHeaderRow(i); addHeaderRowInternal(headerRow); } } protected void initFooterRows(Grid<E> component) { for (int i = 0; i < component.getFooterRowCount(); i++) { com.vaadin.ui.components.grid.FooterRow footerRow = component.getFooterRow(i); addFooterRowInternal(footerRow); } } protected List<Column<E>> getColumnsOrderInternal() { List<Grid.Column<E, ?>> columnsOrder = component.getColumns(); return columnsOrder.stream() .map(this::getColumnByGridColumn) .collect(Collectors.toList()); } /** * Inserts columns hidden by security permissions (or with visible = false, * which means that where is no Grid.Column associated with DatGrid.Column) * into a list of visible columns, passed as a parameter, in they original positions. * * @param visibleColumns the list of DataGrid columns, * not hidden by security permissions * @return a list of all columns in DataGrid */ protected List<Column<E>> restoreColumnsOrder(List<Column<E>> visibleColumns) { List<Column<E>> newColumnsOrder = new ArrayList<>(visibleColumns); columnsOrder.stream() .filter(column -> !visibleColumns.contains(column)) .forEach(column -> newColumnsOrder.add(columnsOrder.indexOf(column), column)); return newColumnsOrder; } protected void initContextMenu() { contextMenu = new CubaGridContextMenu<>(component); contextMenu.addGridBodyContextMenuListener(event -> { if (!component.getSelectedItems().contains(event.getItem())) { // In the multi select model 'setSelected' adds item to selected set, // but, in case of context click, we want to have a single selected item, // if it isn't in a set of already selected items if (isMultiSelect()) { component.deselectAll(); } setSelected(event.getItem()); } }); } protected void refreshActionsState() { getActions().forEach(Action::refreshState); } protected void handleDoubleClickAction() { Action action = getItemClickAction(); if (action == null) { action = getEnterAction(); if (action == null) { action = getAction("edit"); if (action == null) { action = getAction("view"); } } } if (action != null && action.isEnabled()) { action.actionPerform(WebAbstractDataGrid.this); } } @Override public void focus() { component.focus(); } @Override public void setLookupSelectHandler(Consumer<Collection<E>> selectHandler) { Consumer<Action.ActionPerformedEvent> actionHandler = event -> { Set<E> selected = getSelected(); selectHandler.accept(selected); }; setEnterPressAction(new BaseAction(LOOKUP_ENTER_PRESSED_ACTION_ID) .withHandler(actionHandler)); setItemClickAction(new BaseAction(LOOKUP_ITEM_CLICK_ACTION_ID) .withHandler(actionHandler)); if (buttonsPanel != null && !buttonsPanel.isAlwaysVisible()) { buttonsPanel.setVisible(false); } setEditorEnabled(false); } @Override public Collection<E> getLookupSelectedItems() { return getSelected(); } protected Action getEnterAction() { for (Action action : getActions()) { KeyCombination kc = action.getShortcutCombination(); if (kc != null) { if ((kc.getModifiers() == null || kc.getModifiers().length == 0) && kc.getKey() == KeyCombination.Key.ENTER) { return action; } } } return null; } @Override public List<Column<E>> getColumns() { return Collections.unmodifiableList(columnsOrder); } @Override public List<Column<E>> getVisibleColumns() { return columnsOrder.stream() .filter(Column::isVisible) .collect(Collectors.toList()); } @Nullable @Override public Column<E> getColumn(String id) { checkNotNullArgument(id); return columns.get(id); } @Override public Column<E> getColumnNN(String id) { Column<E> column = getColumn(id); if (column == null) { throw new IllegalStateException("Unable to find column with id " + id); } return column; } @Override public void addColumn(Column<E> column) { addColumn(column, columnsOrder.size()); } @Override public void addColumn(Column<E> column, int index) { checkNotNullArgument(column, "Column must be non null"); if (column.getOwner() != null && column.getOwner() != this) { throw new IllegalArgumentException("Can't add column owned by another DataGrid"); } addColumnInternal((ColumnImpl<E>) column, index); } @Override public Column<E> addColumn(String id, MetaPropertyPath propertyPath) { return addColumn(id, propertyPath, columnsOrder.size()); } @Override public Column<E> addColumn(String id, MetaPropertyPath propertyPath, int index) { ColumnImpl<E> column = new ColumnImpl<>(id, propertyPath, this); addColumnInternal(column, index); return column; } protected void addColumnInternal(ColumnImpl<E> column, int index) { Grid.Column<E, ?> gridColumn = component.addColumn( new EntityValueProvider<>(column.getPropertyPath())); columns.put(column.getId(), column); columnsOrder.add(index, column); final String caption = StringUtils.capitalize(column.getCaption() != null ? column.getCaption() : generateColumnCaption(column)); column.setCaption(caption); if (column.getOwner() == null) { column.setOwner(this); } MetaPropertyPath propertyPath = column.getPropertyPath(); if (propertyPath != null) { MetaProperty metaProperty = propertyPath.getMetaProperty(); MetaClass propertyMetaClass = metadataTools.getPropertyEnclosingMetaClass(propertyPath); String storeName = metadataTools.getStoreName(propertyMetaClass); if (metadataTools.isLob(metaProperty) && !persistenceManagerClient.supportsLobSortingAndFiltering(storeName)) { column.setSortable(false); } } setupGridColumnProperties(gridColumn, column); component.setColumnOrder(getColumnOrder()); } protected String generateColumnCaption(Column<E> column) { return column.getPropertyPath() != null ? column.getPropertyPath().getMetaProperty().getName() : column.getId(); } protected void setupGridColumnProperties(Grid.Column<E, ?> gridColumn, Column<E> column) { if (gridColumn.getId() == null) { gridColumn.setId(column.getId()); } else if (!Objects.equals(gridColumn.getId(), column.getId())) { log.warn("Trying to copy column settings with mismatched ids. Grid.Column: " + gridColumn.getId() + "; DataGrid.Column: " + column.getId()); } gridColumn.setCaption(column.getCaption()); gridColumn.setHidingToggleCaption(column.getCollapsingToggleCaption()); if (column.isWidthAuto()) { gridColumn.setWidthUndefined(); } else { gridColumn.setWidth(column.getWidth()); } gridColumn.setExpandRatio(column.getExpandRatio()); gridColumn.setMinimumWidth(column.getMinimumWidth()); gridColumn.setMaximumWidth(column.getMaximumWidth()); gridColumn.setHidden(column.isCollapsed()); gridColumn.setHidable(column.isCollapsible() && column.getOwner().isColumnsCollapsingAllowed()); gridColumn.setResizable(column.isResizable()); gridColumn.setSortable(column.isSortable() && column.getOwner().isSortable()); gridColumn.setEditable(column.isEditable()); AppUI current = AppUI.getCurrent(); if (current != null && current.isTestMode()) { addColumnId(gridColumn, column); } //noinspection unchecked gridColumn.setRenderer(getDefaultPresentationValueProvider(column), getDefaultRenderer(column)); gridColumn.setStyleGenerator(new CellStyleGeneratorAdapter<>(column)); gridColumn.setDescriptionGenerator(new CellDescriptionGeneratorAdapter<>(column), WebWrapperUtils.toVaadinContentMode(((ColumnImpl) column).getDescriptionContentMode())); ((ColumnImpl<E>) column).setGridColumn(gridColumn); } protected ValueProvider getDefaultPresentationValueProvider(Column<E> column) { MetaProperty metaProperty = column.getPropertyPath() != null ? column.getPropertyPath().getMetaProperty() : null; if (column.getFormatter() != null) { //noinspection unchecked return new FormatterBasedValueProvider<>(column.getFormatter()); } else if (metaProperty != null) { if (Collection.class.isAssignableFrom(metaProperty.getJavaType())) { return new FormatterBasedValueProvider<>(new CollectionFormatter(metadataTools)); } if (column.getType() == Boolean.class) { return new YesNoIconPresentationValueProvider(); } } return new StringPresentationValueProvider(metaProperty, metadataTools); } protected com.vaadin.ui.renderers.Renderer getDefaultRenderer(Column<E> column) { MetaProperty metaProperty = column.getPropertyPath() != null ? column.getPropertyPath().getMetaProperty() : null; return column.getType() == Boolean.class && metaProperty != null ? new com.vaadin.ui.renderers.HtmlRenderer() : new com.vaadin.ui.renderers.TextRenderer(); } protected void addColumnId(Grid.Column<E, ?> gridColumn, Column<E> column) { component.addColumnId(gridColumn.getState().internalId, column.getId()); } protected void removeColumnId(Grid.Column<E, ?> gridColumn) { component.removeColumnId(gridColumn.getId()); } @Override public void removeColumn(Column<E> column) { if (column == null) { return; } component.removeColumn(column.getId()); columns.remove(column.getId()); columnsOrder.remove(column); columnGenerators.remove(column.getId()); ((ColumnImpl<E>) column).setGridColumn(null); column.setOwner(null); } @Override public void removeColumn(String id) { removeColumn(getColumn(id)); } @Nullable @Override public DataGridItems<E> getItems() { return this.dataBinding != null ? this.dataBinding.getDataGridItems() : null; } protected DataGridItems<E> getDataGridItemsNN() { DataGridItems<E> dataGridItems = getItems(); if (dataGridItems == null || dataGridItems.getState() == BindingState.INACTIVE) { throw new IllegalStateException("DataGridItems is not active"); } return dataGridItems; } protected EntityDataGridItems<E> getEntityDataGridItems() { return getItems() != null ? (EntityDataGridItems<E>) getItems() : null; } protected EntityDataGridItems<E> getEntityDataGridItemsNN() { return (EntityDataGridItems<E>) getDataGridItemsNN(); } @Override public void setItems(DataGridItems<E> dataGridItems) { if (dataGridItems != null && !(dataGridItems instanceof EntityDataGridItems)) { throw new IllegalArgumentException("DataGrid supports only EntityDataGridItems"); } if (this.dataBinding != null) { this.dataBinding.unbind(); this.dataBinding = null; clearFieldDatasources(null); this.component.setDataProvider(createEmptyDataProvider()); } if (dataGridItems != null) { // DataGrid supports only EntityDataGridItems EntityDataGridItems<E> entityDataGridSource = (EntityDataGridItems<E>) dataGridItems; if (this.columns.isEmpty()) { setupAutowiredColumns(entityDataGridSource); } // Bind new datasource this.dataBinding = createDataGridDataProvider(dataGridItems); this.component.setDataProvider(this.dataBinding); List<Column<E>> visibleColumnsOrder = getInitialVisibleColumns(); setVisibleColumns(visibleColumnsOrder); for (Column<E> column : visibleColumnsOrder) { Grid.Column<E, ?> gridColumn = ((ColumnImpl<E>) column).getGridColumn(); setupGridColumnProperties(gridColumn, column); } component.setColumnOrder(getColumnOrder()); initShowInfoAction(); if (rowsCount != null) { rowsCount.setRowsCountTarget(this); } if (!canBeSorted(dataGridItems)) { setSortable(false); } // resort data if dataGrid have been sorted before setting items if (isSortable()) { List<GridSortOrder<E>> sortOrders = component.getSortOrder(); if (!sortOrders.isEmpty()) { List<GridSortOrder<E>> copiedSortOrders = new ArrayList<>(sortOrders); component.clearSortOrder(); component.setSortOrder(copiedSortOrders); } } refreshActionsState(); setUiTestId(dataGridItems); } initEmptyState(); } protected void setUiTestId(DataGridItems<E> items) { AppUI ui = AppUI.getCurrent(); if (ui != null && ui.isTestMode() && getComponent().getCubaId() == null) { String testId = UiTestIds.getInferredTestId(items, "DataGrid"); if (testId != null) { getComponent().setCubaId(testId); componentComposition.setCubaId(testId + "_composition"); } } } protected DataProvider<E, ?> createEmptyDataProvider() { return new ListDataProvider<>(Collections.emptyList()); } protected void setVisibleColumns(List<Column<E>> visibleColumnsOrder) { // mark columns hidden by security permissions as visible = false // and remove Grid.Column to prevent its property changing columnsOrder.stream() .filter(column -> !visibleColumnsOrder.contains(column)) .forEach(column -> { ColumnImpl<E> columnImpl = (ColumnImpl<E>) column; columnImpl.setVisible(false); columnImpl.setGridColumn(null); }); } protected Collection<MetaPropertyPath> getAutowiredProperties(EntityDataGridItems<E> entityDataGridSource) { if (entityDataGridSource instanceof ContainerDataUnit) { CollectionContainer container = ((ContainerDataUnit) entityDataGridSource).getContainer(); return container.getView() != null ? // if a view is specified - use view properties metadataTools.getViewPropertyPaths(container.getView(), container.getEntityMetaClass()) : // otherwise use all properties from meta-class metadataTools.getPropertyPaths(container.getEntityMetaClass()); } if (entityDataGridSource instanceof DatasourceDataUnit) { CollectionDatasource datasource = ((DatasourceDataUnit) entityDataGridSource).getDatasource(); return datasource.getView() != null ? // if a view is specified - use view properties metadataTools.getViewPropertyPaths(datasource.getView(), datasource.getMetaClass()) : // otherwise use all properties from meta-class metadataTools.getPropertyPaths(datasource.getMetaClass()); } if (entityDataGridSource instanceof EmptyDataUnit) { return metadataTools.getPropertyPaths(entityDataGridSource.getEntityMetaClass()); } return Collections.emptyList(); } protected void setupAutowiredColumns(EntityDataGridItems<E> entityDataGridSource) { Collection<MetaPropertyPath> paths = getAutowiredProperties(entityDataGridSource); for (MetaPropertyPath metaPropertyPath : paths) { MetaProperty property = metaPropertyPath.getMetaProperty(); if (!property.getRange().getCardinality().isMany() && !metadataTools.isSystem(property)) { String propertyName = property.getName(); ColumnImpl<E> column = new ColumnImpl<>(propertyName, metaPropertyPath, this); MetaClass propertyMetaClass = metadataTools.getPropertyEnclosingMetaClass(metaPropertyPath); column.setCaption(messageTools.getPropertyCaption(propertyMetaClass, propertyName)); addColumn(column); } } } protected DataGridDataProvider<E> createDataGridDataProvider(DataGridItems<E> dataGridItems) { return (dataGridItems instanceof DataGridItems.Sortable) ? new SortableDataGridDataProvider<>((DataGridItems.Sortable<E>) dataGridItems, this) : new DataGridDataProvider<>(dataGridItems, this); } @Override public void dataGridSourceItemSetChanged(DataGridItems.ItemSetChangeEvent<E> event) { // #PL-2035, reload selection from ds Set<E> selectedItems = getSelected(); Set<E> newSelection = new HashSet<>(); for (E item : selectedItems) { if (event.getSource().containsItem(item)) { newSelection.add(event.getSource().getItem(item.getId())); } } if (event.getSource().getState() == BindingState.ACTIVE && event.getSource().getSelectedItem() != null) { newSelection.add(event.getSource().getSelectedItem()); } if (newSelection.isEmpty()) { setSelected((E) null); } else { // Workaround for the MultiSelect model. // Set the selected items only if the previous selection is different // Otherwise, the DataGrid rows will display the values before editing if (isMultiSelect() && !selectedItems.equals(newSelection)) { setSelectedItems(newSelection); } } refreshActionsState(); } @Override public void dataGridSourcePropertyValueChanged(DataGridItems.ValueChangeEvent<E> event) { refreshActionsState(); } @Override public void dataGridSourceStateChanged(DataGridItems.StateChangeEvent event) { refreshActionsState(); } @Override public void dataGridSourceSelectedItemChanged(DataGridItems.SelectedItemChangeEvent<E> event) { refreshActionsState(); } protected String[] getColumnOrder() { return columnsOrder.stream() .filter(Column::isVisible) .map(Column::getId) .toArray(String[]::new); } protected void initShowInfoAction() { if (security.isSpecificPermitted(ShowInfoAction.ACTION_PERMISSION)) { if (getAction(ShowInfoAction.ACTION_ID) == null) { addAction(new ShowInfoAction()); } } } @Override public String getCaption() { return getComposition().getCaption(); } @Override public void setCaption(String caption) { getComposition().setCaption(caption); } @Override public boolean isCaptionAsHtml() { return ((com.vaadin.ui.AbstractComponent) getComposition()).isCaptionAsHtml(); } @Override public void setCaptionAsHtml(boolean captionAsHtml) { ((com.vaadin.ui.AbstractComponent) getComposition()).setCaptionAsHtml(captionAsHtml); } @Override public boolean isTextSelectionEnabled() { return textSelectionEnabled; } @Override public void setTextSelectionEnabled(boolean textSelectionEnabled) { if (this.textSelectionEnabled != textSelectionEnabled) { this.textSelectionEnabled = textSelectionEnabled; if (textSelectionEnabled) { if (!internalStyles.contains(TEXT_SELECTION_ENABLED_STYLE)) { internalStyles.add(TEXT_SELECTION_ENABLED_STYLE); } componentComposition.addStyleName(TEXT_SELECTION_ENABLED_STYLE); } else { internalStyles.remove(TEXT_SELECTION_ENABLED_STYLE); componentComposition.removeStyleName(TEXT_SELECTION_ENABLED_STYLE); } } } @Override public boolean isColumnReorderingAllowed() { return component.isColumnReorderingAllowed(); } @Override public void setColumnReorderingAllowed(boolean columnReorderingAllowed) { component.setColumnReorderingAllowed(columnReorderingAllowed); } @Override public boolean isSortable() { return sortable; } @Override public void setSortable(boolean sortable) { this.sortable = sortable && (getItems() == null || canBeSorted(getItems())); for (Column<E> column : getColumns()) { ((ColumnImpl<E>) column).updateSortable(); } } @Override public boolean isColumnsCollapsingAllowed() { return columnsCollapsingAllowed; } @Override public void setColumnsCollapsingAllowed(boolean columnsCollapsingAllowed) { this.columnsCollapsingAllowed = columnsCollapsingAllowed; for (Column<E> column : getColumns()) { ((ColumnImpl<E>) column).updateCollapsible(); } } @Override public boolean isEditorEnabled() { return component.getEditor().isEnabled(); } @Override public void setEditorEnabled(boolean isEnabled) { component.getEditor().setEnabled(isEnabled); enableCrossFieldValidationHandling(editorCrossFieldValidate); } @Override public boolean isEditorBuffered() { return component.getEditor().isBuffered(); } @Override public void setEditorBuffered(boolean editorBuffered) { component.getEditor().setBuffered(editorBuffered); } @Override public String getEditorSaveCaption() { return component.getEditor().getSaveCaption(); } @Override public void setEditorSaveCaption(String saveCaption) { component.getEditor().setSaveCaption(saveCaption); } @Override public String getEditorCancelCaption() { return component.getEditor().getCancelCaption(); } @Override public void setEditorCancelCaption(String cancelCaption) { component.getEditor().setCancelCaption(cancelCaption); } @Nullable @Override public Object getEditedItemId() { E item = getEditedItem(); return item != null ? item.getId() : null; } @Override public E getEditedItem() { return component.getEditor() instanceof CubaEditorImpl ? ((CubaEditorImpl<E>) component.getEditor()).getBean() : component.getEditor().getBinder().getBean(); } @Override public boolean isEditorActive() { return component.getEditor().isOpen(); } @Override public void editItem(Object itemId) { checkNotNullArgument(itemId, "Item's Id must be non null"); DataGridItems<E> dataGridItems = getItems(); if (dataGridItems == null || dataGridItems.getState() == BindingState.INACTIVE) { return; } E item = getItems().getItem(itemId); edit(item); } @Override public void edit(E item) { checkNotNullArgument(item, "Entity must be non null"); DataGridItems<E> dataGridItems = getItems(); if (dataGridItems == null || dataGridItems.getState() == BindingState.INACTIVE) { return; } if (!dataGridItems.containsItem(item)) { throw new IllegalArgumentException("Datasource doesn't contain item"); } editItemInternal(item); } protected void editItemInternal(E item) { int rowIndex = getDataGridItemsNN().indexOfItem(item); component.getEditor().editRow(rowIndex); } @SuppressWarnings("ConstantConditions") protected Map<String, Field> convertToCubaFields(Map<Grid.Column<E, ?>, Component> columnFieldMap) { return columnFieldMap.entrySet().stream() .filter(entry -> getColumnByGridColumn(entry.getKey()) != null) .collect(Collectors.toMap( entry -> getColumnByGridColumn(entry.getKey()).getId(), entry -> ((DataGridEditorCustomField) entry.getValue()).getField()) ); } @Override public Subscription addEditorOpenListener(Consumer<EditorOpenEvent> listener) { if (editorOpenListener == null) { editorOpenListener = component.getEditor().addOpenListener(this::onEditorOpen); } return getEventHub().subscribe(EditorOpenEvent.class, listener); } protected void onEditorOpen(com.vaadin.ui.components.grid.EditorOpenEvent<E> editorOpenEvent) { //noinspection unchecked CubaEditorOpenEvent<E> event = ((CubaEditorOpenEvent) editorOpenEvent); Map<String, Field> fields = convertToCubaFields(event.getColumnFieldMap()); EditorOpenEvent<E> e = new EditorOpenEvent<>(this, event.getBean(), fields); publish(EditorOpenEvent.class, e); } @Override public void removeEditorOpenListener(Consumer<EditorOpenEvent> listener) { unsubscribe(EditorOpenEvent.class, listener); if (!hasSubscriptions(EditorOpenEvent.class)) { editorOpenListener.remove(); editorOpenListener = null; } } @Override public Subscription addEditorCloseListener(Consumer<EditorCloseEvent> listener) { if (editorCancelListener == null) { editorCancelListener = component.getEditor().addCancelListener(this::onEditorCancel); } return getEventHub().subscribe(EditorCloseEvent.class, listener); } protected void onEditorCancel(EditorCancelEvent<E> cancelEvent) { //noinspection unchecked CubaEditorCancelEvent<E> event = ((CubaEditorCancelEvent) cancelEvent); Map<String, Field> fields = convertToCubaFields(event.getColumnFieldMap()); EditorCloseEvent<E> e = new EditorCloseEvent<>(this, event.getBean(), fields); publish(EditorCloseEvent.class, e); } @Override public void removeEditorCloseListener(Consumer<EditorCloseEvent> listener) { unsubscribe(EditorCloseEvent.class, listener); if (!hasSubscriptions(EditorCloseEvent.class)) { editorCancelListener.remove(); editorCancelListener = null; } } @Override public Subscription addEditorPreCommitListener(Consumer<EditorPreCommitEvent> listener) { if (editorBeforeSaveListener == null) { //noinspection unchecked CubaEditorImpl<E> editor = (CubaEditorImpl) component.getEditor(); editorBeforeSaveListener = editor.addBeforeSaveListener(this::onEditorBeforeSave); } return getEventHub().subscribe(EditorPreCommitEvent.class, listener); } protected void onEditorBeforeSave(CubaEditorBeforeSaveEvent<E> event) { Map<String, Field> fields = convertToCubaFields(event.getColumnFieldMap()); EditorPreCommitEvent<E> e = new EditorPreCommitEvent<>(this, event.getBean(), fields); publish(EditorPreCommitEvent.class, e); } @Override public void removeEditorPreCommitListener(Consumer<EditorPreCommitEvent> listener) { unsubscribe(EditorPreCommitEvent.class, listener); if (!hasSubscriptions(EditorPreCommitEvent.class)) { editorBeforeSaveListener.remove(); editorBeforeSaveListener = null; } } @Override public Subscription addEditorPostCommitListener(Consumer<EditorPostCommitEvent> listener) { if (editorSaveListener == null) { editorSaveListener = component.getEditor().addSaveListener(this::onEditorSave); } return getEventHub().subscribe(EditorPostCommitEvent.class, listener); } @Override public void setEditorCrossFieldValidate(boolean validate) { this.editorCrossFieldValidate = validate; enableCrossFieldValidationHandling(validate); } @Override public boolean isEditorCrossFieldValidate() { return editorCrossFieldValidate; } protected void onEditorSave(EditorSaveEvent<E> saveEvent) { //noinspection unchecked CubaEditorSaveEvent<E> event = ((CubaEditorSaveEvent) saveEvent); Map<String, Field> fields = convertToCubaFields(event.getColumnFieldMap()); EditorPostCommitEvent<E> e = new EditorPostCommitEvent<>(this, event.getBean(), fields); publish(EditorPostCommitEvent.class, e); } @Override public void removeEditorPostCommitListener(Consumer<EditorPostCommitEvent> listener) { unsubscribe(EditorPostCommitEvent.class, listener); if (!hasSubscriptions(EditorPostCommitEvent.class)) { editorSaveListener.remove(); editorSaveListener = null; } } protected Datasource createItemDatasource(E item) { if (itemDatasources == null) { itemDatasources = new WeakHashMap<>(); } Object fieldDatasource = itemDatasources.get(item); if (fieldDatasource instanceof Datasource) { return (Datasource) fieldDatasource; } EntityDataGridItems<E> items = getEntityDataGridItemsNN(); Datasource datasource = DsBuilder.create() .setAllowCommit(false) .setMetaClass(items.getEntityMetaClass()) .setRefreshMode(CollectionDatasource.RefreshMode.NEVER) .setViewName(View.LOCAL) .buildDatasource(); ((DatasourceImplementation) datasource).valid(); //noinspection unchecked datasource.setItem(item); return datasource; } protected InstanceContainer<E> createInstanceContainer(E item) { if (itemDatasources == null) { itemDatasources = new WeakHashMap<>(); } Object container = itemDatasources.get(item); if (container instanceof InstanceContainer) { //noinspection unchecked return (InstanceContainer<E>) container; } EntityDataGridItems<E> items = getEntityDataGridItemsNN(); DataComponents factory = beanLocator.get(DataComponents.class); ViewRepository viewRepository = beanLocator.get(ViewRepository.NAME); MetaClass metaClass = items.getEntityMetaClass(); InstanceContainer<E> instanceContainer; if (metaClass instanceof KeyValueMetaClass) { //noinspection unchecked instanceContainer = (InstanceContainer<E>) new KeyValueContainerImpl((KeyValueMetaClass) metaClass); } else { instanceContainer = factory.createInstanceContainer(metaClass.getJavaClass()); } instanceContainer.setView(viewRepository.getView(metaClass, View.LOCAL)); instanceContainer.setItem(item); itemDatasources.put(item, instanceContainer); return instanceContainer; } protected void clearFieldDatasources(E item) { if (itemDatasources == null) { return; } if (item != null) { if (isEditorActive() && !isEditorBuffered() && item.equals(getEditedItem())) { return; } Object removed = itemDatasources.remove(item); if (removed != null) { detachItemContainer(removed); } } else { // detach instance containers from entities explicitly for (Map.Entry<E, Object> entry : itemDatasources.entrySet()) { detachItemContainer(entry.getValue()); } itemDatasources.clear(); } } @SuppressWarnings("unchecked") protected void detachItemContainer(Object container) { if (container instanceof InstanceContainer) { InstanceContainer<E> instanceContainer = (InstanceContainer<E>) container; instanceContainer.setItem(null); } else if (container instanceof Datasource) { Datasource<E> datasource = (Datasource<E>) container; datasource.setItem(null); } } protected ValueSourceProvider createValueSourceProvider(E item) { InstanceContainer<E> instanceContainer = createInstanceContainer(item); return new ContainerValueSourceProvider<>(instanceContainer); } protected static class WebDataGridEditorFieldFactory<E extends Entity> implements CubaGridEditorFieldFactory<E> { protected WebAbstractDataGrid<?, E> dataGrid; protected DataGridEditorFieldFactory fieldFactory; public WebDataGridEditorFieldFactory(WebAbstractDataGrid<?, E> dataGrid, DataGridEditorFieldFactory fieldFactory) { this.dataGrid = dataGrid; this.fieldFactory = fieldFactory; } @Override public CubaEditorField<?> createField(E bean, Grid.Column<E, ?> gridColumn) { ColumnImpl<E> column = dataGrid.getColumnByGridColumn(gridColumn); if (column == null || !column.isShouldBeEditable()) { return null; } Field columnComponent; if (column.getEditFieldGenerator() != null) { ValueSourceProvider valueSourceProvider = dataGrid.createValueSourceProvider(bean); EditorFieldGenerationContext<E> context = new EditorFieldGenerationContext<>(bean, valueSourceProvider); columnComponent = column.getEditFieldGenerator().apply(context); } else { String fieldPropertyId = String.valueOf(column.getPropertyId()); if (column.getEditorFieldGenerator() != null) { Datasource fieldDatasource = dataGrid.createItemDatasource(bean); columnComponent = column.getEditorFieldGenerator().createField(fieldDatasource, fieldPropertyId); } else { InstanceContainer<E> container = dataGrid.createInstanceContainer(bean); columnComponent = fieldFactory.createField( new ContainerValueSource<>(container, fieldPropertyId), fieldPropertyId); } } columnComponent.setParent(dataGrid); columnComponent.setFrame(dataGrid.getFrame()); return createCustomField(columnComponent); } protected CubaEditorField createCustomField(final Field columnComponent) { if (!(columnComponent instanceof Buffered)) { throw new IllegalArgumentException("Editor field must implement " + "com.haulmont.cuba.gui.components.Buffered"); } Component content = WebComponentsHelper.getComposition(columnComponent); //noinspection unchecked CubaEditorField wrapper = new DataGridEditorCustomField(columnComponent) { @Override protected Component initContent() { return content; } }; if (content instanceof Component.Focusable) { wrapper.setFocusDelegate((Component.Focusable) content); } wrapper.setReadOnly(!columnComponent.isEditable()); wrapper.setRequiredIndicatorVisible(columnComponent.isRequired()); //noinspection unchecked columnComponent.addValueChangeListener(event -> wrapper.markAsDirty()); return wrapper; } } protected static abstract class DataGridEditorCustomField<T> extends CubaEditorField<T> { protected Field<T> columnComponent; public DataGridEditorCustomField(Field<T> columnComponent) { this.columnComponent = columnComponent; initComponent(this.columnComponent); } protected void initComponent(Field<T> columnComponent) { columnComponent.addValueChangeListener(event -> fireEvent(createValueChange(event.getPrevValue(), event.isUserOriginated()))); } protected Field getField() { return columnComponent; } @Override protected void doSetValue(T value) { columnComponent.setValue(value); } @Override public T getValue() { return columnComponent.getValue(); } @Override public boolean isBuffered() { return ((Buffered) columnComponent).isBuffered(); } @Override public void setBuffered(boolean buffered) { ((Buffered) columnComponent).setBuffered(buffered); } @Override public void commit() { ((Buffered) columnComponent).commit(); } @Override public ValidationResult validate() { try { columnComponent.validate(); return ValidationResult.ok(); } catch (ValidationException e) { return ValidationResult.error(e.getDetailsMessage()); } } @Override public void discard() { ((Buffered) columnComponent).discard(); } @Override public boolean isModified() { return ((Buffered) columnComponent).isModified(); } @Override public void setWidth(float width, Unit unit) { super.setWidth(width, unit); if (getContent() != null) { if (width < 0) { getContent().setWidthUndefined(); } else { getContent().setWidth(100, Unit.PERCENTAGE); } } } @Override public void setHeight(float height, Unit unit) { super.setHeight(height, unit); if (getContent() != null) { if (height < 0) { getContent().setHeightUndefined(); } else { getContent().setHeight(100, Unit.PERCENTAGE); } } } } @Override public boolean isHeaderVisible() { return component.isHeaderVisible(); } @Override public void setHeaderVisible(boolean headerVisible) { component.setHeaderVisible(headerVisible); } @Override public boolean isFooterVisible() { return component.isFooterVisible(); } @Override public void setFooterVisible(boolean footerVisible) { component.setFooterVisible(footerVisible); } @Override public double getBodyRowHeight() { return component.getBodyRowHeight(); } @Override public void setBodyRowHeight(double rowHeight) { component.setBodyRowHeight(rowHeight); } @Override public double getHeaderRowHeight() { return component.getHeaderRowHeight(); } @Override public void setHeaderRowHeight(double rowHeight) { component.setHeaderRowHeight(rowHeight); } @Override public double getFooterRowHeight() { return component.getFooterRowHeight(); } @Override public void setFooterRowHeight(double rowHeight) { component.setFooterRowHeight(rowHeight); } @Override public boolean isContextMenuEnabled() { return contextMenu.isEnabled(); } @Override public void setContextMenuEnabled(boolean contextMenuEnabled) { contextMenu.setEnabled(contextMenuEnabled); } @Override public ColumnResizeMode getColumnResizeMode() { return WebWrapperUtils.convertToDataGridColumnResizeMode(component.getColumnResizeMode()); } @Override public void setColumnResizeMode(ColumnResizeMode mode) { component.setColumnResizeMode(WebWrapperUtils.convertToGridColumnResizeMode(mode)); } @Override public SelectionMode getSelectionMode() { return selectionMode; } @Override public void setSelectionMode(SelectionMode selectionMode) { this.selectionMode = selectionMode; switch (selectionMode) { case SINGLE: component.setGridSelectionModel(new CubaSingleSelectionModel<>()); break; case MULTI: component.setGridSelectionModel(new CubaMultiSelectionModel<>()); break; case MULTI_CHECK: component.setGridSelectionModel(new CubaMultiCheckSelectionModel<>()); break; case NONE: component.setSelectionMode(Grid.SelectionMode.NONE); return; } // Every time we change selection mode, the new selection model is set, // so we need to add selection listener again. component.getSelectionModel().addSelectionListener(this::onSelectionChange); } @Override public boolean isMultiSelect() { return SelectionMode.MULTI.equals(selectionMode) || SelectionMode.MULTI_CHECK.equals(selectionMode); } @Nullable @Override public E getSingleSelected() { return component.getSelectionModel() .getFirstSelectedItem() .orElse(null); } @Override public Set<E> getSelected() { return component.getSelectedItems(); } @Override public void setSelected(@Nullable E item) { if (SelectionMode.NONE.equals(getSelectionMode())) { return; } if (item == null) { component.deselectAll(); } else { setSelected(Collections.singletonList(item)); } } @Override public void setSelected(Collection<E> items) { DataGridItems<E> dataGridItems = getDataGridItemsNN(); for (E item : items) { if (!dataGridItems.containsItem(item)) { throw new IllegalStateException("Datasource doesn't contain items"); } } setSelectedItems(items); } @SuppressWarnings("unchecked") protected void setSelectedItems(Collection<E> items) { switch (selectionMode) { case SINGLE: if (items.size() > 0) { E item = items.iterator().next(); component.getSelectionModel().select(item); } else { component.deselectAll(); } break; case MULTI: case MULTI_CHECK: component.deselectAll(); ((SelectionModel.Multi) component.getSelectionModel()).selectItems(items.toArray()); break; default: throw new UnsupportedOperationException("Unsupported selection mode"); } } @Override public void selectAll() { if (isMultiSelect()) { ((SelectionModel.Multi) component.getSelectionModel()).selectAll(); } } @Override public void deselect(E item) { checkNotNullArgument(item); component.deselect(item); } @Override public void deselectAll() { component.deselectAll(); } @Override public void sort(String columnId, SortDirection direction) { ColumnImpl<E> column = (ColumnImpl<E>) getColumnNN(columnId); component.sort(column.getGridColumn(), WebWrapperUtils.convertToGridSortDirection(direction)); } @Override public List<SortOrder> getSortOrder() { return convertToDataGridSortOrder(component.getSortOrder()); } protected List<SortOrder> convertToDataGridSortOrder(List<GridSortOrder<E>> gridSortOrder) { if (CollectionUtils.isEmpty(gridSortOrder)) { return Collections.emptyList(); } return gridSortOrder.stream() .map(sortOrder -> { Column column = getColumnByGridColumn(sortOrder.getSorted()); return new SortOrder(column != null ? column.getId() : null, WebWrapperUtils.convertToDataGridSortDirection(sortOrder.getDirection())); }) .collect(Collectors.toList()); } @Override public void addAction(Action action) { int index = findActionById(actionList, action.getId()); if (index < 0) { index = actionList.size(); } addAction(action, index); } @Override public void addAction(Action action, int index) { checkNotNullArgument(action, "Action must be non null"); int oldIndex = findActionById(actionList, action.getId()); if (oldIndex >= 0) { removeAction(actionList.get(oldIndex)); if (index > oldIndex) { index--; } } if (StringUtils.isNotEmpty(action.getCaption())) { ActionMenuItemWrapper menuItemWrapper = createContextMenuItem(action); menuItemWrapper.setAction(action); contextMenuItems.add(menuItemWrapper); } actionList.add(index, action); shortcutsDelegate.addAction(null, action); attachAction(action); actionsPermissions.apply(action); } protected ActionMenuItemWrapper createContextMenuItem(Action action) { MenuItem menuItem = contextMenu.addItem(action.getCaption(), null); menuItem.setStyleName("c-cm-item"); return new ActionMenuItemWrapper(menuItem, showIconsForPopupMenuActions) { @Override public void performAction(Action action) { action.actionPerform(WebAbstractDataGrid.this); } }; } protected void attachAction(Action action) { if (action instanceof Action.HasTarget) { ((Action.HasTarget) action).setTarget(this); } action.refreshState(); } @Override public void removeAction(@Nullable Action action) { if (actionList.remove(action)) { ActionMenuItemWrapper menuItemWrapper = null; for (ActionMenuItemWrapper menuItem : contextMenuItems) { if (menuItem.getAction() == action) { menuItemWrapper = menuItem; break; } } if (menuItemWrapper != null) { menuItemWrapper.setAction(null); contextMenu.removeItem(menuItemWrapper.getMenuItem()); } shortcutsDelegate.removeAction(action); } } @Override public void removeAction(@Nullable String id) { Action action = getAction(id); if (action != null) { removeAction(action); } } @Override public void removeAllActions() { for (Action action : actionList.toArray(new Action[0])) { removeAction(action); } } @Override public Collection<Action> getActions() { return Collections.unmodifiableCollection(actionList); } @Nullable @Override public Action getAction(String id) { for (Action action : getActions()) { if (Objects.equals(action.getId(), id)) { return action; } } return null; } @Override public ActionsPermissions getActionsPermissions() { return actionsPermissions; } protected List<Column<E>> getInitialVisibleColumns() { MetaClass metaClass = getEntityDataGridItems().getEntityMetaClass(); return columnsOrder.stream() .filter(column -> { MetaPropertyPath propertyPath = column.getPropertyPath(); return propertyPath == null || security.isEntityAttrReadPermitted(metaClass, propertyPath.toString()); }) .collect(Collectors.toList()); } @Override public Component getComposition() { return componentComposition; } @Override public int getFrozenColumnCount() { return component.getFrozenColumnCount(); } @Override public void setFrozenColumnCount(int numberOfColumns) { component.setFrozenColumnCount(numberOfColumns); } @Override public void scrollTo(E item) { scrollTo(item, ScrollDestination.ANY); } @Override public void scrollTo(E item, ScrollDestination destination) { Preconditions.checkNotNullArgument(item); Preconditions.checkNotNullArgument(destination); DataGridItems<E> dataGridItems = getDataGridItemsNN(); if (!dataGridItems.containsItem(item)) { throw new IllegalArgumentException("Unable to find item in DataGrid"); } int rowIndex = dataGridItems.indexOfItem(item); component.scrollTo(rowIndex, WebWrapperUtils.convertToGridScrollDestination(destination)); } @Override public void scrollToStart() { component.scrollToStart(); } @Override public void scrollToEnd() { component.scrollToEnd(); } @Override public void repaint() { component.repaint(); } protected boolean canBeSorted(@Nullable DataGridItems<E> dataGridItems) { return dataGridItems instanceof DataGridItems.Sortable; } @Override public void setDebugId(String id) { super.setDebugId(id); AppUI ui = AppUI.getCurrent(); if (id != null && ui != null) { componentComposition.setId(ui.getTestIdManager().getTestId(id + "_composition")); } } @Override public void setId(String id) { super.setId(id); AppUI ui = AppUI.getCurrent(); if (id != null && ui != null && ui.isTestMode()) { componentComposition.setCubaId(id + "_composition"); } } @Override public void setStyleName(String name) { super.setStyleName(name); internalStyles.forEach(internalStyle -> componentComposition.addStyleName(internalStyle)); } @Override public ButtonsPanel getButtonsPanel() { return buttonsPanel; } @Override public void setButtonsPanel(ButtonsPanel panel) { if (buttonsPanel != null && topPanel != null) { topPanel.removeComponent(WebComponentsHelper.unwrap(buttonsPanel)); buttonsPanel.setParent(null); } buttonsPanel = panel; if (panel != null) { if (panel.getParent() != null && panel.getParent() != this) { throw new IllegalStateException("Component already has parent"); } if (topPanel == null) { topPanel = createTopPanel(); componentComposition.addComponentAsFirst(topPanel); } topPanel.addComponent(WebComponentsHelper.unwrap(panel)); if (panel instanceof VisibilityChangeNotifier) { ((VisibilityChangeNotifier) panel).addVisibilityChangeListener(event -> updateCompositionStylesTopPanelVisible() ); } panel.setParent(this); } updateCompositionStylesTopPanelVisible(); } @Override public RowsCount getRowsCount() { return rowsCount; } @Override public void setRowsCount(RowsCount rowsCount) { if (this.rowsCount != null && topPanel != null) { topPanel.removeComponent(WebComponentsHelper.unwrap(this.rowsCount)); this.rowsCount.setParent(null); } this.rowsCount = rowsCount; if (rowsCount != null) { if (rowsCount.getParent() != null && rowsCount.getParent() != this) { throw new IllegalStateException("Component already has parent"); } if (topPanel == null) { topPanel = createTopPanel(); componentComposition.addComponentAsFirst(topPanel); } Component rc = WebComponentsHelper.unwrap(rowsCount); topPanel.addComponent(rc); if (rowsCount instanceof VisibilityChangeNotifier) { ((VisibilityChangeNotifier) rowsCount).addVisibilityChangeListener(event -> updateCompositionStylesTopPanelVisible() ); } } updateCompositionStylesTopPanelVisible(); } protected HorizontalLayout createTopPanel() { HorizontalLayout topPanel = new HorizontalLayout(); topPanel.setMargin(false); topPanel.setSpacing(false); topPanel.setStyleName("c-data-grid-top"); return topPanel; } // if buttons panel becomes hidden we need to set top panel height to 0 protected void updateCompositionStylesTopPanelVisible() { if (topPanel != null) { boolean hasChildren = topPanel.getComponentCount() > 0; boolean anyChildVisible = false; for (Component childComponent : topPanel) { if (childComponent.isVisible()) { anyChildVisible = true; break; } } boolean topPanelVisible = hasChildren && anyChildVisible; if (!topPanelVisible) { componentComposition.removeStyleName(HAS_TOP_PANEL_STYLE_NAME); internalStyles.remove(HAS_TOP_PANEL_STYLE_NAME); } else { componentComposition.addStyleName(HAS_TOP_PANEL_STYLE_NAME); if (!internalStyles.contains(HAS_TOP_PANEL_STYLE_NAME)) { internalStyles.add(HAS_TOP_PANEL_STYLE_NAME); } } } } @Override public Action getEnterPressAction() { return enterPressAction; } @Override public void setEnterPressAction(Action action) { enterPressAction = action; } @Override public Action getItemClickAction() { return itemClickAction; } @Override public void setItemClickAction(Action action) { if (itemClickAction != null) { removeAction(itemClickAction); } itemClickAction = action; if (!getActions().contains(action)) { addAction(action); } } @Override public void applySettings(Element element) { if (!isSettingsEnabled()) { return; } if (defaultSettings == null) { defaultSettings = DocumentHelper.createDocument(); defaultSettings.setRootElement(defaultSettings.addElement("presentation")); // init default settings saveSettings(defaultSettings.getRootElement()); } Element columnsElem = element.element("columns"); if (columnsElem != null) { List<Column<E>> modelColumns = getVisibleColumns(); List<String> modelIds = modelColumns.stream() .map(String::valueOf) .collect(Collectors.toList()); List<String> loadedIds = columnsElem.elements("columns").stream() .map(colElem -> colElem.attributeValue("id")) .collect(Collectors.toList()); if (CollectionUtils.isEqualCollection(modelIds, loadedIds)) { applyColumnSettings(element, modelColumns); } } } public void applyDataLoadingSettings(Element element) { if (!isSettingsEnabled()) { return; } if (isSortable() && isApplyDataLoadingSettings()) { Element columnsElem = element.element("columns"); if (columnsElem != null) { String sortColumnId = columnsElem.attributeValue("sortColumnId"); if (!StringUtils.isEmpty(sortColumnId)) { Grid.Column<E, ?> column = component.getColumn(sortColumnId); if (column != null) { if (getItems() instanceof DataGridItems.Sortable) { ((DataGridItems.Sortable<E>) getItems()).suppressSorting(); } try { component.clearSortOrder(); String sortDirection = columnsElem.attributeValue("sortDirection"); if (StringUtils.isNotEmpty(sortDirection)) { List<GridSortOrder<E>> sortOrders = Collections.singletonList(new GridSortOrder<>(column, com.vaadin.shared.data.sort.SortDirection.valueOf(sortDirection)) ); component.setSortOrder(sortOrders); } } finally { if (getItems() instanceof DataGridItems.Sortable) { ((DataGridItems.Sortable<E>) getItems()).enableSorting(); } } } } } } } protected void applyColumnSettings(Element element, Collection<Column<E>> oldColumns) { Element columnsElem = element.element("columns"); List<Column<E>> newColumns = new ArrayList<>(); // add columns from saved settings for (Element colElem : columnsElem.elements("columns")) { for (Column<E> column : oldColumns) { if (column.getId().equals(colElem.attributeValue("id"))) { newColumns.add(column); String width = colElem.attributeValue("width"); if (width != null) { column.setWidth(Double.parseDouble(width)); } else { column.setWidthAuto(); } String collapsed = colElem.attributeValue("collapsed"); if (collapsed != null && component.isColumnReorderingAllowed()) { column.setCollapsed(Boolean.parseBoolean(collapsed)); } break; } } } // add columns not saved in settings (perhaps new) for (Column<E> column : oldColumns) { if (!newColumns.contains(column)) { newColumns.add(column); } } // if the data grid contains only one column, always show it if (newColumns.size() == 1) { newColumns.get(0).setCollapsed(false); } // We don't save settings for columns hidden by security permissions, // so we need to return them back to they initial positions columnsOrder = restoreColumnsOrder(newColumns); component.setColumnOrder(newColumns.stream() .map(Column::getId) .toArray(String[]::new)); if (isSortable() && !isApplyDataLoadingSettings()) { // apply sorting component.clearSortOrder(); String sortColumnId = columnsElem.attributeValue("sortColumnId"); if (!StringUtils.isEmpty(sortColumnId)) { Grid.Column<E, ?> column = component.getColumn(sortColumnId); if (column != null) { String sortDirection = columnsElem.attributeValue("sortDirection"); if (StringUtils.isNotEmpty(sortDirection)) { List<GridSortOrder<E>> sortOrders = Collections.singletonList(new GridSortOrder<>(column, com.vaadin.shared.data.sort.SortDirection.valueOf(sortDirection)) ); component.setSortOrder(sortOrders); } } } } } protected boolean isApplyDataLoadingSettings() { DataGridItems<E> tableItems = getItems(); if (tableItems instanceof ContainerDataUnit) { CollectionContainer container = ((ContainerDataUnit) tableItems).getContainer(); return container instanceof HasLoader && ((HasLoader) container).getLoader() instanceof CollectionLoader; } return false; } @Override public boolean saveSettings(Element element) { if (!isSettingsEnabled()) { return false; } Element columnsElem = element.element("columns"); String sortColumnId = null; String sortDirection = null; if (columnsElem != null) { sortColumnId = columnsElem.attributeValue("sortColumnId"); sortDirection = columnsElem.attributeValue("sortDirection"); } boolean commonSettingsChanged = isCommonDataGridSettingsChanged(columnsElem); boolean sortChanged = isSortPropertySettingsChanged(sortColumnId, sortDirection); boolean settingsChanged = commonSettingsChanged || sortChanged; if (settingsChanged) { if (columnsElem != null) { element.remove(columnsElem); } columnsElem = element.addElement("columns"); List<Column<E>> visibleColumns = getVisibleColumns(); for (Column<E> column : visibleColumns) { Element colElem = columnsElem.addElement("columns"); colElem.addAttribute("id", column.toString()); double width = column.getWidth(); if (width > -1) { colElem.addAttribute("width", String.valueOf(width)); } colElem.addAttribute("collapsed", Boolean.toString(column.isCollapsed())); } List<GridSortOrder<E>> sortOrders = component.getSortOrder(); if (!sortOrders.isEmpty()) { GridSortOrder<E> sortOrder = sortOrders.get(0); columnsElem.addAttribute("sortColumnId", sortOrder.getSorted().getId()); columnsElem.addAttribute("sortDirection", sortOrder.getDirection().toString()); } } return settingsChanged; } protected boolean isCommonDataGridSettingsChanged(Element columnsElem) { if (columnsElem == null) { if (defaultSettings != null) { columnsElem = defaultSettings.getRootElement().element("columns"); if (columnsElem == null) { return true; } } else { return false; } } List<Element> settingsColumnList = columnsElem.elements("columns"); List<Column<E>> visibleColumns = getVisibleColumns(); if (settingsColumnList.size() != visibleColumns.size()) { return true; } for (int i = 0; i < visibleColumns.size(); i++) { Object columnId = visibleColumns.get(i).getId(); Element settingsColumn = settingsColumnList.get(i); String settingsColumnId = settingsColumn.attributeValue("id"); if (columnId.toString().equals(settingsColumnId)) { double columnWidth = visibleColumns.get(i).getWidth(); String settingsColumnWidth = settingsColumn.attributeValue("width"); double settingColumnWidth = settingsColumnWidth == null ? -1 : Double.parseDouble(settingsColumnWidth); if (columnWidth != settingColumnWidth) { return true; } boolean columnCollapsed = visibleColumns.get(i).isCollapsed(); boolean settingsColumnCollapsed = Boolean.parseBoolean(settingsColumn.attributeValue("collapsed")); if (columnCollapsed != settingsColumnCollapsed) { return true; } } else { return true; } } return false; } protected boolean isSortPropertySettingsChanged(String settingsSortColumnId, String settingsSortDirection) { List<GridSortOrder<E>> sortOrders = component.getSortOrder(); String columnId = null; String sortDirection = null; if (!sortOrders.isEmpty()) { GridSortOrder<E> sortOrder = sortOrders.get(0); columnId = sortOrder.getSorted().getId(); sortDirection = sortOrder.getDirection().toString(); } if (!Objects.equals(columnId, settingsSortColumnId) || !Objects.equals(sortDirection, settingsSortDirection)) { return true; } return false; } @Nullable protected ColumnImpl<E> getColumnByGridColumn(Grid.Column<E, ?> gridColumn) { for (Column<E> column : getColumns()) { ColumnImpl<E> columnImpl = (ColumnImpl<E>) column; if (columnImpl.getGridColumn() == gridColumn) { return columnImpl; } } return null; } @Nullable protected Column<E> getColumnById(Object id) { for (Column<E> column : getColumns()) { String columnId = column.getId(); if (Objects.equals(columnId, id)) { return column; } } return null; } @Override public boolean isSettingsEnabled() { return settingsEnabled; } @Override public void setSettingsEnabled(boolean settingsEnabled) { this.settingsEnabled = settingsEnabled; } @Override public void addRowStyleProvider(Function<? super E, String> styleProvider) { if (this.rowStyleProviders == null) { this.rowStyleProviders = new LinkedList<>(); } if (!this.rowStyleProviders.contains(styleProvider)) { this.rowStyleProviders.add(styleProvider); repaint(); } } @Override public void removeRowStyleProvider(Function<? super E, String> styleProvider) { if (this.rowStyleProviders != null) { if (this.rowStyleProviders.remove(styleProvider)) { repaint(); } } } @Override public void addCellStyleProvider(CellStyleProvider<? super E> styleProvider) { if (this.cellStyleProviders == null) { this.cellStyleProviders = new LinkedList<>(); } if (!this.cellStyleProviders.contains(styleProvider)) { this.cellStyleProviders.add(styleProvider); repaint(); } } @Override public void removeCellStyleProvider(CellStyleProvider<? super E> styleProvider) { if (this.cellStyleProviders != null) { if (this.cellStyleProviders.remove(styleProvider)) { repaint(); } } } @SuppressWarnings("unchecked") @Override public CellDescriptionProvider<E> getCellDescriptionProvider() { return (CellDescriptionProvider<E>) cellDescriptionProvider; } @Override public void setCellDescriptionProvider(CellDescriptionProvider<? super E> provider) { this.cellDescriptionProvider = provider; repaint(); } @SuppressWarnings("unchecked") @Override public Function<E, String> getRowDescriptionProvider() { return (Function<E, String>) rowDescriptionProvider; } @Override public void setRowDescriptionProvider(Function<? super E, String> provider) { setRowDescriptionProvider(provider, ContentMode.PREFORMATTED); } @Override public void setRowDescriptionProvider(Function<? super E, String> provider, ContentMode contentMode) { this.rowDescriptionProvider = provider; if (provider != null) { component.setDescriptionGenerator(this::getRowDescription, WebWrapperUtils.toVaadinContentMode(contentMode)); } else { component.setDescriptionGenerator(null); } } protected String getRowDescription(E item) { return rowDescriptionProvider.apply(item); } @Override public Column<E> addGeneratedColumn(String columnId, ColumnGenerator<E, ?> generator) { return addGeneratedColumn(columnId, generator, columnsOrder.size()); } @SuppressWarnings("unchecked") @Override public Column<E> addGeneratedColumn(String columnId, GenericColumnGenerator<E, ?> generator) { Column<E> column = getColumn(columnId); if (column == null) { throw new DevelopmentException("Unable to set ColumnGenerator for non-existing column: " + columnId); } Class<? extends Renderer> rendererType = null; Renderer renderer = column.getRenderer(); if (renderer != null) { Class<?>[] rendererInterfaces = renderer.getClass().getInterfaces(); rendererType = (Class<? extends Renderer>) Arrays.stream(rendererInterfaces) .filter(Renderer.class::isAssignableFrom) .findFirst() .orElseThrow(() -> new DevelopmentException( "Renderer should be specified explicitly for generated column: " + columnId)); } Column<E> generatedColumn = addGeneratedColumn(columnId, new ColumnGenerator<E, Object>() { @Override public Object getValue(ColumnGeneratorEvent<E> event) { return generator.getValue(event); } @Override public Class<Object> getType() { return column.getGeneratedType(); } }); if (renderer != null) { generatedColumn.setRenderer(createRenderer(rendererType)); } return column; } @Override public Column<E> addGeneratedColumn(String columnId, ColumnGenerator<E, ?> generator, int index) { checkNotNullArgument(columnId, "columnId is null"); checkNotNullArgument(generator, "generator is null for column id '%s'", columnId); Column<E> existingColumn = getColumn(columnId); if (existingColumn != null) { index = columnsOrder.indexOf(existingColumn); removeColumn(existingColumn); } Grid.Column<E, Object> generatedColumn = component.addColumn(createGeneratedColumnValueProvider(columnId, generator)); // Pass propertyPath from the existing column to support sorting ColumnImpl<E> column = new ColumnImpl<>(columnId, existingColumn != null ? existingColumn.getPropertyPath() : null, generator.getType(), this); if (existingColumn != null) { copyColumnProperties(column, existingColumn); } else { column.setCaption(columnId); } column.setGenerated(true); columns.put(column.getId(), column); columnsOrder.add(index, column); columnGenerators.put(column.getId(), generator); setupGridColumnProperties(generatedColumn, column); component.setColumnOrder(getColumnOrder()); return column; } protected ValueProvider<E, Object> createGeneratedColumnValueProvider(String columnId, ColumnGenerator<E, ?> generator) { return (ValueProvider<E, Object>) item -> { ColumnGeneratorEvent<E> event = new ColumnGeneratorEvent<>(WebAbstractDataGrid.this, item, columnId, this::createInstanceContainer); return generator.getValue(event); }; } @Override public ColumnGenerator<E, ?> getColumnGenerator(String columnId) { return columnGenerators.get(columnId); } protected void copyColumnProperties(Column<E> column, Column<E> existingColumn) { column.setCaption(existingColumn.getCaption()); column.setVisible(existingColumn.isVisible()); column.setCollapsed(existingColumn.isCollapsed()); column.setCollapsible(existingColumn.isCollapsible()); column.setCollapsingToggleCaption(existingColumn.getCollapsingToggleCaption()); column.setMinimumWidth(existingColumn.getMinimumWidth()); column.setMaximumWidth(existingColumn.getMaximumWidth()); column.setWidth(existingColumn.getWidth()); column.setExpandRatio(existingColumn.getExpandRatio()); column.setResizable(existingColumn.isResizable()); column.setFormatter(existingColumn.getFormatter()); column.setStyleProvider(existingColumn.getStyleProvider()); column.setDescriptionProvider(existingColumn.getDescriptionProvider(), ((ColumnImpl) existingColumn).getDescriptionContentMode()); // If the new column has propertyPath and it equals to propertyPath // of the existing column, then coping the Sortable state, as it seems // that the new column corresponds to the generated column that is // related to the existing Entity attribute, so that this column can be sortable if (column.getPropertyPath() != null && column.getPropertyPath().equals(existingColumn.getPropertyPath())) { column.setSortable(existingColumn.isSortable()); } } @Override public <T extends Renderer> T createRenderer(Class<T> type) { Class<? extends Renderer> rendererClass = rendererClasses.get(type); if (rendererClass == null) { throw new IllegalArgumentException( String.format("Can't find renderer class for '%s'", type.getTypeName())); } Constructor<? extends Renderer> constructor; try { constructor = rendererClass.getConstructor(); } catch (NoSuchMethodException e) { throw new RuntimeException(String.format("Error creating the '%s' renderer instance", type.getTypeName()), e); } try { Renderer instance = constructor.newInstance(); autowireContext(instance); return type.cast(instance); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(String.format("Error creating the '%s' renderer instance", type.getTypeName()), e); } } protected void autowireContext(Renderer instance) { AutowireCapableBeanFactory autowireBeanFactory = applicationContext.getAutowireCapableBeanFactory(); autowireBeanFactory.autowireBean(instance); if (instance instanceof ApplicationContextAware) { ((ApplicationContextAware) instance).setApplicationContext(applicationContext); } if (instance instanceof InitializingBean) { try { ((InitializingBean) instance).afterPropertiesSet(); } catch (Exception e) { throw new RuntimeException("Unable to initialize Renderer - calling afterPropertiesSet for " + instance.getClass(), e); } } } @Override public Subscription addColumnCollapsingChangeListener(Consumer<ColumnCollapsingChangeEvent> listener) { if (columnCollapsingChangeListenerRegistration == null) { columnCollapsingChangeListenerRegistration = component.addColumnVisibilityChangeListener(this::onColumnVisibilityChanged); } getEventHub().subscribe(ColumnCollapsingChangeEvent.class, listener); return () -> removeColumnCollapsingChangeListener(listener); } protected void onColumnVisibilityChanged(Grid.ColumnVisibilityChangeEvent e) { // Due to vaadin/framework#11419, // we discard events with UserOriginated == false. if (!e.isUserOriginated()) { return; } //noinspection unchecked ColumnCollapsingChangeEvent event = new ColumnCollapsingChangeEvent(WebAbstractDataGrid.this, getColumnByGridColumn((Grid.Column<E, ?>) e.getColumn()), e.isHidden(), e.isUserOriginated()); publish(ColumnCollapsingChangeEvent.class, event); } @Override public void removeColumnCollapsingChangeListener(Consumer<ColumnCollapsingChangeEvent> listener) { unsubscribe(ColumnCollapsingChangeEvent.class, listener); if (!hasSubscriptions(ColumnCollapsingChangeEvent.class) && columnCollapsingChangeListenerRegistration != null) { columnCollapsingChangeListenerRegistration.remove(); columnCollapsingChangeListenerRegistration = null; } } @Override public Subscription addColumnResizeListener(Consumer<ColumnResizeEvent> listener) { if (columnResizeListenerRegistration == null) { columnResizeListenerRegistration = component.addColumnResizeListener(this::onColumnResize); } getEventHub().subscribe(ColumnResizeEvent.class, listener); return () -> removeColumnResizeListener(listener); } protected void onColumnResize(Grid.ColumnResizeEvent e) { //noinspection unchecked ColumnResizeEvent event = new ColumnResizeEvent(WebAbstractDataGrid.this, getColumnByGridColumn((Grid.Column<E, ?>) e.getColumn()), e.isUserOriginated()); publish(ColumnResizeEvent.class, event); } @Override public void removeColumnResizeListener(Consumer<ColumnResizeEvent> listener) { unsubscribe(ColumnResizeEvent.class, listener); if (!hasSubscriptions(ColumnResizeEvent.class) && columnResizeListenerRegistration != null) { columnResizeListenerRegistration.remove(); columnResizeListenerRegistration = null; } } @Override public Subscription addSortListener(Consumer<SortEvent> listener) { return getEventHub().subscribe(SortEvent.class, listener); } @Override public void removeSortListener(Consumer<SortEvent> listener) { unsubscribe(SortEvent.class, listener); } @Override public Subscription addColumnReorderListener(Consumer<ColumnReorderEvent> listener) { return getEventHub().subscribe(ColumnReorderEvent.class, listener); } @Override public void removeColumnReorderListener(Consumer<ColumnReorderEvent> listener) { unsubscribe(ColumnReorderEvent.class, listener); } @SuppressWarnings("unchecked") @Override public Subscription addSelectionListener(Consumer<SelectionEvent<E>> listener) { return getEventHub().subscribe(SelectionEvent.class, (Consumer) listener); } @SuppressWarnings("unchecked") @Override public void removeSelectionListener(Consumer<SelectionEvent<E>> listener) { unsubscribe(SelectionEvent.class, (Consumer) listener); } @SuppressWarnings("unchecked") @Override public Subscription addItemClickListener(Consumer<ItemClickEvent<E>> listener) { return getEventHub().subscribe(ItemClickEvent.class, (Consumer) listener); } @SuppressWarnings("unchecked") @Override public void removeItemClickListener(Consumer<ItemClickEvent<E>> listener) { unsubscribe(ItemClickEvent.class, (Consumer) listener); } @Override public Subscription addContextClickListener(Consumer<ContextClickEvent> listener) { if (contextClickListenerRegistration == null) { contextClickListenerRegistration = component.addContextClickListener(this::onContextClick); } return getEventHub().subscribe(ContextClickEvent.class, listener); } protected void onContextClick(com.vaadin.event.ContextClickEvent e) { MouseEventDetails mouseEventDetails = WebWrapperUtils.toMouseEventDetails(e); ContextClickEvent event = new ContextClickEvent(WebAbstractDataGrid.this, mouseEventDetails); publish(ContextClickEvent.class, event); } @Override public void removeContextClickListener(Consumer<ContextClickEvent> listener) { unsubscribe(ContextClickEvent.class, listener); if (!hasSubscriptions(ContextClickEvent.class) && contextClickListenerRegistration != null) { contextClickListenerRegistration.remove(); contextClickListenerRegistration = null; } } @SuppressWarnings("unchecked") @Override public Subscription addLookupValueChangeListener(Consumer<LookupSelectionChangeEvent<E>> listener) { return getEventHub().subscribe(LookupSelectionChangeEvent.class, (Consumer) listener); } @SuppressWarnings("unchecked") @Override public void removeLookupValueChangeListener(Consumer<LookupSelectionChangeEvent<E>> listener) { unsubscribe(LookupSelectionChangeEvent.class, (Consumer) listener); } @Override public HeaderRow getHeaderRow(int index) { return getHeaderRowByGridRow(component.getHeaderRow(index)); } @Nullable protected HeaderRow getHeaderRowByGridRow(com.vaadin.ui.components.grid.HeaderRow gridRow) { for (HeaderRow headerRow : headerRows) { if (((HeaderRowImpl) headerRow).getGridRow() == gridRow) { return headerRow; } } return null; } @Override public HeaderRow appendHeaderRow() { com.vaadin.ui.components.grid.HeaderRow headerRow = component.appendHeaderRow(); return addHeaderRowInternal(headerRow); } @Override public HeaderRow prependHeaderRow() { com.vaadin.ui.components.grid.HeaderRow headerRow = component.prependHeaderRow(); return addHeaderRowInternal(headerRow); } @Override public HeaderRow addHeaderRowAt(int index) { com.vaadin.ui.components.grid.HeaderRow headerRow = component.addHeaderRowAt(index); return addHeaderRowInternal(headerRow); } protected HeaderRow addHeaderRowInternal(com.vaadin.ui.components.grid.HeaderRow headerRow) { HeaderRowImpl rowImpl = new HeaderRowImpl(this, (Header.Row) headerRow); headerRows.add(rowImpl); return rowImpl; } @Override public void removeHeaderRow(HeaderRow headerRow) { if (headerRow == null || !headerRows.contains(headerRow)) { return; } component.removeHeaderRow(((HeaderRowImpl) headerRow).getGridRow()); headerRows.remove(headerRow); } @Override public void removeHeaderRow(int index) { HeaderRow headerRow = getHeaderRow(index); removeHeaderRow(headerRow); } @Override public HeaderRow getDefaultHeaderRow() { return getHeaderRowByGridRow(component.getDefaultHeaderRow()); } @Override public void setDefaultHeaderRow(HeaderRow headerRow) { component.setDefaultHeaderRow(((HeaderRowImpl) headerRow).getGridRow()); } @Override public int getHeaderRowCount() { return component.getHeaderRowCount(); } @Override public FooterRow getFooterRow(int index) { return getFooterRowByGridRow(component.getFooterRow(index)); } @Nullable protected FooterRow getFooterRowByGridRow(com.vaadin.ui.components.grid.FooterRow gridRow) { for (FooterRow footerRow : footerRows) { if (((FooterRowImpl) footerRow).getGridRow() == gridRow) { return footerRow; } } return null; } @Override public FooterRow appendFooterRow() { com.vaadin.ui.components.grid.FooterRow footerRow = component.appendFooterRow(); return addFooterRowInternal(footerRow); } @Override public FooterRow prependFooterRow() { com.vaadin.ui.components.grid.FooterRow footerRow = component.prependFooterRow(); return addFooterRowInternal(footerRow); } @Override public FooterRow addFooterRowAt(int index) { com.vaadin.ui.components.grid.FooterRow footerRow = component.addFooterRowAt(index); return addFooterRowInternal(footerRow); } protected FooterRow addFooterRowInternal(com.vaadin.ui.components.grid.FooterRow footerRow) { FooterRowImpl rowImpl = new FooterRowImpl(this, (Footer.Row) footerRow); footerRows.add(rowImpl); return rowImpl; } @Override public void removeFooterRow(FooterRow footerRow) { if (footerRow == null || !footerRows.contains(footerRow)) { return; } component.removeFooterRow(((FooterRowImpl) footerRow).getGridRow()); footerRows.remove(footerRow); } @Override public void removeFooterRow(int index) { FooterRow footerRow = getFooterRow(index); removeFooterRow(footerRow); } @Override public int getFooterRowCount() { return component.getFooterRowCount(); } @Nullable @Override public DetailsGenerator<E> getDetailsGenerator() { return detailsGenerator; } @Override public void setDetailsGenerator(DetailsGenerator<E> detailsGenerator) { this.detailsGenerator = detailsGenerator; component.setDetailsGenerator(detailsGenerator != null ? this::getRowDetails : null); } protected Component getRowDetails(E item) { com.haulmont.cuba.gui.components.Component component = detailsGenerator.getDetails(item); return component != null ? component.unwrapComposition(Component.class) : null; } @Override public boolean isDetailsVisible(E entity) { return component.isDetailsVisible(entity); } @Override public void setDetailsVisible(E entity, boolean visible) { component.setDetailsVisible(entity, visible); } @Override public int getTabIndex() { return component.getTabIndex(); } @Override public void setTabIndex(int tabIndex) { component.setTabIndex(tabIndex); } @Override public void setEmptyStateMessage(String message) { component.setEmptyStateMessage(message); showEmptyStateIfPossible(); } @Override public String getEmptyStateMessage() { return component.getEmptyStateMessage(); } @Override public void setEmptyStateLinkMessage(String linkMessage) { component.setEmptyStateLinkMessage(linkMessage); showEmptyStateIfPossible(); } @Override public String getEmptyStateLinkMessage() { return component.getEmptyStateLinkMessage(); } @Override public void setEmptyStateLinkClickHandler(Consumer<EmptyStateClickEvent<E>> handler) { this.emptyStateClickEventHandler = handler; } @Override public Consumer<EmptyStateClickEvent<E>> getEmptyStateLinkClickHandler() { return emptyStateClickEventHandler; } protected void enableCrossFieldValidationHandling(boolean enable) { if (isEditorEnabled()) { ((CubaEditorImpl<E>) component.getEditor()).setCrossFieldValidationHandler( enable ? this::validateCrossFieldRules : null); } } protected String validateCrossFieldRules(Map<String, Object> properties) { E item = getEditedItem(); if (item == null) { return null; } // set changed values from editor to copied entity E copiedItem = metadataTools.deepCopy(item); for (Map.Entry<String, Object> property : properties.entrySet()) { copiedItem.setValue(property.getKey(), property.getValue()); } // validate copy ValidationErrors errors = screenValidation.validateCrossFieldRules( getFrame() != null ? getFrame().getFrameOwner() : null, copiedItem); if (errors.isEmpty()) { return null; } StringBuilder errorMessage = new StringBuilder(); for (ValidationErrors.Item error : errors.getAll()) { errorMessage.append(error.description).append("\n"); } return errorMessage.toString(); } @Nullable protected String getGeneratedRowStyle(E item) { if (rowStyleProviders == null) { return null; } StringBuilder joinedStyle = null; for (Function<? super E, String> styleProvider : rowStyleProviders) { String styleName = styleProvider.apply(item); if (styleName != null) { if (joinedStyle == null) { joinedStyle = new StringBuilder(styleName); } else { joinedStyle.append(" ").append(styleName); } } } return joinedStyle != null ? joinedStyle.toString() : null; } protected void initEmptyState() { component.setEmptyStateLinkClickHandler(() -> { if (emptyStateClickEventHandler != null) { emptyStateClickEventHandler.accept(new EmptyStateClickEvent<>(this)); } }); if (dataBinding != null) { dataBinding.addDataProviderListener(event -> showEmptyStateIfPossible()); } showEmptyStateIfPossible(); } protected void showEmptyStateIfPossible() { boolean emptyItems = (dataBinding != null && dataBinding.getDataGridItems().size() == 0) || getItems() == null; boolean notEmptyMessages = !Strings.isNullOrEmpty(component.getEmptyStateMessage()) || !Strings.isNullOrEmpty(component.getEmptyStateLinkMessage()); component.setShowEmptyState(emptyItems && notEmptyMessages); } protected class CellStyleGeneratorAdapter<T extends E> implements StyleGenerator<T> { protected Column<T> column; public CellStyleGeneratorAdapter(Column<T> column) { this.column = column; } @Override public String apply(T item) { //noinspection unchecked return getGeneratedCellStyle(item, (Column<E>) column); } } @Nullable protected String getGeneratedCellStyle(E item, Column<E> column) { StringBuilder joinedStyle = null; if (column.getStyleProvider() != null) { String styleName = column.getStyleProvider().apply(item); if (styleName != null) { joinedStyle = new StringBuilder(styleName); } } if (cellStyleProviders != null) { for (CellStyleProvider<? super E> styleProvider : cellStyleProviders) { String styleName = styleProvider.getStyleName(item, column.getId()); if (styleName != null) { if (joinedStyle == null) { joinedStyle = new StringBuilder(styleName); } else { joinedStyle.append(" ").append(styleName); } } } } return joinedStyle != null ? joinedStyle.toString() : null; } protected class CellDescriptionGeneratorAdapter<T extends E> implements DescriptionGenerator<T> { protected Column<T> column; public CellDescriptionGeneratorAdapter(Column<T> column) { this.column = column; } @Override public String apply(T item) { //noinspection unchecked return getGeneratedCellDescription(item, (Column<E>) column); } } protected String getGeneratedCellDescription(E item, Column<E> column) { if (column.getDescriptionProvider() != null) { return column.getDescriptionProvider().apply(item); } if (cellDescriptionProvider != null) { return cellDescriptionProvider.getDescription(item, column.getId()); } return null; } public static abstract class AbstractRenderer<T extends Entity, V> implements RendererWrapper<V> { protected com.vaadin.ui.renderers.Renderer<V> renderer; protected WebAbstractDataGrid<?, T> dataGrid; protected String nullRepresentation; protected AbstractRenderer() { } protected AbstractRenderer(String nullRepresentation) { this.nullRepresentation = nullRepresentation; } @Override public com.vaadin.ui.renderers.Renderer<V> getImplementation() { if (renderer == null) { renderer = createImplementation(); } return renderer; } protected abstract com.vaadin.ui.renderers.Renderer<V> createImplementation(); public ValueProvider<?, V> getPresentationValueProvider() { // Some renderers need specific presentation ValueProvider to be set at the same time // (see com.vaadin.ui.Grid.Column.setRenderer(com.vaadin.data.ValueProvider<V,P>, // com.vaadin.ui.renderers.Renderer<? super P>)). // Default `null` means do not use any presentation ValueProvider return null; } @Override public void resetImplementation() { renderer = null; } protected WebAbstractDataGrid<?, T> getDataGrid() { return dataGrid; } protected void setDataGrid(WebAbstractDataGrid<?, T> dataGrid) { this.dataGrid = dataGrid; } protected String getNullRepresentation() { return nullRepresentation; } protected void setNullRepresentation(String nullRepresentation) { checkRendererNotSet(); this.nullRepresentation = nullRepresentation; } protected Column<T> getColumnByGridColumn(Grid.Column<T, ?> column) { return dataGrid.getColumnByGridColumn(column); } protected void checkRendererNotSet() { if (renderer != null) { throw new IllegalStateException("Renderer parameters cannot be changed after it is set to a column"); } } } protected static class ColumnImpl<E extends Entity> implements Column<E>, HasXmlDescriptor { protected final String id; protected final MetaPropertyPath propertyPath; protected String caption; protected String collapsingToggleCaption; protected double width; protected double minWidth; protected double maxWidth; protected int expandRatio; protected boolean collapsed; protected boolean visible; protected boolean collapsible; protected boolean sortable; protected boolean resizable; protected boolean editable; protected boolean generated; protected Function<?, String> formatter; protected AbstractRenderer<E, ?> renderer; protected Function presentationProvider; protected Converter converter; protected Function<? super E, String> styleProvider; protected Function<? super E, String> descriptionProvider; protected ContentMode descriptionContentMode = ContentMode.PREFORMATTED; protected final Class type; protected Class generatedType; protected Element element; protected WebAbstractDataGrid<?, E> owner; protected Grid.Column<E, ?> gridColumn; protected ColumnEditorFieldGenerator fieldGenerator; protected Function<EditorFieldGenerationContext<E>, Field<?>> generator; public ColumnImpl(String id, @Nullable MetaPropertyPath propertyPath, WebAbstractDataGrid<?, E> owner) { this(id, propertyPath, propertyPath != null ? propertyPath.getRangeJavaClass() : String.class, owner); } public ColumnImpl(String id, Class type, WebAbstractDataGrid<?, E> owner) { this(id, null, type, owner); } protected ColumnImpl(String id, @Nullable MetaPropertyPath propertyPath, Class type, WebAbstractDataGrid<?, E> owner) { this.id = id; this.propertyPath = propertyPath; this.type = type; this.owner = owner; setupDefaults(); } protected void setupDefaults() { resizable = true; editable = true; generated = false; // the generated properties are not normally sortable, // but require special handling to enable sorting. // for now sorting for generated properties is disabled sortable = propertyPath != null && owner.isSortable(); collapsible = owner.isColumnsCollapsingAllowed(); collapsed = false; visible = true; ThemeConstants theme = App.getInstance().getThemeConstants(); width = theme.getInt("cuba.web.DataGrid.defaultColumnWidth", -1); maxWidth = theme.getInt("cuba.web.DataGrid.defaultColumnMaxWidth", -1); minWidth = theme.getInt("cuba.web.DataGrid.defaultColumnMinWidth", 10); expandRatio = theme.getInt("cuba.web.DataGrid.defaultColumnExpandRatio", -1); } @Override public String getId() { if (gridColumn != null) { return gridColumn.getId(); } return id; } @Nullable @Override public MetaPropertyPath getPropertyPath() { return propertyPath; } public Object getPropertyId() { return propertyPath != null ? propertyPath : id; } @Override public String getCaption() { if (gridColumn != null) { return gridColumn.getCaption(); } return caption; } @Override public void setCaption(String caption) { this.caption = caption; if (gridColumn != null) { gridColumn.setCaption(caption); } } @Override public String getCollapsingToggleCaption() { if (gridColumn != null) { return gridColumn.getHidingToggleCaption(); } return collapsingToggleCaption; } @Override public void setCollapsingToggleCaption(String collapsingToggleCaption) { this.collapsingToggleCaption = collapsingToggleCaption; if (gridColumn != null) { gridColumn.setHidingToggleCaption(collapsingToggleCaption); } } @Override public double getWidth() { if (gridColumn != null) { return gridColumn.getWidth(); } return width; } @Override public void setWidth(double width) { this.width = width; if (gridColumn != null) { gridColumn.setWidth(width); } } @Override public boolean isWidthAuto() { if (gridColumn != null) { return gridColumn.isWidthUndefined(); } return width < 0; } @Override public void setWidthAuto() { if (!isWidthAuto()) { width = -1; if (gridColumn != null) { gridColumn.setWidthUndefined(); } } } @Override public int getExpandRatio() { if (gridColumn != null) { return gridColumn.getExpandRatio(); } return expandRatio; } @Override public void setExpandRatio(int expandRatio) { this.expandRatio = expandRatio; if (gridColumn != null) { gridColumn.setExpandRatio(expandRatio); } } @Override public void clearExpandRatio() { setExpandRatio(-1); } @Override public double getMinimumWidth() { if (gridColumn != null) { return gridColumn.getMinimumWidth(); } return minWidth; } @Override public void setMinimumWidth(double pixels) { this.minWidth = pixels; if (gridColumn != null) { gridColumn.setMinimumWidth(pixels); } } @Override public double getMaximumWidth() { if (gridColumn != null) { return gridColumn.getMaximumWidth(); } return maxWidth; } @Override public void setMaximumWidth(double pixels) { this.maxWidth = pixels; if (gridColumn != null) { gridColumn.setMaximumWidth(pixels); } } @Override public boolean isVisible() { return visible; } @Override public void setVisible(boolean visible) { if (this.visible != visible) { this.visible = visible; Grid<E> grid = owner.getComponent(); if (visible) { Grid.Column<E, ?> gridColumn = grid.addColumn(new EntityValueProvider<>(getPropertyPath())); owner.setupGridColumnProperties(gridColumn, this); grid.setColumnOrder(owner.getColumnOrder()); } else { grid.removeColumn(getId()); setGridColumn(null); } } } @Override public boolean isCollapsed() { if (gridColumn != null) { return gridColumn.isHidden(); } return collapsed; } @Override public void setCollapsed(boolean collapsed) { this.collapsed = collapsed; if (gridColumn != null) { gridColumn.setHidden(collapsed); // Due to vaadin/framework#11419, // we explicitly send ColumnCollapsingChangeEvent with UserOriginated == false. ColumnCollapsingChangeEvent event = new ColumnCollapsingChangeEvent(owner, this, collapsed, false); owner.publish(ColumnCollapsingChangeEvent.class, event); } } @Override public boolean isCollapsible() { if (gridColumn != null) { return gridColumn.isHidable(); } return collapsible; } @Override public void setCollapsible(boolean collapsible) { this.collapsible = collapsible; updateCollapsible(); } public void updateCollapsible() { if (gridColumn != null) { gridColumn.setHidable(collapsible && owner.isColumnsCollapsingAllowed()); } } @Override public boolean isSortable() { return sortable; } @Override public void setSortable(boolean sortable) { this.sortable = sortable; updateSortable(); } public void updateSortable() { if (gridColumn != null) { gridColumn.setSortable(this.sortable && owner.isSortable()); } } @Override public boolean isResizable() { if (gridColumn != null) { return gridColumn.isResizable(); } return resizable; } @Override public void setResizable(boolean resizable) { this.resizable = resizable; if (gridColumn != null) { gridColumn.setResizable(resizable); } } @Override public Function getFormatter() { return formatter; } @Override public void setFormatter(Function formatter) { this.formatter = formatter; updateRendererInternal(); } @Nullable protected MetaProperty getMetaProperty() { return getPropertyPath() != null ? getPropertyPath().getMetaProperty() : null; } @Override public Element getXmlDescriptor() { return element; } @Override public void setXmlDescriptor(Element element) { this.element = element; } @Override public Renderer getRenderer() { return renderer; } @Override public void setRenderer(Renderer renderer) { setRenderer(renderer, null); } @Override public void setRenderer(Renderer renderer, Function presentationProvider) { if (renderer == null && this.renderer != null) { this.renderer.resetImplementation(); this.renderer.setDataGrid(null); } //noinspection unchecked this.renderer = (AbstractRenderer) renderer; this.presentationProvider = presentationProvider; if (this.renderer != null) { this.renderer.setDataGrid(owner); } updateRendererInternal(); } @SuppressWarnings({"unchecked"}) protected ValueProvider createPresentationProviderWrapper(Function presentationProvider) { return (ValueProvider) presentationProvider::apply; } @SuppressWarnings("unchecked") protected void updateRendererInternal() { if (gridColumn != null) { com.vaadin.ui.renderers.Renderer vRenderer = renderer != null ? renderer.getImplementation() : owner.getDefaultRenderer(this); // The following priority is used to determine a value provider: // a presentation provider > a converter > a formatter > a renderer's presentation provider > // a value provider that always returns its input argument > a default presentation provider //noinspection RedundantCast ValueProvider vPresentationProvider = presentationProvider != null ? createPresentationProviderWrapper(presentationProvider) : converter != null ? new DataGridConverterBasedValueProvider(converter) : formatter != null ? new FormatterBasedValueProvider(formatter) : renderer != null && renderer.getPresentationValueProvider() != null ? (ValueProvider) renderer.getPresentationValueProvider() : renderer != null // In case renderer != null and there are no other user specified value providers // We use a value provider that always returns its input argument instead of a default // value provider as we want to keep the original value type. ? ValueProvider.identity() : owner.getDefaultPresentationValueProvider(this); gridColumn.setRenderer(vPresentationProvider, vRenderer); owner.repaint(); } } @Override public Function getPresentationProvider() { return presentationProvider; } @Override public Converter<?, ?> getConverter() { return converter; } @Override public void setConverter(Converter<?, ?> converter) { this.converter = converter; updateRendererInternal(); } @Override public Class getType() { return type; } @Override public void setGeneratedType(Class generatedType) { this.generatedType = generatedType; } @Override public Class getGeneratedType() { return generatedType; } public boolean isGenerated() { return generated; } public void setGenerated(boolean generated) { this.generated = generated; } @Override public boolean isEditable() { if (gridColumn != null) { return gridColumn.isEditable(); } return isShouldBeEditable(); } public boolean isShouldBeEditable() { return editable && propertyPath != null // We can't generate field for editor in case we don't have propertyPath && (!generated && !isRepresentsCollection() || fieldGenerator != null || generator != null) && isEditingPermitted(); } protected boolean isRepresentsCollection() { if (propertyPath != null) { MetaProperty metaProperty = propertyPath.getMetaProperty(); Class<?> javaType = metaProperty.getJavaType(); return Collection.class.isAssignableFrom(javaType); } return false; } protected boolean isEditingPermitted() { if (propertyPath != null) { MetaClass metaClass = propertyPath.getMetaClass(); return owner.security.isEntityAttrUpdatePermitted(metaClass, propertyPath.toString()); } return true; } @Override public void setEditable(boolean editable) { this.editable = editable; updateEditable(); } protected void updateEditable() { if (gridColumn != null) { gridColumn.setEditable(isShouldBeEditable()); } } @Override public ColumnEditorFieldGenerator getEditorFieldGenerator() { return fieldGenerator; } @Override public void setEditorFieldGenerator(ColumnEditorFieldGenerator fieldFactory) { this.fieldGenerator = fieldFactory; updateEditable(); } @Override public Function<EditorFieldGenerationContext<E>, Field<?>> getEditFieldGenerator() { return generator; } @Override public void setEditFieldGenerator(Function<EditorFieldGenerationContext<E>, Field<?>> generator) { this.generator = generator; updateEditable(); } @SuppressWarnings("unchecked") @Override public Function<E, String> getStyleProvider() { return (Function<E, String>) styleProvider; } @Override public void setStyleProvider(Function<? super E, String> styleProvider) { this.styleProvider = styleProvider; owner.repaint(); } @SuppressWarnings("unchecked") @Override public Function<E, String> getDescriptionProvider() { return (Function<E, String>) descriptionProvider; } @Override public void setDescriptionProvider(Function<? super E, String> descriptionProvider) { setDescriptionProvider(descriptionProvider, ContentMode.PREFORMATTED); } @Override public void setDescriptionProvider(Function<? super E, String> descriptionProvider, ContentMode contentMode) { this.descriptionProvider = descriptionProvider; this.descriptionContentMode = contentMode; if (gridColumn != null) { gridColumn.getState().tooltipContentMode = WebWrapperUtils.toVaadinContentMode(contentMode); } owner.repaint(); } public ContentMode getDescriptionContentMode() { return descriptionContentMode; } public Grid.Column<E, ?> getGridColumn() { return gridColumn; } public void setGridColumn(Grid.Column<E, ?> gridColumn) { AppUI current = AppUI.getCurrent(); if (gridColumn == null && current != null && current.isTestMode()) { owner.removeColumnId(this.gridColumn); } this.gridColumn = gridColumn; } @Override public DataGrid<E> getOwner() { return owner; } @Override public void setOwner(DataGrid<E> owner) { this.owner = (WebAbstractDataGrid<?, E>) owner; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ColumnImpl column = (ColumnImpl) o; return id.equals(column.id); } @Override public int hashCode() { return id.hashCode(); } @Override public String toString() { return id == null ? super.toString() : id; } } protected abstract static class AbstractStaticRowImp<T extends StaticCell> implements StaticRow<T> { protected WebAbstractDataGrid dataGrid; protected StaticSection.StaticRow<?> gridRow; public AbstractStaticRowImp(WebAbstractDataGrid dataGrid, StaticSection.StaticRow<?> gridRow) { this.dataGrid = dataGrid; this.gridRow = gridRow; } @Override public String getStyleName() { return gridRow.getStyleName(); } @Override public void setStyleName(String styleName) { gridRow.setStyleName(styleName); } @Override public T join(String... columnIds) { return joinInternal(columnIds); } protected abstract T joinInternal(String... columnIds); @Override public T getCell(String columnId) { ColumnImpl column = (ColumnImpl) dataGrid.getColumnNN(columnId); return getCellInternal(column.getId()); } protected abstract T getCellInternal(String columnId); public StaticSection.StaticRow<?> getGridRow() { return gridRow; } } protected static class HeaderRowImpl extends AbstractStaticRowImp<HeaderCell> implements HeaderRow { public HeaderRowImpl(WebAbstractDataGrid dataGrid, Header.Row headerRow) { super(dataGrid, headerRow); } @Override public Header.Row getGridRow() { return (Header.Row) super.getGridRow(); } @Override protected HeaderCell getCellInternal(String columnId) { Header.Row.Cell gridCell = getGridRow().getCell(columnId); return new HeaderCellImpl(this, gridCell); } @Override protected HeaderCell joinInternal(String... columnIds) { Header.Row.Cell gridCell = (Header.Row.Cell) getGridRow().join(columnIds); return new HeaderCellImpl(this, gridCell); } } protected static class FooterRowImpl extends AbstractStaticRowImp<FooterCell> implements FooterRow { public FooterRowImpl(WebAbstractDataGrid dataGrid, Footer.Row footerRow) { super(dataGrid, footerRow); } @Override public Footer.Row getGridRow() { return (Footer.Row) super.getGridRow(); } @Override protected FooterCell getCellInternal(String columnId) { Footer.Row.Cell gridCell = getGridRow().getCell(columnId); return new FooterCellImpl(this, gridCell); } @Override protected FooterCell joinInternal(String... columnIds) { Footer.Row.Cell gridCell = (Footer.Row.Cell) getGridRow().join(columnIds); return new FooterCellImpl(this, gridCell); } } protected abstract static class AbstractStaticCellImpl implements StaticCell { protected StaticRow<?> row; protected com.haulmont.cuba.gui.components.Component component; public AbstractStaticCellImpl(StaticRow<?> row) { this.row = row; } @Override public StaticRow<?> getRow() { return row; } @Override public com.haulmont.cuba.gui.components.Component getComponent() { return component; } @Override public void setComponent(com.haulmont.cuba.gui.components.Component component) { this.component = component; } } protected static class HeaderCellImpl extends AbstractStaticCellImpl implements HeaderCell { protected Header.Row.Cell gridCell; public HeaderCellImpl(HeaderRow row, Header.Row.Cell gridCell) { super(row); this.gridCell = gridCell; } @Override public HeaderRow getRow() { return (HeaderRow) super.getRow(); } @Override public String getStyleName() { return gridCell.getStyleName(); } @Override public void setStyleName(String styleName) { gridCell.setStyleName(styleName); } @Override public DataGridStaticCellType getCellType() { return WebWrapperUtils.toDataGridStaticCellType(gridCell.getCellType()); } @Override public void setComponent(com.haulmont.cuba.gui.components.Component component) { super.setComponent(component); gridCell.setComponent(component.unwrap(Component.class)); } @Override public String getHtml() { return gridCell.getHtml(); } @Override public void setHtml(String html) { gridCell.setHtml(html); } @Override public String getText() { return gridCell.getText(); } @Override public void setText(String text) { gridCell.setText(text); } } protected static class FooterCellImpl extends AbstractStaticCellImpl implements FooterCell { protected Footer.Row.Cell gridCell; public FooterCellImpl(FooterRow row, Footer.Row.Cell gridCell) { super(row); this.gridCell = gridCell; } @Override public FooterRow getRow() { return (FooterRow) super.getRow(); } @Override public String getStyleName() { return gridCell.getStyleName(); } @Override public void setStyleName(String styleName) { gridCell.setStyleName(styleName); } @Override public DataGridStaticCellType getCellType() { return WebWrapperUtils.toDataGridStaticCellType(gridCell.getCellType()); } @Override public void setComponent(com.haulmont.cuba.gui.components.Component component) { super.setComponent(component); gridCell.setComponent(component.unwrap(Component.class)); } @Override public String getHtml() { return gridCell.getHtml(); } @Override public void setHtml(String html) { gridCell.setHtml(html); } @Override public String getText() { return gridCell.getText(); } @Override public void setText(String text) { gridCell.setText(text); } } public static class ActionMenuItemWrapper { protected MenuItem menuItem; protected Action action; protected boolean showIconsForPopupMenuActions; protected Consumer<PropertyChangeEvent> actionPropertyChangeListener; public ActionMenuItemWrapper(MenuItem menuItem, boolean showIconsForPopupMenuActions) { this.menuItem = menuItem; this.showIconsForPopupMenuActions = showIconsForPopupMenuActions; this.menuItem.setCommand((MenuBar.Command) selectedItem -> { if (action != null) { performAction(action); } }); } public void performAction(Action action) { action.actionPerform(null); } public MenuItem getMenuItem() { return menuItem; } public Action getAction() { return action; } public void setAction(Action action) { if (this.action != action) { if (this.action != null) { this.action.removePropertyChangeListener(actionPropertyChangeListener); } this.action = action; if (action != null) { String caption = action.getCaption(); if (!StringUtils.isEmpty(caption)) { setCaption(caption); } menuItem.setEnabled(action.isEnabled()); menuItem.setVisible(action.isVisible()); if (action.getIcon() != null) { setIcon(action.getIcon()); } actionPropertyChangeListener = evt -> { if (Action.PROP_ICON.equals(evt.getPropertyName())) { setIcon(this.action.getIcon()); } else if (Action.PROP_CAPTION.equals(evt.getPropertyName())) { setCaption(this.action.getCaption()); } else if (Action.PROP_ENABLED.equals(evt.getPropertyName())) { setEnabled(this.action.isEnabled()); } else if (Action.PROP_VISIBLE.equals(evt.getPropertyName())) { setVisible(this.action.isVisible()); } }; action.addPropertyChangeListener(actionPropertyChangeListener); } } } public void setEnabled(boolean enabled) { menuItem.setEnabled(enabled); } public void setVisible(boolean visible) { menuItem.setVisible(visible); } public void setIcon(String icon) { if (showIconsForPopupMenuActions) { if (!StringUtils.isEmpty(icon)) { menuItem.setIcon(AppBeans.get(IconResolver.class).getIconResource(icon)); } else { menuItem.setIcon(null); } } } public void setCaption(String caption) { if (action.getShortcutCombination() != null) { StringBuilder sb = new StringBuilder(); sb.append(caption); if (action.getShortcutCombination() != null) { sb.append(" (").append(action.getShortcutCombination().format()).append(")"); } caption = sb.toString(); } menuItem.setText(caption); } } protected static class GridComposition extends CubaCssActionsLayout { protected Grid<?> grid; public Grid<?> getGrid() { return grid; } public void setGrid(Grid<?> grid) { this.grid = grid; } @Override public void setHeight(float height, Unit unit) { super.setHeight(height, unit); if (getHeight() < 0) { grid.setHeightUndefined(); grid.setHeightMode(HeightMode.UNDEFINED); } else { grid.setHeight(100, Unit.PERCENTAGE); grid.setHeightMode(HeightMode.CSS); } } @Override public void setWidth(float width, Unit unit) { super.setWidth(width, unit); if (getWidth() < 0) { grid.setWidthUndefined(); } else { grid.setWidth(100, Unit.PERCENTAGE); } } } }
modules/web/src/com/haulmont/cuba/web/gui/components/WebAbstractDataGrid.java
/* * Copyright (c) 2008-2016 Haulmont. * * 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. */ package com.haulmont.cuba.web.gui.components; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.haulmont.bali.events.Subscription; import com.haulmont.bali.util.Preconditions; import com.haulmont.chile.core.model.MetaClass; import com.haulmont.chile.core.model.MetaProperty; import com.haulmont.chile.core.model.MetaPropertyPath; import com.haulmont.cuba.client.sys.PersistenceManagerClient; import com.haulmont.cuba.core.app.keyvalue.KeyValueMetaClass; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.global.*; import com.haulmont.cuba.gui.components.*; import com.haulmont.cuba.gui.components.actions.BaseAction; import com.haulmont.cuba.gui.components.data.BindingState; import com.haulmont.cuba.gui.components.data.DataGridItems; import com.haulmont.cuba.gui.components.data.ValueSourceProvider; import com.haulmont.cuba.gui.components.data.meta.ContainerDataUnit; import com.haulmont.cuba.gui.components.data.meta.DatasourceDataUnit; import com.haulmont.cuba.gui.components.data.meta.EmptyDataUnit; import com.haulmont.cuba.gui.components.data.meta.EntityDataGridItems; import com.haulmont.cuba.gui.components.data.value.ContainerValueSource; import com.haulmont.cuba.gui.components.data.value.ContainerValueSourceProvider; import com.haulmont.cuba.gui.components.formatters.CollectionFormatter; import com.haulmont.cuba.gui.components.security.ActionsPermissions; import com.haulmont.cuba.gui.components.sys.ShortcutsDelegate; import com.haulmont.cuba.gui.components.sys.ShowInfoAction; import com.haulmont.cuba.gui.data.CollectionDatasource; import com.haulmont.cuba.gui.data.Datasource; import com.haulmont.cuba.gui.data.DsBuilder; import com.haulmont.cuba.gui.data.impl.DatasourceImplementation; import com.haulmont.cuba.gui.model.*; import com.haulmont.cuba.gui.model.impl.KeyValueContainerImpl; import com.haulmont.cuba.gui.screen.ScreenValidation; import com.haulmont.cuba.gui.sys.UiTestIds; import com.haulmont.cuba.gui.theme.ThemeConstants; import com.haulmont.cuba.gui.theme.ThemeConstantsManager; import com.haulmont.cuba.web.App; import com.haulmont.cuba.web.AppUI; import com.haulmont.cuba.web.gui.components.datagrid.DataGridDataProvider; import com.haulmont.cuba.web.gui.components.datagrid.DataGridItemsEventsDelegate; import com.haulmont.cuba.web.gui.components.datagrid.SortableDataGridDataProvider; import com.haulmont.cuba.web.gui.components.renderers.*; import com.haulmont.cuba.web.gui.components.util.ShortcutListenerDelegate; import com.haulmont.cuba.web.gui.components.valueproviders.*; import com.haulmont.cuba.web.gui.icons.IconResolver; import com.haulmont.cuba.web.widgets.CubaCssActionsLayout; import com.haulmont.cuba.web.widgets.CubaEnhancedGrid; import com.haulmont.cuba.web.widgets.CubaGridEditorFieldFactory; import com.haulmont.cuba.web.widgets.CubaUI; import com.haulmont.cuba.web.widgets.data.SortableDataProvider; import com.haulmont.cuba.web.widgets.grid.*; import com.vaadin.data.HasValue; import com.vaadin.data.SelectionModel; import com.vaadin.data.ValidationResult; import com.vaadin.data.ValueProvider; import com.vaadin.data.provider.DataProvider; import com.vaadin.data.provider.GridSortOrder; import com.vaadin.data.provider.ListDataProvider; import com.vaadin.event.ShortcutAction.KeyCode; import com.vaadin.event.ShortcutListener; import com.vaadin.event.selection.MultiSelectionEvent; import com.vaadin.shared.Registration; import com.vaadin.shared.ui.grid.HeightMode; import com.vaadin.ui.Component; import com.vaadin.ui.DescriptionGenerator; import com.vaadin.ui.*; import com.vaadin.ui.MenuBar.MenuItem; import com.vaadin.ui.components.grid.*; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import javax.annotation.Nullable; import javax.inject.Inject; import java.beans.PropertyChangeEvent; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import static com.haulmont.bali.util.Preconditions.checkNotNullArgument; import static com.haulmont.cuba.gui.ComponentsHelper.findActionById; import static com.haulmont.cuba.gui.components.Window.Lookup.LOOKUP_ENTER_PRESSED_ACTION_ID; import static com.haulmont.cuba.gui.components.Window.Lookup.LOOKUP_ITEM_CLICK_ACTION_ID; public abstract class WebAbstractDataGrid<C extends Grid<E> & CubaEnhancedGrid<E>, E extends Entity> extends WebAbstractComponent<C> implements DataGrid<E>, SecuredActionsHolder, LookupComponent.LookupSelectionChangeNotifier<E>, DataGridItemsEventsDelegate<E>, HasInnerComponents, InitializingBean { protected static final String HAS_TOP_PANEL_STYLE_NAME = "has-top-panel"; protected static final String TEXT_SELECTION_ENABLED_STYLE = "text-selection-enabled"; private static final Logger log = LoggerFactory.getLogger(WebAbstractDataGrid.class); /* Beans */ protected MetadataTools metadataTools; protected Security security; protected Messages messages; protected MessageTools messageTools; protected PersistenceManagerClient persistenceManagerClient; protected ApplicationContext applicationContext; protected ScreenValidation screenValidation; // Style names used by grid itself protected final List<String> internalStyles = new ArrayList<>(2); protected final Map<String, Column<E>> columns = new HashMap<>(); protected List<Column<E>> columnsOrder = new ArrayList<>(); protected final Map<String, ColumnGenerator<E, ?>> columnGenerators = new HashMap<>(); protected final List<Action> actionList = new ArrayList<>(); protected final ShortcutsDelegate<ShortcutListener> shortcutsDelegate; protected final ActionsPermissions actionsPermissions = new ActionsPermissions(this); protected CubaGridContextMenu<E> contextMenu; protected final List<ActionMenuItemWrapper> contextMenuItems = new ArrayList<>(); protected boolean settingsEnabled = true; protected boolean sortable = true; protected boolean columnsCollapsingAllowed = true; protected boolean textSelectionEnabled = false; protected boolean editorCrossFieldValidate = true; protected Action itemClickAction; protected Action enterPressAction; protected SelectionMode selectionMode; protected GridComposition componentComposition; protected HorizontalLayout topPanel; protected ButtonsPanel buttonsPanel; protected RowsCount rowsCount; protected List<Function<? super E, String>> rowStyleProviders; protected List<CellStyleProvider<? super E>> cellStyleProviders; protected Function<? super E, String> rowDescriptionProvider; protected CellDescriptionProvider<? super E> cellDescriptionProvider; protected DetailsGenerator<E> detailsGenerator = null; protected Registration columnCollapsingChangeListenerRegistration; protected Registration columnResizeListenerRegistration; protected Registration contextClickListenerRegistration; protected Document defaultSettings; protected Registration editorCancelListener; protected Registration editorOpenListener; protected Registration editorBeforeSaveListener; protected Registration editorSaveListener; protected final List<HeaderRow> headerRows = new ArrayList<>(); protected final List<FooterRow> footerRows = new ArrayList<>(); protected static final Map<Class<? extends Renderer>, Class<? extends Renderer>> rendererClasses; protected boolean showIconsForPopupMenuActions; protected DataGridDataProvider<E> dataBinding; protected Map<E, Object> itemDatasources; // lazily initialized WeakHashMap; protected Consumer<EmptyStateClickEvent<E>> emptyStateClickEventHandler; static { ImmutableMap.Builder<Class<? extends Renderer>, Class<? extends Renderer>> builder = new ImmutableMap.Builder<>(); builder.put(TextRenderer.class, WebTextRenderer.class); builder.put(ClickableTextRenderer.class, WebClickableTextRenderer.class); builder.put(HtmlRenderer.class, WebHtmlRenderer.class); builder.put(ProgressBarRenderer.class, WebProgressBarRenderer.class); builder.put(DateRenderer.class, WebDateRenderer.class); builder.put(LocalDateRenderer.class, WebLocalDateRenderer.class); builder.put(LocalDateTimeRenderer.class, WebLocalDateTimeRenderer.class); builder.put(NumberRenderer.class, WebNumberRenderer.class); builder.put(ButtonRenderer.class, WebButtonRenderer.class); builder.put(ImageRenderer.class, WebImageRenderer.class); builder.put(CheckBoxRenderer.class, WebCheckBoxRenderer.class); builder.put(ComponentRenderer.class, WebComponentRenderer.class); builder.put(IconRenderer.class, WebIconRenderer.class); rendererClasses = builder.build(); } public WebAbstractDataGrid() { component = createComponent(); componentComposition = createComponentComposition(); shortcutsDelegate = createShortcutsDelegate(); } protected GridComposition createComponentComposition() { return new GridComposition(); } protected abstract C createComponent(); protected ShortcutsDelegate<ShortcutListener> createShortcutsDelegate() { return new ShortcutsDelegate<ShortcutListener>() { @Override protected ShortcutListener attachShortcut(String actionId, KeyCombination keyCombination) { ShortcutListener shortcut = new ShortcutListenerDelegate(actionId, keyCombination.getKey().getCode(), KeyCombination.Modifier.codes(keyCombination.getModifiers()) ).withHandler((sender, target) -> { if (sender == componentComposition) { Action action = getAction(actionId); if (action != null && action.isEnabled() && action.isVisible()) { action.actionPerform(WebAbstractDataGrid.this); } } }); componentComposition.addShortcutListener(shortcut); return shortcut; } @Override protected void detachShortcut(Action action, ShortcutListener shortcutDescriptor) { componentComposition.removeShortcutListener(shortcutDescriptor); } @Override protected Collection<Action> getActions() { return WebAbstractDataGrid.this.getActions(); } }; } @Override public void afterPropertiesSet() throws Exception { initComponent(component); initComponentComposition(componentComposition); initHeaderRows(component); initFooterRows(component); initEditor(component); initContextMenu(); } @Inject public void setMetadataTools(MetadataTools metadataTools) { this.metadataTools = metadataTools; } @Inject public void setSecurity(Security security) { this.security = security; } @Inject public void setMessages(Messages messages) { this.messages = messages; } @Inject public void setMessageTools(MessageTools messageTools) { this.messageTools = messageTools; } @Inject public void setThemeConstantsManager(ThemeConstantsManager themeConstantsManager) { ThemeConstants theme = themeConstantsManager.getConstants(); this.showIconsForPopupMenuActions = theme.getBoolean("cuba.gui.showIconsForPopupMenuActions", false); } @Inject public void setPersistenceManagerClient(PersistenceManagerClient persistenceManagerClient) { this.persistenceManagerClient = persistenceManagerClient; } @Inject public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Inject protected void setScreenValidation(ScreenValidation screenValidation) { this.screenValidation = screenValidation; } @SuppressWarnings("unchecked") protected void initComponent(Grid<E> component) { setSelectionMode(SelectionMode.SINGLE); component.setColumnReorderingAllowed(true); component.addItemClickListener(this::onItemClick); component.addColumnReorderListener(this::onColumnReorder); component.addSortListener(this::onSort); component.setSizeUndefined(); component.setHeightMode(HeightMode.UNDEFINED); component.setStyleGenerator(this::getGeneratedRowStyle); ((CubaEnhancedGrid<E>) component).setCubaEditorFieldFactory(createEditorFieldFactory()); ((CubaEnhancedGrid<E>) component).setBeforeRefreshHandler(this::onBeforeRefreshGridData); initEmptyState(); } protected void onBeforeRefreshGridData(E item) { clearFieldDatasources(item); } protected CubaGridEditorFieldFactory<E> createEditorFieldFactory() { DataGridEditorFieldFactory fieldFactory = beanLocator.get(DataGridEditorFieldFactory.NAME); return new WebDataGridEditorFieldFactory<>(this, fieldFactory); } protected void initComponentComposition(GridComposition componentComposition) { componentComposition.setPrimaryStyleName("c-data-grid-composition"); componentComposition.setGrid(component); componentComposition.addComponent(component); componentComposition.setWidthUndefined(); componentComposition.addShortcutListener(createEnterShortcutListener()); } protected void onItemClick(Grid.ItemClick<E> e) { CubaUI ui = (CubaUI) component.getUI(); if (!ui.isAccessibleForUser(component)) { LoggerFactory.getLogger(WebDataGrid.class) .debug("Ignore click attempt because DataGrid is inaccessible for user"); return; } com.vaadin.shared.MouseEventDetails vMouseEventDetails = e.getMouseEventDetails(); if (vMouseEventDetails.isDoubleClick() && e.getItem() != null && !WebAbstractDataGrid.this.isEditorEnabled()) { // note: for now Grid doesn't send double click if editor is enabled, // but it's better to handle it manually handleDoubleClickAction(); } if (hasSubscriptions(ItemClickEvent.class)) { MouseEventDetails mouseEventDetails = WebWrapperUtils.toMouseEventDetails(vMouseEventDetails); E item = e.getItem(); if (item == null) { // this can happen if user clicked on an item which is removed from the // datasource, so we don't want to send such event because it's useless return; } Column<E> column = getColumnById(e.getColumn().getId()); ItemClickEvent<E> event = new ItemClickEvent<>(WebAbstractDataGrid.this, mouseEventDetails, item, item.getId(), column != null ? column.getId() : null); publish(ItemClickEvent.class, event); } } protected void onColumnReorder(Grid.ColumnReorderEvent e) { // Grid doesn't know about columns hidden by security permissions, // so we need to return them back to they previous positions columnsOrder = restoreColumnsOrder(getColumnsOrderInternal()); ColumnReorderEvent event = new ColumnReorderEvent(WebAbstractDataGrid.this, e.isUserOriginated()); publish(ColumnReorderEvent.class, event); } protected void onSort(com.vaadin.event.SortEvent<GridSortOrder<E>> e) { if (component.getDataProvider() instanceof SortableDataProvider) { //noinspection unchecked SortableDataProvider<E> dataProvider = (SortableDataProvider<E>) component.getDataProvider(); List<GridSortOrder<E>> sortOrders = e.getSortOrder(); if (sortOrders.isEmpty()) { dataProvider.resetSortOrder(); } else { GridSortOrder<E> sortOrder = sortOrders.get(0); Column<E> column = getColumnByGridColumn(sortOrder.getSorted()); if (column != null) { MetaPropertyPath propertyPath = column.getPropertyPath(); boolean ascending = com.vaadin.shared.data.sort.SortDirection.ASCENDING .equals(sortOrder.getDirection()); dataProvider.sort(new Object[]{propertyPath}, new boolean[]{ascending}); } } } List<SortOrder> sortOrders = convertToDataGridSortOrder(e.getSortOrder()); SortEvent event = new SortEvent(WebAbstractDataGrid.this, sortOrders, e.isUserOriginated()); publish(SortEvent.class, event); } protected void onSelectionChange(com.vaadin.event.selection.SelectionEvent<E> e) { DataGridItems<E> dataGridItems = getItems(); if (dataGridItems == null || dataGridItems.getState() == BindingState.INACTIVE) { return; } Set<E> selected = getSelected(); if (selected.isEmpty()) { dataGridItems.setSelectedItem(null); } else { // reset selection and select new item if (isMultiSelect()) { dataGridItems.setSelectedItem(null); } E newItem = selected.iterator().next(); E dsItem = dataGridItems.getSelectedItem(); dataGridItems.setSelectedItem(newItem); if (Objects.equals(dsItem, newItem)) { // in this case item change event will not be generated refreshActionsState(); } } fireSelectionEvent(e); LookupSelectionChangeEvent<E> selectionChangeEvent = new LookupSelectionChangeEvent<>(this); publish(LookupSelectionChangeEvent.class, selectionChangeEvent); } protected void fireSelectionEvent(com.vaadin.event.selection.SelectionEvent<E> e) { Set<E> oldSelection; if (e instanceof MultiSelectionEvent) { oldSelection = ((MultiSelectionEvent<E>) e).getOldSelection(); } else { //noinspection unchecked E oldValue = ((HasValue.ValueChangeEvent<E>) e).getOldValue(); oldSelection = oldValue != null ? Collections.singleton(oldValue) : Collections.emptySet(); } SelectionEvent<E> event = new SelectionEvent<>(WebAbstractDataGrid.this, oldSelection, e.isUserOriginated()); publish(SelectionEvent.class, event); } protected ShortcutListenerDelegate createEnterShortcutListener() { return new ShortcutListenerDelegate("dataGridEnter", KeyCode.ENTER, null) .withHandler((sender, target) -> { if (sender == componentComposition) { if (isEditorEnabled()) { // Prevent custom actions on Enter if DataGrid editor is enabled // since it's the default shortcut to open editor return; } CubaUI ui = (CubaUI) componentComposition.getUI(); if (!ui.isAccessibleForUser(componentComposition)) { LoggerFactory.getLogger(WebDataGrid.class) .debug("Ignore click attempt because DataGrid is inaccessible for user"); return; } if (enterPressAction != null) { enterPressAction.actionPerform(this); } else { handleDoubleClickAction(); } } }); } @Override public Collection<com.haulmont.cuba.gui.components.Component> getInnerComponents() { if (buttonsPanel != null) { return Collections.singletonList(buttonsPanel); } return Collections.emptyList(); } protected void initEditor(Grid<E> component) { component.getEditor().setSaveCaption(messages.getMainMessage("actions.Ok")); component.getEditor().setCancelCaption(messages.getMainMessage("actions.Cancel")); } protected void initHeaderRows(Grid<E> component) { for (int i = 0; i < component.getHeaderRowCount(); i++) { com.vaadin.ui.components.grid.HeaderRow headerRow = component.getHeaderRow(i); addHeaderRowInternal(headerRow); } } protected void initFooterRows(Grid<E> component) { for (int i = 0; i < component.getFooterRowCount(); i++) { com.vaadin.ui.components.grid.FooterRow footerRow = component.getFooterRow(i); addFooterRowInternal(footerRow); } } protected List<Column<E>> getColumnsOrderInternal() { List<Grid.Column<E, ?>> columnsOrder = component.getColumns(); return columnsOrder.stream() .map(this::getColumnByGridColumn) .collect(Collectors.toList()); } /** * Inserts columns hidden by security permissions (or with visible = false, * which means that where is no Grid.Column associated with DatGrid.Column) * into a list of visible columns, passed as a parameter, in they original positions. * * @param visibleColumns the list of DataGrid columns, * not hidden by security permissions * @return a list of all columns in DataGrid */ protected List<Column<E>> restoreColumnsOrder(List<Column<E>> visibleColumns) { List<Column<E>> newColumnsOrder = new ArrayList<>(visibleColumns); columnsOrder.stream() .filter(column -> !visibleColumns.contains(column)) .forEach(column -> newColumnsOrder.add(columnsOrder.indexOf(column), column)); return newColumnsOrder; } protected void initContextMenu() { contextMenu = new CubaGridContextMenu<>(component); contextMenu.addGridBodyContextMenuListener(event -> { if (!component.getSelectedItems().contains(event.getItem())) { // In the multi select model 'setSelected' adds item to selected set, // but, in case of context click, we want to have a single selected item, // if it isn't in a set of already selected items if (isMultiSelect()) { component.deselectAll(); } setSelected(event.getItem()); } }); } protected void refreshActionsState() { getActions().forEach(Action::refreshState); } protected void handleDoubleClickAction() { Action action = getItemClickAction(); if (action == null) { action = getEnterAction(); if (action == null) { action = getAction("edit"); if (action == null) { action = getAction("view"); } } } if (action != null && action.isEnabled()) { action.actionPerform(WebAbstractDataGrid.this); } } @Override public void focus() { component.focus(); } @Override public void setLookupSelectHandler(Consumer<Collection<E>> selectHandler) { Consumer<Action.ActionPerformedEvent> actionHandler = event -> { Set<E> selected = getSelected(); selectHandler.accept(selected); }; setEnterPressAction(new BaseAction(LOOKUP_ENTER_PRESSED_ACTION_ID) .withHandler(actionHandler)); setItemClickAction(new BaseAction(LOOKUP_ITEM_CLICK_ACTION_ID) .withHandler(actionHandler)); if (buttonsPanel != null && !buttonsPanel.isAlwaysVisible()) { buttonsPanel.setVisible(false); } setEditorEnabled(false); } @Override public Collection<E> getLookupSelectedItems() { return getSelected(); } protected Action getEnterAction() { for (Action action : getActions()) { KeyCombination kc = action.getShortcutCombination(); if (kc != null) { if ((kc.getModifiers() == null || kc.getModifiers().length == 0) && kc.getKey() == KeyCombination.Key.ENTER) { return action; } } } return null; } @Override public List<Column<E>> getColumns() { return Collections.unmodifiableList(columnsOrder); } @Override public List<Column<E>> getVisibleColumns() { return columnsOrder.stream() .filter(Column::isVisible) .collect(Collectors.toList()); } @Nullable @Override public Column<E> getColumn(String id) { checkNotNullArgument(id); return columns.get(id); } @Override public Column<E> getColumnNN(String id) { Column<E> column = getColumn(id); if (column == null) { throw new IllegalStateException("Unable to find column with id " + id); } return column; } @Override public void addColumn(Column<E> column) { addColumn(column, columnsOrder.size()); } @Override public void addColumn(Column<E> column, int index) { checkNotNullArgument(column, "Column must be non null"); if (column.getOwner() != null && column.getOwner() != this) { throw new IllegalArgumentException("Can't add column owned by another DataGrid"); } addColumnInternal((ColumnImpl<E>) column, index); } @Override public Column<E> addColumn(String id, MetaPropertyPath propertyPath) { return addColumn(id, propertyPath, columnsOrder.size()); } @Override public Column<E> addColumn(String id, MetaPropertyPath propertyPath, int index) { ColumnImpl<E> column = new ColumnImpl<>(id, propertyPath, this); addColumnInternal(column, index); return column; } protected void addColumnInternal(ColumnImpl<E> column, int index) { Grid.Column<E, ?> gridColumn = component.addColumn( new EntityValueProvider<>(column.getPropertyPath())); columns.put(column.getId(), column); columnsOrder.add(index, column); final String caption = StringUtils.capitalize(column.getCaption() != null ? column.getCaption() : generateColumnCaption(column)); column.setCaption(caption); if (column.getOwner() == null) { column.setOwner(this); } MetaPropertyPath propertyPath = column.getPropertyPath(); if (propertyPath != null) { MetaProperty metaProperty = propertyPath.getMetaProperty(); MetaClass propertyMetaClass = metadataTools.getPropertyEnclosingMetaClass(propertyPath); String storeName = metadataTools.getStoreName(propertyMetaClass); if (metadataTools.isLob(metaProperty) && !persistenceManagerClient.supportsLobSortingAndFiltering(storeName)) { column.setSortable(false); } } setupGridColumnProperties(gridColumn, column); component.setColumnOrder(getColumnOrder()); } protected String generateColumnCaption(Column<E> column) { return column.getPropertyPath() != null ? column.getPropertyPath().getMetaProperty().getName() : column.getId(); } protected void setupGridColumnProperties(Grid.Column<E, ?> gridColumn, Column<E> column) { if (gridColumn.getId() == null) { gridColumn.setId(column.getId()); } else if (!Objects.equals(gridColumn.getId(), column.getId())) { log.warn("Trying to copy column settings with mismatched ids. Grid.Column: " + gridColumn.getId() + "; DataGrid.Column: " + column.getId()); } gridColumn.setCaption(column.getCaption()); gridColumn.setHidingToggleCaption(column.getCollapsingToggleCaption()); if (column.isWidthAuto()) { gridColumn.setWidthUndefined(); } else { gridColumn.setWidth(column.getWidth()); } gridColumn.setExpandRatio(column.getExpandRatio()); gridColumn.setMinimumWidth(column.getMinimumWidth()); gridColumn.setMaximumWidth(column.getMaximumWidth()); gridColumn.setHidden(column.isCollapsed()); gridColumn.setHidable(column.isCollapsible() && column.getOwner().isColumnsCollapsingAllowed()); gridColumn.setResizable(column.isResizable()); gridColumn.setSortable(column.isSortable() && column.getOwner().isSortable()); gridColumn.setEditable(column.isEditable()); AppUI current = AppUI.getCurrent(); if (current != null && current.isTestMode()) { addColumnId(gridColumn, column); } //noinspection unchecked gridColumn.setRenderer(getDefaultPresentationValueProvider(column), getDefaultRenderer(column)); gridColumn.setStyleGenerator(new CellStyleGeneratorAdapter<>(column)); gridColumn.setDescriptionGenerator(new CellDescriptionGeneratorAdapter<>(column), WebWrapperUtils.toVaadinContentMode(((ColumnImpl) column).getDescriptionContentMode())); ((ColumnImpl<E>) column).setGridColumn(gridColumn); } protected ValueProvider getDefaultPresentationValueProvider(Column<E> column) { MetaProperty metaProperty = column.getPropertyPath() != null ? column.getPropertyPath().getMetaProperty() : null; if (column.getFormatter() != null) { //noinspection unchecked return new FormatterBasedValueProvider<>(column.getFormatter()); } else if (metaProperty != null) { if (Collection.class.isAssignableFrom(metaProperty.getJavaType())) { return new FormatterBasedValueProvider<>(new CollectionFormatter(metadataTools)); } if (column.getType() == Boolean.class) { return new YesNoIconPresentationValueProvider(); } } return new StringPresentationValueProvider(metaProperty, metadataTools); } protected com.vaadin.ui.renderers.Renderer getDefaultRenderer(Column<E> column) { MetaProperty metaProperty = column.getPropertyPath() != null ? column.getPropertyPath().getMetaProperty() : null; return column.getType() == Boolean.class && metaProperty != null ? new com.vaadin.ui.renderers.HtmlRenderer() : new com.vaadin.ui.renderers.TextRenderer(); } protected void addColumnId(Grid.Column<E, ?> gridColumn, Column<E> column) { component.addColumnId(gridColumn.getState().internalId, column.getId()); } protected void removeColumnId(Grid.Column<E, ?> gridColumn) { component.removeColumnId(gridColumn.getId()); } @Override public void removeColumn(Column<E> column) { if (column == null) { return; } component.removeColumn(column.getId()); columns.remove(column.getId()); columnsOrder.remove(column); columnGenerators.remove(column.getId()); ((ColumnImpl<E>) column).setGridColumn(null); column.setOwner(null); } @Override public void removeColumn(String id) { removeColumn(getColumn(id)); } @Nullable @Override public DataGridItems<E> getItems() { return this.dataBinding != null ? this.dataBinding.getDataGridItems() : null; } protected DataGridItems<E> getDataGridItemsNN() { DataGridItems<E> dataGridItems = getItems(); if (dataGridItems == null || dataGridItems.getState() == BindingState.INACTIVE) { throw new IllegalStateException("DataGridItems is not active"); } return dataGridItems; } protected EntityDataGridItems<E> getEntityDataGridItems() { return getItems() != null ? (EntityDataGridItems<E>) getItems() : null; } protected EntityDataGridItems<E> getEntityDataGridItemsNN() { return (EntityDataGridItems<E>) getDataGridItemsNN(); } @Override public void setItems(DataGridItems<E> dataGridItems) { if (dataGridItems != null && !(dataGridItems instanceof EntityDataGridItems)) { throw new IllegalArgumentException("DataGrid supports only EntityDataGridItems"); } if (this.dataBinding != null) { this.dataBinding.unbind(); this.dataBinding = null; clearFieldDatasources(null); this.component.setDataProvider(createEmptyDataProvider()); } if (dataGridItems != null) { // DataGrid supports only EntityDataGridItems EntityDataGridItems<E> entityDataGridSource = (EntityDataGridItems<E>) dataGridItems; if (this.columns.isEmpty()) { setupAutowiredColumns(entityDataGridSource); } // Bind new datasource this.dataBinding = createDataGridDataProvider(dataGridItems); this.component.setDataProvider(this.dataBinding); List<Column<E>> visibleColumnsOrder = getInitialVisibleColumns(); setVisibleColumns(visibleColumnsOrder); for (Column<E> column : visibleColumnsOrder) { Grid.Column<E, ?> gridColumn = ((ColumnImpl<E>) column).getGridColumn(); setupGridColumnProperties(gridColumn, column); } component.setColumnOrder(getColumnOrder()); initShowInfoAction(); if (rowsCount != null) { rowsCount.setRowsCountTarget(this); } if (!canBeSorted(dataGridItems)) { setSortable(false); } // resort data if dataGrid have been sorted before setting items if (isSortable()) { List<GridSortOrder<E>> sortOrders = component.getSortOrder(); if (!sortOrders.isEmpty()) { List<GridSortOrder<E>> copiedSortOrders = new ArrayList<>(sortOrders); component.clearSortOrder(); component.setSortOrder(copiedSortOrders); } } refreshActionsState(); setUiTestId(dataGridItems); } initEmptyState(); } protected void setUiTestId(DataGridItems<E> items) { AppUI ui = AppUI.getCurrent(); if (ui != null && ui.isTestMode() && getComponent().getCubaId() == null) { String testId = UiTestIds.getInferredTestId(items, "DataGrid"); if (testId != null) { getComponent().setCubaId(testId); componentComposition.setCubaId(testId + "_composition"); } } } protected DataProvider<E, ?> createEmptyDataProvider() { return new ListDataProvider<>(Collections.emptyList()); } protected void setVisibleColumns(List<Column<E>> visibleColumnsOrder) { // mark columns hidden by security permissions as visible = false // and remove Grid.Column to prevent its property changing columnsOrder.stream() .filter(column -> !visibleColumnsOrder.contains(column)) .forEach(column -> { ColumnImpl<E> columnImpl = (ColumnImpl<E>) column; columnImpl.setVisible(false); columnImpl.setGridColumn(null); }); } protected Collection<MetaPropertyPath> getAutowiredProperties(EntityDataGridItems<E> entityDataGridSource) { if (entityDataGridSource instanceof ContainerDataUnit) { CollectionContainer container = ((ContainerDataUnit) entityDataGridSource).getContainer(); return container.getView() != null ? // if a view is specified - use view properties metadataTools.getViewPropertyPaths(container.getView(), container.getEntityMetaClass()) : // otherwise use all properties from meta-class metadataTools.getPropertyPaths(container.getEntityMetaClass()); } if (entityDataGridSource instanceof DatasourceDataUnit) { CollectionDatasource datasource = ((DatasourceDataUnit) entityDataGridSource).getDatasource(); return datasource.getView() != null ? // if a view is specified - use view properties metadataTools.getViewPropertyPaths(datasource.getView(), datasource.getMetaClass()) : // otherwise use all properties from meta-class metadataTools.getPropertyPaths(datasource.getMetaClass()); } if (entityDataGridSource instanceof EmptyDataUnit) { return metadataTools.getPropertyPaths(entityDataGridSource.getEntityMetaClass()); } return Collections.emptyList(); } protected void setupAutowiredColumns(EntityDataGridItems<E> entityDataGridSource) { Collection<MetaPropertyPath> paths = getAutowiredProperties(entityDataGridSource); for (MetaPropertyPath metaPropertyPath : paths) { MetaProperty property = metaPropertyPath.getMetaProperty(); if (!property.getRange().getCardinality().isMany() && !metadataTools.isSystem(property)) { String propertyName = property.getName(); ColumnImpl<E> column = new ColumnImpl<>(propertyName, metaPropertyPath, this); MetaClass propertyMetaClass = metadataTools.getPropertyEnclosingMetaClass(metaPropertyPath); column.setCaption(messageTools.getPropertyCaption(propertyMetaClass, propertyName)); addColumn(column); } } } protected DataGridDataProvider<E> createDataGridDataProvider(DataGridItems<E> dataGridItems) { return (dataGridItems instanceof DataGridItems.Sortable) ? new SortableDataGridDataProvider<>((DataGridItems.Sortable<E>) dataGridItems, this) : new DataGridDataProvider<>(dataGridItems, this); } @Override public void dataGridSourceItemSetChanged(DataGridItems.ItemSetChangeEvent<E> event) { // #PL-2035, reload selection from ds Set<E> selectedItems = getSelected(); Set<E> newSelection = new HashSet<>(); for (E item : selectedItems) { if (event.getSource().containsItem(item)) { newSelection.add(event.getSource().getItem(item.getId())); } } if (event.getSource().getState() == BindingState.ACTIVE && event.getSource().getSelectedItem() != null) { newSelection.add(event.getSource().getSelectedItem()); } if (newSelection.isEmpty()) { setSelected((E) null); } else { // Workaround for the MultiSelect model. // Set the selected items only if the previous selection is different // Otherwise, the DataGrid rows will display the values before editing if (isMultiSelect() && !selectedItems.equals(newSelection)) { setSelectedItems(newSelection); } } refreshActionsState(); } @Override public void dataGridSourcePropertyValueChanged(DataGridItems.ValueChangeEvent<E> event) { refreshActionsState(); } @Override public void dataGridSourceStateChanged(DataGridItems.StateChangeEvent event) { refreshActionsState(); } @Override public void dataGridSourceSelectedItemChanged(DataGridItems.SelectedItemChangeEvent<E> event) { refreshActionsState(); } protected String[] getColumnOrder() { return columnsOrder.stream() .filter(Column::isVisible) .map(Column::getId) .toArray(String[]::new); } protected void initShowInfoAction() { if (security.isSpecificPermitted(ShowInfoAction.ACTION_PERMISSION)) { if (getAction(ShowInfoAction.ACTION_ID) == null) { addAction(new ShowInfoAction()); } } } @Override public String getCaption() { return getComposition().getCaption(); } @Override public void setCaption(String caption) { getComposition().setCaption(caption); } @Override public boolean isCaptionAsHtml() { return ((com.vaadin.ui.AbstractComponent) getComposition()).isCaptionAsHtml(); } @Override public void setCaptionAsHtml(boolean captionAsHtml) { ((com.vaadin.ui.AbstractComponent) getComposition()).setCaptionAsHtml(captionAsHtml); } @Override public boolean isTextSelectionEnabled() { return textSelectionEnabled; } @Override public void setTextSelectionEnabled(boolean textSelectionEnabled) { if (this.textSelectionEnabled != textSelectionEnabled) { this.textSelectionEnabled = textSelectionEnabled; if (textSelectionEnabled) { if (!internalStyles.contains(TEXT_SELECTION_ENABLED_STYLE)) { internalStyles.add(TEXT_SELECTION_ENABLED_STYLE); } componentComposition.addStyleName(TEXT_SELECTION_ENABLED_STYLE); } else { internalStyles.remove(TEXT_SELECTION_ENABLED_STYLE); componentComposition.removeStyleName(TEXT_SELECTION_ENABLED_STYLE); } } } @Override public boolean isColumnReorderingAllowed() { return component.isColumnReorderingAllowed(); } @Override public void setColumnReorderingAllowed(boolean columnReorderingAllowed) { component.setColumnReorderingAllowed(columnReorderingAllowed); } @Override public boolean isSortable() { return sortable; } @Override public void setSortable(boolean sortable) { this.sortable = sortable && (getItems() == null || canBeSorted(getItems())); for (Column<E> column : getColumns()) { ((ColumnImpl<E>) column).updateSortable(); } } @Override public boolean isColumnsCollapsingAllowed() { return columnsCollapsingAllowed; } @Override public void setColumnsCollapsingAllowed(boolean columnsCollapsingAllowed) { this.columnsCollapsingAllowed = columnsCollapsingAllowed; for (Column<E> column : getColumns()) { ((ColumnImpl<E>) column).updateCollapsible(); } } @Override public boolean isEditorEnabled() { return component.getEditor().isEnabled(); } @Override public void setEditorEnabled(boolean isEnabled) { component.getEditor().setEnabled(isEnabled); enableCrossFieldValidationHandling(editorCrossFieldValidate); } @Override public boolean isEditorBuffered() { return component.getEditor().isBuffered(); } @Override public void setEditorBuffered(boolean editorBuffered) { component.getEditor().setBuffered(editorBuffered); } @Override public String getEditorSaveCaption() { return component.getEditor().getSaveCaption(); } @Override public void setEditorSaveCaption(String saveCaption) { component.getEditor().setSaveCaption(saveCaption); } @Override public String getEditorCancelCaption() { return component.getEditor().getCancelCaption(); } @Override public void setEditorCancelCaption(String cancelCaption) { component.getEditor().setCancelCaption(cancelCaption); } @Nullable @Override public Object getEditedItemId() { E item = getEditedItem(); return item != null ? item.getId() : null; } @Override public E getEditedItem() { return component.getEditor() instanceof CubaEditorImpl ? ((CubaEditorImpl<E>) component.getEditor()).getBean() : component.getEditor().getBinder().getBean(); } @Override public boolean isEditorActive() { return component.getEditor().isOpen(); } @Override public void editItem(Object itemId) { checkNotNullArgument(itemId, "Item's Id must be non null"); DataGridItems<E> dataGridItems = getItems(); if (dataGridItems == null || dataGridItems.getState() == BindingState.INACTIVE) { return; } E item = getItems().getItem(itemId); edit(item); } @Override public void edit(E item) { checkNotNullArgument(item, "Entity must be non null"); DataGridItems<E> dataGridItems = getItems(); if (dataGridItems == null || dataGridItems.getState() == BindingState.INACTIVE) { return; } if (!dataGridItems.containsItem(item)) { throw new IllegalArgumentException("Datasource doesn't contain item"); } editItemInternal(item); } protected void editItemInternal(E item) { int rowIndex = getDataGridItemsNN().indexOfItem(item); component.getEditor().editRow(rowIndex); } @SuppressWarnings("ConstantConditions") protected Map<String, Field> convertToCubaFields(Map<Grid.Column<E, ?>, Component> columnFieldMap) { return columnFieldMap.entrySet().stream() .filter(entry -> getColumnByGridColumn(entry.getKey()) != null) .collect(Collectors.toMap( entry -> getColumnByGridColumn(entry.getKey()).getId(), entry -> ((DataGridEditorCustomField) entry.getValue()).getField()) ); } @Override public Subscription addEditorOpenListener(Consumer<EditorOpenEvent> listener) { if (editorOpenListener == null) { editorOpenListener = component.getEditor().addOpenListener(this::onEditorOpen); } return getEventHub().subscribe(EditorOpenEvent.class, listener); } protected void onEditorOpen(com.vaadin.ui.components.grid.EditorOpenEvent<E> editorOpenEvent) { //noinspection unchecked CubaEditorOpenEvent<E> event = ((CubaEditorOpenEvent) editorOpenEvent); Map<String, Field> fields = convertToCubaFields(event.getColumnFieldMap()); EditorOpenEvent<E> e = new EditorOpenEvent<>(this, event.getBean(), fields); publish(EditorOpenEvent.class, e); } @Override public void removeEditorOpenListener(Consumer<EditorOpenEvent> listener) { unsubscribe(EditorOpenEvent.class, listener); if (!hasSubscriptions(EditorOpenEvent.class)) { editorOpenListener.remove(); editorOpenListener = null; } } @Override public Subscription addEditorCloseListener(Consumer<EditorCloseEvent> listener) { if (editorCancelListener == null) { editorCancelListener = component.getEditor().addCancelListener(this::onEditorCancel); } return getEventHub().subscribe(EditorCloseEvent.class, listener); } protected void onEditorCancel(EditorCancelEvent<E> cancelEvent) { //noinspection unchecked CubaEditorCancelEvent<E> event = ((CubaEditorCancelEvent) cancelEvent); Map<String, Field> fields = convertToCubaFields(event.getColumnFieldMap()); EditorCloseEvent<E> e = new EditorCloseEvent<>(this, event.getBean(), fields); publish(EditorCloseEvent.class, e); } @Override public void removeEditorCloseListener(Consumer<EditorCloseEvent> listener) { unsubscribe(EditorCloseEvent.class, listener); if (!hasSubscriptions(EditorCloseEvent.class)) { editorCancelListener.remove(); editorCancelListener = null; } } @Override public Subscription addEditorPreCommitListener(Consumer<EditorPreCommitEvent> listener) { if (editorBeforeSaveListener == null) { //noinspection unchecked CubaEditorImpl<E> editor = (CubaEditorImpl) component.getEditor(); editorBeforeSaveListener = editor.addBeforeSaveListener(this::onEditorBeforeSave); } return getEventHub().subscribe(EditorPreCommitEvent.class, listener); } protected void onEditorBeforeSave(CubaEditorBeforeSaveEvent<E> event) { Map<String, Field> fields = convertToCubaFields(event.getColumnFieldMap()); EditorPreCommitEvent<E> e = new EditorPreCommitEvent<>(this, event.getBean(), fields); publish(EditorPreCommitEvent.class, e); } @Override public void removeEditorPreCommitListener(Consumer<EditorPreCommitEvent> listener) { unsubscribe(EditorPreCommitEvent.class, listener); if (!hasSubscriptions(EditorPreCommitEvent.class)) { editorBeforeSaveListener.remove(); editorBeforeSaveListener = null; } } @Override public Subscription addEditorPostCommitListener(Consumer<EditorPostCommitEvent> listener) { if (editorSaveListener == null) { editorSaveListener = component.getEditor().addSaveListener(this::onEditorSave); } return getEventHub().subscribe(EditorPostCommitEvent.class, listener); } @Override public void setEditorCrossFieldValidate(boolean validate) { this.editorCrossFieldValidate = validate; enableCrossFieldValidationHandling(validate); } @Override public boolean isEditorCrossFieldValidate() { return editorCrossFieldValidate; } protected void onEditorSave(EditorSaveEvent<E> saveEvent) { //noinspection unchecked CubaEditorSaveEvent<E> event = ((CubaEditorSaveEvent) saveEvent); Map<String, Field> fields = convertToCubaFields(event.getColumnFieldMap()); EditorPostCommitEvent<E> e = new EditorPostCommitEvent<>(this, event.getBean(), fields); publish(EditorPostCommitEvent.class, e); } @Override public void removeEditorPostCommitListener(Consumer<EditorPostCommitEvent> listener) { unsubscribe(EditorPostCommitEvent.class, listener); if (!hasSubscriptions(EditorPostCommitEvent.class)) { editorSaveListener.remove(); editorSaveListener = null; } } protected Datasource createItemDatasource(E item) { if (itemDatasources == null) { itemDatasources = new WeakHashMap<>(); } Object fieldDatasource = itemDatasources.get(item); if (fieldDatasource instanceof Datasource) { return (Datasource) fieldDatasource; } EntityDataGridItems<E> items = getEntityDataGridItemsNN(); Datasource datasource = DsBuilder.create() .setAllowCommit(false) .setMetaClass(items.getEntityMetaClass()) .setRefreshMode(CollectionDatasource.RefreshMode.NEVER) .setViewName(View.LOCAL) .buildDatasource(); ((DatasourceImplementation) datasource).valid(); //noinspection unchecked datasource.setItem(item); return datasource; } protected InstanceContainer<E> createInstanceContainer(E item) { if (itemDatasources == null) { itemDatasources = new WeakHashMap<>(); } Object container = itemDatasources.get(item); if (container instanceof InstanceContainer) { //noinspection unchecked return (InstanceContainer<E>) container; } EntityDataGridItems<E> items = getEntityDataGridItemsNN(); DataComponents factory = beanLocator.get(DataComponents.class); ViewRepository viewRepository = beanLocator.get(ViewRepository.NAME); MetaClass metaClass = items.getEntityMetaClass(); InstanceContainer<E> instanceContainer; if (metaClass instanceof KeyValueMetaClass) { //noinspection unchecked instanceContainer = (InstanceContainer<E>) new KeyValueContainerImpl((KeyValueMetaClass) metaClass); } else { instanceContainer = factory.createInstanceContainer(metaClass.getJavaClass()); } instanceContainer.setView(viewRepository.getView(metaClass, View.LOCAL)); instanceContainer.setItem(item); itemDatasources.put(item, instanceContainer); return instanceContainer; } protected void clearFieldDatasources(E item) { if (itemDatasources == null) { return; } if (item != null) { if (isEditorActive() && !isEditorBuffered() && item.equals(getEditedItem())) { return; } Object removed = itemDatasources.remove(item); if (removed != null) { detachItemContainer(removed); } } else { // detach instance containers from entities explicitly for (Map.Entry<E, Object> entry : itemDatasources.entrySet()) { detachItemContainer(entry.getValue()); } itemDatasources.clear(); } } @SuppressWarnings("unchecked") protected void detachItemContainer(Object container) { if (container instanceof InstanceContainer) { InstanceContainer<E> instanceContainer = (InstanceContainer<E>) container; instanceContainer.setItem(null); } else if (container instanceof Datasource) { Datasource<E> datasource = (Datasource<E>) container; datasource.setItem(null); } } protected ValueSourceProvider createValueSourceProvider(E item) { InstanceContainer<E> instanceContainer = createInstanceContainer(item); return new ContainerValueSourceProvider<>(instanceContainer); } protected static class WebDataGridEditorFieldFactory<E extends Entity> implements CubaGridEditorFieldFactory<E> { protected WebAbstractDataGrid<?, E> dataGrid; protected DataGridEditorFieldFactory fieldFactory; public WebDataGridEditorFieldFactory(WebAbstractDataGrid<?, E> dataGrid, DataGridEditorFieldFactory fieldFactory) { this.dataGrid = dataGrid; this.fieldFactory = fieldFactory; } @Override public CubaEditorField<?> createField(E bean, Grid.Column<E, ?> gridColumn) { ColumnImpl<E> column = dataGrid.getColumnByGridColumn(gridColumn); if (column == null || !column.isShouldBeEditable()) { return null; } Field columnComponent; if (column.getEditFieldGenerator() != null) { ValueSourceProvider valueSourceProvider = dataGrid.createValueSourceProvider(bean); EditorFieldGenerationContext<E> context = new EditorFieldGenerationContext<>(bean, valueSourceProvider); columnComponent = column.getEditFieldGenerator().apply(context); } else { String fieldPropertyId = String.valueOf(column.getPropertyId()); if (column.getEditorFieldGenerator() != null) { Datasource fieldDatasource = dataGrid.createItemDatasource(bean); columnComponent = column.getEditorFieldGenerator().createField(fieldDatasource, fieldPropertyId); } else { InstanceContainer<E> container = dataGrid.createInstanceContainer(bean); columnComponent = fieldFactory.createField( new ContainerValueSource<>(container, fieldPropertyId), fieldPropertyId); } } columnComponent.setParent(dataGrid); columnComponent.setFrame(dataGrid.getFrame()); return createCustomField(columnComponent); } protected CubaEditorField createCustomField(final Field columnComponent) { if (!(columnComponent instanceof Buffered)) { throw new IllegalArgumentException("Editor field must implement " + "com.haulmont.cuba.gui.components.Buffered"); } Component content = WebComponentsHelper.getComposition(columnComponent); //noinspection unchecked CubaEditorField wrapper = new DataGridEditorCustomField(columnComponent) { @Override protected Component initContent() { return content; } }; if (content instanceof Component.Focusable) { wrapper.setFocusDelegate((Component.Focusable) content); } wrapper.setReadOnly(!columnComponent.isEditable()); wrapper.setRequiredIndicatorVisible(columnComponent.isRequired()); //noinspection unchecked columnComponent.addValueChangeListener(event -> wrapper.markAsDirty()); return wrapper; } } protected static abstract class DataGridEditorCustomField<T> extends CubaEditorField<T> { protected Field<T> columnComponent; public DataGridEditorCustomField(Field<T> columnComponent) { this.columnComponent = columnComponent; initComponent(this.columnComponent); } protected void initComponent(Field<T> columnComponent) { columnComponent.addValueChangeListener(event -> fireEvent(createValueChange(event.getPrevValue(), event.isUserOriginated()))); } protected Field getField() { return columnComponent; } @Override protected void doSetValue(T value) { columnComponent.setValue(value); } @Override public T getValue() { return columnComponent.getValue(); } @Override public boolean isBuffered() { return ((Buffered) columnComponent).isBuffered(); } @Override public void setBuffered(boolean buffered) { ((Buffered) columnComponent).setBuffered(buffered); } @Override public void commit() { ((Buffered) columnComponent).commit(); } @Override public ValidationResult validate() { try { columnComponent.validate(); return ValidationResult.ok(); } catch (ValidationException e) { return ValidationResult.error(e.getDetailsMessage()); } } @Override public void discard() { ((Buffered) columnComponent).discard(); } @Override public boolean isModified() { return ((Buffered) columnComponent).isModified(); } @Override public void setWidth(float width, Unit unit) { super.setWidth(width, unit); if (getContent() != null) { if (width < 0) { getContent().setWidthUndefined(); } else { getContent().setWidth(100, Unit.PERCENTAGE); } } } @Override public void setHeight(float height, Unit unit) { super.setHeight(height, unit); if (getContent() != null) { if (height < 0) { getContent().setHeightUndefined(); } else { getContent().setHeight(100, Unit.PERCENTAGE); } } } } @Override public boolean isHeaderVisible() { return component.isHeaderVisible(); } @Override public void setHeaderVisible(boolean headerVisible) { component.setHeaderVisible(headerVisible); } @Override public boolean isFooterVisible() { return component.isFooterVisible(); } @Override public void setFooterVisible(boolean footerVisible) { component.setFooterVisible(footerVisible); } @Override public double getBodyRowHeight() { return component.getBodyRowHeight(); } @Override public void setBodyRowHeight(double rowHeight) { component.setBodyRowHeight(rowHeight); } @Override public double getHeaderRowHeight() { return component.getHeaderRowHeight(); } @Override public void setHeaderRowHeight(double rowHeight) { component.setHeaderRowHeight(rowHeight); } @Override public double getFooterRowHeight() { return component.getFooterRowHeight(); } @Override public void setFooterRowHeight(double rowHeight) { component.setFooterRowHeight(rowHeight); } @Override public boolean isContextMenuEnabled() { return contextMenu.isEnabled(); } @Override public void setContextMenuEnabled(boolean contextMenuEnabled) { contextMenu.setEnabled(contextMenuEnabled); } @Override public ColumnResizeMode getColumnResizeMode() { return WebWrapperUtils.convertToDataGridColumnResizeMode(component.getColumnResizeMode()); } @Override public void setColumnResizeMode(ColumnResizeMode mode) { component.setColumnResizeMode(WebWrapperUtils.convertToGridColumnResizeMode(mode)); } @Override public SelectionMode getSelectionMode() { return selectionMode; } @Override public void setSelectionMode(SelectionMode selectionMode) { this.selectionMode = selectionMode; switch (selectionMode) { case SINGLE: component.setGridSelectionModel(new CubaSingleSelectionModel<>()); break; case MULTI: component.setGridSelectionModel(new CubaMultiSelectionModel<>()); break; case MULTI_CHECK: component.setGridSelectionModel(new CubaMultiCheckSelectionModel<>()); break; case NONE: component.setSelectionMode(Grid.SelectionMode.NONE); return; } // Every time we change selection mode, the new selection model is set, // so we need to add selection listener again. component.getSelectionModel().addSelectionListener(this::onSelectionChange); } @Override public boolean isMultiSelect() { return SelectionMode.MULTI.equals(selectionMode) || SelectionMode.MULTI_CHECK.equals(selectionMode); } @Nullable @Override public E getSingleSelected() { return component.getSelectionModel() .getFirstSelectedItem() .orElse(null); } @Override public Set<E> getSelected() { return component.getSelectedItems(); } @Override public void setSelected(@Nullable E item) { if (SelectionMode.NONE.equals(getSelectionMode())) { return; } if (item == null) { component.deselectAll(); } else { setSelected(Collections.singletonList(item)); } } @Override public void setSelected(Collection<E> items) { DataGridItems<E> dataGridItems = getDataGridItemsNN(); for (E item : items) { if (!dataGridItems.containsItem(item)) { throw new IllegalStateException("Datasource doesn't contain items"); } } setSelectedItems(items); } @SuppressWarnings("unchecked") protected void setSelectedItems(Collection<E> items) { switch (selectionMode) { case SINGLE: if (items.size() > 0) { E item = items.iterator().next(); component.getSelectionModel().select(item); } else { component.deselectAll(); } break; case MULTI: case MULTI_CHECK: component.deselectAll(); ((SelectionModel.Multi) component.getSelectionModel()).selectItems(items.toArray()); break; default: throw new UnsupportedOperationException("Unsupported selection mode"); } } @Override public void selectAll() { if (isMultiSelect()) { ((SelectionModel.Multi) component.getSelectionModel()).selectAll(); } } @Override public void deselect(E item) { checkNotNullArgument(item); component.deselect(item); } @Override public void deselectAll() { component.deselectAll(); } @Override public void sort(String columnId, SortDirection direction) { ColumnImpl<E> column = (ColumnImpl<E>) getColumnNN(columnId); component.sort(column.getGridColumn(), WebWrapperUtils.convertToGridSortDirection(direction)); } @Override public List<SortOrder> getSortOrder() { return convertToDataGridSortOrder(component.getSortOrder()); } protected List<SortOrder> convertToDataGridSortOrder(List<GridSortOrder<E>> gridSortOrder) { if (CollectionUtils.isEmpty(gridSortOrder)) { return Collections.emptyList(); } return gridSortOrder.stream() .map(sortOrder -> { Column column = getColumnByGridColumn(sortOrder.getSorted()); return new SortOrder(column != null ? column.getId() : null, WebWrapperUtils.convertToDataGridSortDirection(sortOrder.getDirection())); }) .collect(Collectors.toList()); } @Override public void addAction(Action action) { int index = findActionById(actionList, action.getId()); if (index < 0) { index = actionList.size(); } addAction(action, index); } @Override public void addAction(Action action, int index) { checkNotNullArgument(action, "Action must be non null"); int oldIndex = findActionById(actionList, action.getId()); if (oldIndex >= 0) { removeAction(actionList.get(oldIndex)); if (index > oldIndex) { index--; } } if (StringUtils.isNotEmpty(action.getCaption())) { ActionMenuItemWrapper menuItemWrapper = createContextMenuItem(action); menuItemWrapper.setAction(action); contextMenuItems.add(menuItemWrapper); } actionList.add(index, action); shortcutsDelegate.addAction(null, action); attachAction(action); actionsPermissions.apply(action); } protected ActionMenuItemWrapper createContextMenuItem(Action action) { MenuItem menuItem = contextMenu.addItem(action.getCaption(), null); menuItem.setStyleName("c-cm-item"); return new ActionMenuItemWrapper(menuItem, showIconsForPopupMenuActions) { @Override public void performAction(Action action) { action.actionPerform(WebAbstractDataGrid.this); } }; } protected void attachAction(Action action) { if (action instanceof Action.HasTarget) { ((Action.HasTarget) action).setTarget(this); } action.refreshState(); } @Override public void removeAction(@Nullable Action action) { if (actionList.remove(action)) { ActionMenuItemWrapper menuItemWrapper = null; for (ActionMenuItemWrapper menuItem : contextMenuItems) { if (menuItem.getAction() == action) { menuItemWrapper = menuItem; break; } } if (menuItemWrapper != null) { menuItemWrapper.setAction(null); contextMenu.removeItem(menuItemWrapper.getMenuItem()); } shortcutsDelegate.removeAction(action); } } @Override public void removeAction(@Nullable String id) { Action action = getAction(id); if (action != null) { removeAction(action); } } @Override public void removeAllActions() { for (Action action : actionList.toArray(new Action[0])) { removeAction(action); } } @Override public Collection<Action> getActions() { return Collections.unmodifiableCollection(actionList); } @Nullable @Override public Action getAction(String id) { for (Action action : getActions()) { if (Objects.equals(action.getId(), id)) { return action; } } return null; } @Override public ActionsPermissions getActionsPermissions() { return actionsPermissions; } protected List<Column<E>> getInitialVisibleColumns() { MetaClass metaClass = getEntityDataGridItems().getEntityMetaClass(); return columnsOrder.stream() .filter(column -> { MetaPropertyPath propertyPath = column.getPropertyPath(); return propertyPath == null || security.isEntityAttrReadPermitted(metaClass, propertyPath.toString()); }) .collect(Collectors.toList()); } @Override public Component getComposition() { return componentComposition; } @Override public int getFrozenColumnCount() { return component.getFrozenColumnCount(); } @Override public void setFrozenColumnCount(int numberOfColumns) { component.setFrozenColumnCount(numberOfColumns); } @Override public void scrollTo(E item) { scrollTo(item, ScrollDestination.ANY); } @Override public void scrollTo(E item, ScrollDestination destination) { Preconditions.checkNotNullArgument(item); Preconditions.checkNotNullArgument(destination); DataGridItems<E> dataGridItems = getDataGridItemsNN(); if (!dataGridItems.containsItem(item)) { throw new IllegalArgumentException("Unable to find item in DataGrid"); } int rowIndex = dataGridItems.indexOfItem(item); component.scrollTo(rowIndex, WebWrapperUtils.convertToGridScrollDestination(destination)); } @Override public void scrollToStart() { component.scrollToStart(); } @Override public void scrollToEnd() { component.scrollToEnd(); } @Override public void repaint() { component.repaint(); } protected boolean canBeSorted(@Nullable DataGridItems<E> dataGridItems) { return dataGridItems instanceof DataGridItems.Sortable; } @Override public void setDebugId(String id) { super.setDebugId(id); AppUI ui = AppUI.getCurrent(); if (id != null && ui != null) { componentComposition.setId(ui.getTestIdManager().getTestId(id + "_composition")); } } @Override public void setId(String id) { super.setId(id); AppUI ui = AppUI.getCurrent(); if (id != null && ui != null && ui.isTestMode()) { componentComposition.setCubaId(id + "_composition"); } } @Override public void setStyleName(String name) { super.setStyleName(name); internalStyles.forEach(internalStyle -> componentComposition.addStyleName(internalStyle)); } @Override public ButtonsPanel getButtonsPanel() { return buttonsPanel; } @Override public void setButtonsPanel(ButtonsPanel panel) { if (buttonsPanel != null && topPanel != null) { topPanel.removeComponent(WebComponentsHelper.unwrap(buttonsPanel)); buttonsPanel.setParent(null); } buttonsPanel = panel; if (panel != null) { if (panel.getParent() != null && panel.getParent() != this) { throw new IllegalStateException("Component already has parent"); } if (topPanel == null) { topPanel = createTopPanel(); componentComposition.addComponentAsFirst(topPanel); } topPanel.addComponent(WebComponentsHelper.unwrap(panel)); if (panel instanceof VisibilityChangeNotifier) { ((VisibilityChangeNotifier) panel).addVisibilityChangeListener(event -> updateCompositionStylesTopPanelVisible() ); } panel.setParent(this); } updateCompositionStylesTopPanelVisible(); } @Override public RowsCount getRowsCount() { return rowsCount; } @Override public void setRowsCount(RowsCount rowsCount) { if (this.rowsCount != null && topPanel != null) { topPanel.removeComponent(WebComponentsHelper.unwrap(this.rowsCount)); this.rowsCount.setParent(null); } this.rowsCount = rowsCount; if (rowsCount != null) { if (rowsCount.getParent() != null && rowsCount.getParent() != this) { throw new IllegalStateException("Component already has parent"); } if (topPanel == null) { topPanel = createTopPanel(); componentComposition.addComponentAsFirst(topPanel); } Component rc = WebComponentsHelper.unwrap(rowsCount); topPanel.addComponent(rc); if (rowsCount instanceof VisibilityChangeNotifier) { ((VisibilityChangeNotifier) rowsCount).addVisibilityChangeListener(event -> updateCompositionStylesTopPanelVisible() ); } } updateCompositionStylesTopPanelVisible(); } protected HorizontalLayout createTopPanel() { HorizontalLayout topPanel = new HorizontalLayout(); topPanel.setMargin(false); topPanel.setSpacing(false); topPanel.setStyleName("c-data-grid-top"); return topPanel; } // if buttons panel becomes hidden we need to set top panel height to 0 protected void updateCompositionStylesTopPanelVisible() { if (topPanel != null) { boolean hasChildren = topPanel.getComponentCount() > 0; boolean anyChildVisible = false; for (Component childComponent : topPanel) { if (childComponent.isVisible()) { anyChildVisible = true; break; } } boolean topPanelVisible = hasChildren && anyChildVisible; if (!topPanelVisible) { componentComposition.removeStyleName(HAS_TOP_PANEL_STYLE_NAME); internalStyles.remove(HAS_TOP_PANEL_STYLE_NAME); } else { componentComposition.addStyleName(HAS_TOP_PANEL_STYLE_NAME); if (!internalStyles.contains(HAS_TOP_PANEL_STYLE_NAME)) { internalStyles.add(HAS_TOP_PANEL_STYLE_NAME); } } } } @Override public Action getEnterPressAction() { return enterPressAction; } @Override public void setEnterPressAction(Action action) { enterPressAction = action; } @Override public Action getItemClickAction() { return itemClickAction; } @Override public void setItemClickAction(Action action) { if (itemClickAction != null) { removeAction(itemClickAction); } itemClickAction = action; if (!getActions().contains(action)) { addAction(action); } } @Override public void applySettings(Element element) { if (!isSettingsEnabled()) { return; } if (defaultSettings == null) { defaultSettings = DocumentHelper.createDocument(); defaultSettings.setRootElement(defaultSettings.addElement("presentation")); // init default settings saveSettings(defaultSettings.getRootElement()); } Element columnsElem = element.element("columns"); if (columnsElem != null) { List<Column<E>> modelColumns = getVisibleColumns(); List<String> modelIds = modelColumns.stream() .map(String::valueOf) .collect(Collectors.toList()); List<String> loadedIds = columnsElem.elements("columns").stream() .map(colElem -> colElem.attributeValue("id")) .collect(Collectors.toList()); if (CollectionUtils.isEqualCollection(modelIds, loadedIds)) { applyColumnSettings(element, modelColumns); } } } public void applyDataLoadingSettings(Element element) { if (!isSettingsEnabled()) { return; } if (isSortable() && isApplyDataLoadingSettings()) { Element columnsElem = element.element("columns"); if (columnsElem != null) { String sortColumnId = columnsElem.attributeValue("sortColumnId"); if (!StringUtils.isEmpty(sortColumnId)) { Grid.Column<E, ?> column = component.getColumn(sortColumnId); if (column != null) { if (getItems() instanceof DataGridItems.Sortable) { ((DataGridItems.Sortable<E>) getItems()).suppressSorting(); } try { component.clearSortOrder(); String sortDirection = columnsElem.attributeValue("sortDirection"); if (StringUtils.isNotEmpty(sortDirection)) { List<GridSortOrder<E>> sortOrders = Collections.singletonList(new GridSortOrder<>(column, com.vaadin.shared.data.sort.SortDirection.valueOf(sortDirection)) ); component.setSortOrder(sortOrders); } } finally { if (getItems() instanceof DataGridItems.Sortable) { ((DataGridItems.Sortable<E>) getItems()).enableSorting(); } } } } } } } protected void applyColumnSettings(Element element, Collection<Column<E>> oldColumns) { Element columnsElem = element.element("columns"); List<Column<E>> newColumns = new ArrayList<>(); // add columns from saved settings for (Element colElem : columnsElem.elements("columns")) { for (Column<E> column : oldColumns) { if (column.getId().equals(colElem.attributeValue("id"))) { newColumns.add(column); String width = colElem.attributeValue("width"); if (width != null) { column.setWidth(Double.parseDouble(width)); } else { column.setWidthAuto(); } String collapsed = colElem.attributeValue("collapsed"); if (collapsed != null && component.isColumnReorderingAllowed()) { column.setCollapsed(Boolean.parseBoolean(collapsed)); } break; } } } // add columns not saved in settings (perhaps new) for (Column<E> column : oldColumns) { if (!newColumns.contains(column)) { newColumns.add(column); } } // if the data grid contains only one column, always show it if (newColumns.size() == 1) { newColumns.get(0).setCollapsed(false); } // We don't save settings for columns hidden by security permissions, // so we need to return them back to they initial positions columnsOrder = restoreColumnsOrder(newColumns); component.setColumnOrder(newColumns.stream() .map(Column::getId) .toArray(String[]::new)); if (isSortable() && !isApplyDataLoadingSettings()) { // apply sorting component.clearSortOrder(); String sortColumnId = columnsElem.attributeValue("sortColumnId"); if (!StringUtils.isEmpty(sortColumnId)) { Grid.Column<E, ?> column = component.getColumn(sortColumnId); if (column != null) { String sortDirection = columnsElem.attributeValue("sortDirection"); if (StringUtils.isNotEmpty(sortDirection)) { List<GridSortOrder<E>> sortOrders = Collections.singletonList(new GridSortOrder<>(column, com.vaadin.shared.data.sort.SortDirection.valueOf(sortDirection)) ); component.setSortOrder(sortOrders); } } } } } protected boolean isApplyDataLoadingSettings() { DataGridItems<E> tableItems = getItems(); if (tableItems instanceof ContainerDataUnit) { CollectionContainer container = ((ContainerDataUnit) tableItems).getContainer(); return container instanceof HasLoader && ((HasLoader) container).getLoader() instanceof CollectionLoader; } return false; } @Override public boolean saveSettings(Element element) { if (!isSettingsEnabled()) { return false; } Element columnsElem = element.element("columns"); String sortColumnId = null; String sortDirection = null; if (columnsElem != null) { sortColumnId = columnsElem.attributeValue("sortColumnId"); sortDirection = columnsElem.attributeValue("sortDirection"); } boolean commonSettingsChanged = isCommonDataGridSettingsChanged(columnsElem); boolean sortChanged = isSortPropertySettingsChanged(sortColumnId, sortDirection); boolean settingsChanged = commonSettingsChanged || sortChanged; if (settingsChanged) { if (columnsElem != null) { element.remove(columnsElem); } columnsElem = element.addElement("columns"); List<Column<E>> visibleColumns = getVisibleColumns(); for (Column<E> column : visibleColumns) { Element colElem = columnsElem.addElement("columns"); colElem.addAttribute("id", column.toString()); double width = column.getWidth(); if (width > -1) { colElem.addAttribute("width", String.valueOf(width)); } colElem.addAttribute("collapsed", Boolean.toString(column.isCollapsed())); } List<GridSortOrder<E>> sortOrders = component.getSortOrder(); if (!sortOrders.isEmpty()) { GridSortOrder<E> sortOrder = sortOrders.get(0); columnsElem.addAttribute("sortColumnId", sortOrder.getSorted().getId()); columnsElem.addAttribute("sortDirection", sortOrder.getDirection().toString()); } } return settingsChanged; } protected boolean isCommonDataGridSettingsChanged(Element columnsElem) { if (columnsElem == null) { if (defaultSettings != null) { columnsElem = defaultSettings.getRootElement().element("columns"); if (columnsElem == null) { return true; } } else { return false; } } List<Element> settingsColumnList = columnsElem.elements("columns"); List<Column<E>> visibleColumns = getVisibleColumns(); if (settingsColumnList.size() != visibleColumns.size()) { return true; } for (int i = 0; i < visibleColumns.size(); i++) { Object columnId = visibleColumns.get(i).getId(); Element settingsColumn = settingsColumnList.get(i); String settingsColumnId = settingsColumn.attributeValue("id"); if (columnId.toString().equals(settingsColumnId)) { double columnWidth = visibleColumns.get(i).getWidth(); String settingsColumnWidth = settingsColumn.attributeValue("width"); double settingColumnWidth = settingsColumnWidth == null ? -1 : Double.parseDouble(settingsColumnWidth); if (columnWidth != settingColumnWidth) { return true; } boolean columnCollapsed = visibleColumns.get(i).isCollapsed(); boolean settingsColumnCollapsed = Boolean.parseBoolean(settingsColumn.attributeValue("collapsed")); if (columnCollapsed != settingsColumnCollapsed) { return true; } } else { return true; } } return false; } protected boolean isSortPropertySettingsChanged(String settingsSortColumnId, String settingsSortDirection) { List<GridSortOrder<E>> sortOrders = component.getSortOrder(); String columnId = null; String sortDirection = null; if (!sortOrders.isEmpty()) { GridSortOrder<E> sortOrder = sortOrders.get(0); columnId = sortOrder.getSorted().getId(); sortDirection = sortOrder.getDirection().toString(); } if (!Objects.equals(columnId, settingsSortColumnId) || !Objects.equals(sortDirection, settingsSortDirection)) { return true; } return false; } @Nullable protected ColumnImpl<E> getColumnByGridColumn(Grid.Column<E, ?> gridColumn) { for (Column<E> column : getColumns()) { ColumnImpl<E> columnImpl = (ColumnImpl<E>) column; if (columnImpl.getGridColumn() == gridColumn) { return columnImpl; } } return null; } @Nullable protected Column<E> getColumnById(Object id) { for (Column<E> column : getColumns()) { String columnId = column.getId(); if (Objects.equals(columnId, id)) { return column; } } return null; } @Override public boolean isSettingsEnabled() { return settingsEnabled; } @Override public void setSettingsEnabled(boolean settingsEnabled) { this.settingsEnabled = settingsEnabled; } @Override public void addRowStyleProvider(Function<? super E, String> styleProvider) { if (this.rowStyleProviders == null) { this.rowStyleProviders = new LinkedList<>(); } if (!this.rowStyleProviders.contains(styleProvider)) { this.rowStyleProviders.add(styleProvider); repaint(); } } @Override public void removeRowStyleProvider(Function<? super E, String> styleProvider) { if (this.rowStyleProviders != null) { if (this.rowStyleProviders.remove(styleProvider)) { repaint(); } } } @Override public void addCellStyleProvider(CellStyleProvider<? super E> styleProvider) { if (this.cellStyleProviders == null) { this.cellStyleProviders = new LinkedList<>(); } if (!this.cellStyleProviders.contains(styleProvider)) { this.cellStyleProviders.add(styleProvider); repaint(); } } @Override public void removeCellStyleProvider(CellStyleProvider<? super E> styleProvider) { if (this.cellStyleProviders != null) { if (this.cellStyleProviders.remove(styleProvider)) { repaint(); } } } @SuppressWarnings("unchecked") @Override public CellDescriptionProvider<E> getCellDescriptionProvider() { return (CellDescriptionProvider<E>) cellDescriptionProvider; } @Override public void setCellDescriptionProvider(CellDescriptionProvider<? super E> provider) { this.cellDescriptionProvider = provider; repaint(); } @SuppressWarnings("unchecked") @Override public Function<E, String> getRowDescriptionProvider() { return (Function<E, String>) rowDescriptionProvider; } @Override public void setRowDescriptionProvider(Function<? super E, String> provider) { setRowDescriptionProvider(provider, ContentMode.PREFORMATTED); } @Override public void setRowDescriptionProvider(Function<? super E, String> provider, ContentMode contentMode) { this.rowDescriptionProvider = provider; if (provider != null) { component.setDescriptionGenerator(this::getRowDescription, WebWrapperUtils.toVaadinContentMode(contentMode)); } else { component.setDescriptionGenerator(null); } } protected String getRowDescription(E item) { return rowDescriptionProvider.apply(item); } @Override public Column<E> addGeneratedColumn(String columnId, ColumnGenerator<E, ?> generator) { return addGeneratedColumn(columnId, generator, columnsOrder.size()); } @SuppressWarnings("unchecked") @Override public Column<E> addGeneratedColumn(String columnId, GenericColumnGenerator<E, ?> generator) { Column<E> column = getColumn(columnId); if (column == null) { throw new DevelopmentException("Unable to set ColumnGenerator for non-existing column: " + columnId); } Class<? extends Renderer> rendererType = null; Renderer renderer = column.getRenderer(); if (renderer != null) { Class<?>[] rendererInterfaces = renderer.getClass().getInterfaces(); rendererType = (Class<? extends Renderer>) Arrays.stream(rendererInterfaces) .filter(Renderer.class::isAssignableFrom) .findFirst() .orElseThrow(() -> new DevelopmentException( "Renderer should be specified explicitly for generated column: " + columnId)); } Column<E> generatedColumn = addGeneratedColumn(columnId, new ColumnGenerator<E, Object>() { @Override public Object getValue(ColumnGeneratorEvent<E> event) { return generator.getValue(event); } @Override public Class<Object> getType() { return column.getGeneratedType(); } }); if (renderer != null) { generatedColumn.setRenderer(createRenderer(rendererType)); } return column; } @Override public Column<E> addGeneratedColumn(String columnId, ColumnGenerator<E, ?> generator, int index) { checkNotNullArgument(columnId, "columnId is null"); checkNotNullArgument(generator, "generator is null for column id '%s'", columnId); Column<E> existingColumn = getColumn(columnId); if (existingColumn != null) { index = columnsOrder.indexOf(existingColumn); removeColumn(existingColumn); } Grid.Column<E, Object> generatedColumn = component.addColumn(createGeneratedColumnValueProvider(columnId, generator)); ColumnImpl<E> column = new ColumnImpl<>(columnId, generator.getType(), this); if (existingColumn != null) { copyColumnProperties(column, existingColumn); } else { column.setCaption(columnId); } column.setGenerated(true); columns.put(column.getId(), column); columnsOrder.add(index, column); columnGenerators.put(column.getId(), generator); setupGridColumnProperties(generatedColumn, column); component.setColumnOrder(getColumnOrder()); return column; } protected ValueProvider<E, Object> createGeneratedColumnValueProvider(String columnId, ColumnGenerator<E, ?> generator) { return (ValueProvider<E, Object>) item -> { ColumnGeneratorEvent<E> event = new ColumnGeneratorEvent<>(WebAbstractDataGrid.this, item, columnId, this::createInstanceContainer); return generator.getValue(event); }; } @Override public ColumnGenerator<E, ?> getColumnGenerator(String columnId) { return columnGenerators.get(columnId); } protected void copyColumnProperties(Column<E> column, Column<E> existingColumn) { column.setCaption(existingColumn.getCaption()); column.setVisible(existingColumn.isVisible()); column.setCollapsed(existingColumn.isCollapsed()); column.setCollapsible(existingColumn.isCollapsible()); column.setCollapsingToggleCaption(existingColumn.getCollapsingToggleCaption()); column.setMinimumWidth(existingColumn.getMinimumWidth()); column.setMaximumWidth(existingColumn.getMaximumWidth()); column.setWidth(existingColumn.getWidth()); column.setExpandRatio(existingColumn.getExpandRatio()); column.setResizable(existingColumn.isResizable()); column.setFormatter(existingColumn.getFormatter()); column.setStyleProvider(existingColumn.getStyleProvider()); column.setDescriptionProvider(existingColumn.getDescriptionProvider(), ((ColumnImpl) existingColumn).getDescriptionContentMode()); } @Override public <T extends Renderer> T createRenderer(Class<T> type) { Class<? extends Renderer> rendererClass = rendererClasses.get(type); if (rendererClass == null) { throw new IllegalArgumentException( String.format("Can't find renderer class for '%s'", type.getTypeName())); } Constructor<? extends Renderer> constructor; try { constructor = rendererClass.getConstructor(); } catch (NoSuchMethodException e) { throw new RuntimeException(String.format("Error creating the '%s' renderer instance", type.getTypeName()), e); } try { Renderer instance = constructor.newInstance(); autowireContext(instance); return type.cast(instance); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(String.format("Error creating the '%s' renderer instance", type.getTypeName()), e); } } protected void autowireContext(Renderer instance) { AutowireCapableBeanFactory autowireBeanFactory = applicationContext.getAutowireCapableBeanFactory(); autowireBeanFactory.autowireBean(instance); if (instance instanceof ApplicationContextAware) { ((ApplicationContextAware) instance).setApplicationContext(applicationContext); } if (instance instanceof InitializingBean) { try { ((InitializingBean) instance).afterPropertiesSet(); } catch (Exception e) { throw new RuntimeException("Unable to initialize Renderer - calling afterPropertiesSet for " + instance.getClass(), e); } } } @Override public Subscription addColumnCollapsingChangeListener(Consumer<ColumnCollapsingChangeEvent> listener) { if (columnCollapsingChangeListenerRegistration == null) { columnCollapsingChangeListenerRegistration = component.addColumnVisibilityChangeListener(this::onColumnVisibilityChanged); } getEventHub().subscribe(ColumnCollapsingChangeEvent.class, listener); return () -> removeColumnCollapsingChangeListener(listener); } protected void onColumnVisibilityChanged(Grid.ColumnVisibilityChangeEvent e) { // Due to vaadin/framework#11419, // we discard events with UserOriginated == false. if (!e.isUserOriginated()) { return; } //noinspection unchecked ColumnCollapsingChangeEvent event = new ColumnCollapsingChangeEvent(WebAbstractDataGrid.this, getColumnByGridColumn((Grid.Column<E, ?>) e.getColumn()), e.isHidden(), e.isUserOriginated()); publish(ColumnCollapsingChangeEvent.class, event); } @Override public void removeColumnCollapsingChangeListener(Consumer<ColumnCollapsingChangeEvent> listener) { unsubscribe(ColumnCollapsingChangeEvent.class, listener); if (!hasSubscriptions(ColumnCollapsingChangeEvent.class) && columnCollapsingChangeListenerRegistration != null) { columnCollapsingChangeListenerRegistration.remove(); columnCollapsingChangeListenerRegistration = null; } } @Override public Subscription addColumnResizeListener(Consumer<ColumnResizeEvent> listener) { if (columnResizeListenerRegistration == null) { columnResizeListenerRegistration = component.addColumnResizeListener(this::onColumnResize); } getEventHub().subscribe(ColumnResizeEvent.class, listener); return () -> removeColumnResizeListener(listener); } protected void onColumnResize(Grid.ColumnResizeEvent e) { //noinspection unchecked ColumnResizeEvent event = new ColumnResizeEvent(WebAbstractDataGrid.this, getColumnByGridColumn((Grid.Column<E, ?>) e.getColumn()), e.isUserOriginated()); publish(ColumnResizeEvent.class, event); } @Override public void removeColumnResizeListener(Consumer<ColumnResizeEvent> listener) { unsubscribe(ColumnResizeEvent.class, listener); if (!hasSubscriptions(ColumnResizeEvent.class) && columnResizeListenerRegistration != null) { columnResizeListenerRegistration.remove(); columnResizeListenerRegistration = null; } } @Override public Subscription addSortListener(Consumer<SortEvent> listener) { return getEventHub().subscribe(SortEvent.class, listener); } @Override public void removeSortListener(Consumer<SortEvent> listener) { unsubscribe(SortEvent.class, listener); } @Override public Subscription addColumnReorderListener(Consumer<ColumnReorderEvent> listener) { return getEventHub().subscribe(ColumnReorderEvent.class, listener); } @Override public void removeColumnReorderListener(Consumer<ColumnReorderEvent> listener) { unsubscribe(ColumnReorderEvent.class, listener); } @SuppressWarnings("unchecked") @Override public Subscription addSelectionListener(Consumer<SelectionEvent<E>> listener) { return getEventHub().subscribe(SelectionEvent.class, (Consumer) listener); } @SuppressWarnings("unchecked") @Override public void removeSelectionListener(Consumer<SelectionEvent<E>> listener) { unsubscribe(SelectionEvent.class, (Consumer) listener); } @SuppressWarnings("unchecked") @Override public Subscription addItemClickListener(Consumer<ItemClickEvent<E>> listener) { return getEventHub().subscribe(ItemClickEvent.class, (Consumer) listener); } @SuppressWarnings("unchecked") @Override public void removeItemClickListener(Consumer<ItemClickEvent<E>> listener) { unsubscribe(ItemClickEvent.class, (Consumer) listener); } @Override public Subscription addContextClickListener(Consumer<ContextClickEvent> listener) { if (contextClickListenerRegistration == null) { contextClickListenerRegistration = component.addContextClickListener(this::onContextClick); } return getEventHub().subscribe(ContextClickEvent.class, listener); } protected void onContextClick(com.vaadin.event.ContextClickEvent e) { MouseEventDetails mouseEventDetails = WebWrapperUtils.toMouseEventDetails(e); ContextClickEvent event = new ContextClickEvent(WebAbstractDataGrid.this, mouseEventDetails); publish(ContextClickEvent.class, event); } @Override public void removeContextClickListener(Consumer<ContextClickEvent> listener) { unsubscribe(ContextClickEvent.class, listener); if (!hasSubscriptions(ContextClickEvent.class) && contextClickListenerRegistration != null) { contextClickListenerRegistration.remove(); contextClickListenerRegistration = null; } } @SuppressWarnings("unchecked") @Override public Subscription addLookupValueChangeListener(Consumer<LookupSelectionChangeEvent<E>> listener) { return getEventHub().subscribe(LookupSelectionChangeEvent.class, (Consumer) listener); } @SuppressWarnings("unchecked") @Override public void removeLookupValueChangeListener(Consumer<LookupSelectionChangeEvent<E>> listener) { unsubscribe(LookupSelectionChangeEvent.class, (Consumer) listener); } @Override public HeaderRow getHeaderRow(int index) { return getHeaderRowByGridRow(component.getHeaderRow(index)); } @Nullable protected HeaderRow getHeaderRowByGridRow(com.vaadin.ui.components.grid.HeaderRow gridRow) { for (HeaderRow headerRow : headerRows) { if (((HeaderRowImpl) headerRow).getGridRow() == gridRow) { return headerRow; } } return null; } @Override public HeaderRow appendHeaderRow() { com.vaadin.ui.components.grid.HeaderRow headerRow = component.appendHeaderRow(); return addHeaderRowInternal(headerRow); } @Override public HeaderRow prependHeaderRow() { com.vaadin.ui.components.grid.HeaderRow headerRow = component.prependHeaderRow(); return addHeaderRowInternal(headerRow); } @Override public HeaderRow addHeaderRowAt(int index) { com.vaadin.ui.components.grid.HeaderRow headerRow = component.addHeaderRowAt(index); return addHeaderRowInternal(headerRow); } protected HeaderRow addHeaderRowInternal(com.vaadin.ui.components.grid.HeaderRow headerRow) { HeaderRowImpl rowImpl = new HeaderRowImpl(this, (Header.Row) headerRow); headerRows.add(rowImpl); return rowImpl; } @Override public void removeHeaderRow(HeaderRow headerRow) { if (headerRow == null || !headerRows.contains(headerRow)) { return; } component.removeHeaderRow(((HeaderRowImpl) headerRow).getGridRow()); headerRows.remove(headerRow); } @Override public void removeHeaderRow(int index) { HeaderRow headerRow = getHeaderRow(index); removeHeaderRow(headerRow); } @Override public HeaderRow getDefaultHeaderRow() { return getHeaderRowByGridRow(component.getDefaultHeaderRow()); } @Override public void setDefaultHeaderRow(HeaderRow headerRow) { component.setDefaultHeaderRow(((HeaderRowImpl) headerRow).getGridRow()); } @Override public int getHeaderRowCount() { return component.getHeaderRowCount(); } @Override public FooterRow getFooterRow(int index) { return getFooterRowByGridRow(component.getFooterRow(index)); } @Nullable protected FooterRow getFooterRowByGridRow(com.vaadin.ui.components.grid.FooterRow gridRow) { for (FooterRow footerRow : footerRows) { if (((FooterRowImpl) footerRow).getGridRow() == gridRow) { return footerRow; } } return null; } @Override public FooterRow appendFooterRow() { com.vaadin.ui.components.grid.FooterRow footerRow = component.appendFooterRow(); return addFooterRowInternal(footerRow); } @Override public FooterRow prependFooterRow() { com.vaadin.ui.components.grid.FooterRow footerRow = component.prependFooterRow(); return addFooterRowInternal(footerRow); } @Override public FooterRow addFooterRowAt(int index) { com.vaadin.ui.components.grid.FooterRow footerRow = component.addFooterRowAt(index); return addFooterRowInternal(footerRow); } protected FooterRow addFooterRowInternal(com.vaadin.ui.components.grid.FooterRow footerRow) { FooterRowImpl rowImpl = new FooterRowImpl(this, (Footer.Row) footerRow); footerRows.add(rowImpl); return rowImpl; } @Override public void removeFooterRow(FooterRow footerRow) { if (footerRow == null || !footerRows.contains(footerRow)) { return; } component.removeFooterRow(((FooterRowImpl) footerRow).getGridRow()); footerRows.remove(footerRow); } @Override public void removeFooterRow(int index) { FooterRow footerRow = getFooterRow(index); removeFooterRow(footerRow); } @Override public int getFooterRowCount() { return component.getFooterRowCount(); } @Nullable @Override public DetailsGenerator<E> getDetailsGenerator() { return detailsGenerator; } @Override public void setDetailsGenerator(DetailsGenerator<E> detailsGenerator) { this.detailsGenerator = detailsGenerator; component.setDetailsGenerator(detailsGenerator != null ? this::getRowDetails : null); } protected Component getRowDetails(E item) { com.haulmont.cuba.gui.components.Component component = detailsGenerator.getDetails(item); return component != null ? component.unwrapComposition(Component.class) : null; } @Override public boolean isDetailsVisible(E entity) { return component.isDetailsVisible(entity); } @Override public void setDetailsVisible(E entity, boolean visible) { component.setDetailsVisible(entity, visible); } @Override public int getTabIndex() { return component.getTabIndex(); } @Override public void setTabIndex(int tabIndex) { component.setTabIndex(tabIndex); } @Override public void setEmptyStateMessage(String message) { component.setEmptyStateMessage(message); showEmptyStateIfPossible(); } @Override public String getEmptyStateMessage() { return component.getEmptyStateMessage(); } @Override public void setEmptyStateLinkMessage(String linkMessage) { component.setEmptyStateLinkMessage(linkMessage); showEmptyStateIfPossible(); } @Override public String getEmptyStateLinkMessage() { return component.getEmptyStateLinkMessage(); } @Override public void setEmptyStateLinkClickHandler(Consumer<EmptyStateClickEvent<E>> handler) { this.emptyStateClickEventHandler = handler; } @Override public Consumer<EmptyStateClickEvent<E>> getEmptyStateLinkClickHandler() { return emptyStateClickEventHandler; } protected void enableCrossFieldValidationHandling(boolean enable) { if (isEditorEnabled()) { ((CubaEditorImpl<E>) component.getEditor()).setCrossFieldValidationHandler( enable ? this::validateCrossFieldRules : null); } } protected String validateCrossFieldRules(Map<String, Object> properties) { E item = getEditedItem(); if (item == null) { return null; } // set changed values from editor to copied entity E copiedItem = metadataTools.deepCopy(item); for (Map.Entry<String, Object> property : properties.entrySet()) { copiedItem.setValue(property.getKey(), property.getValue()); } // validate copy ValidationErrors errors = screenValidation.validateCrossFieldRules( getFrame() != null ? getFrame().getFrameOwner() : null, copiedItem); if (errors.isEmpty()) { return null; } StringBuilder errorMessage = new StringBuilder(); for (ValidationErrors.Item error : errors.getAll()) { errorMessage.append(error.description).append("\n"); } return errorMessage.toString(); } @Nullable protected String getGeneratedRowStyle(E item) { if (rowStyleProviders == null) { return null; } StringBuilder joinedStyle = null; for (Function<? super E, String> styleProvider : rowStyleProviders) { String styleName = styleProvider.apply(item); if (styleName != null) { if (joinedStyle == null) { joinedStyle = new StringBuilder(styleName); } else { joinedStyle.append(" ").append(styleName); } } } return joinedStyle != null ? joinedStyle.toString() : null; } protected void initEmptyState() { component.setEmptyStateLinkClickHandler(() -> { if (emptyStateClickEventHandler != null) { emptyStateClickEventHandler.accept(new EmptyStateClickEvent<>(this)); } }); if (dataBinding != null) { dataBinding.addDataProviderListener(event -> showEmptyStateIfPossible()); } showEmptyStateIfPossible(); } protected void showEmptyStateIfPossible() { boolean emptyItems = (dataBinding != null && dataBinding.getDataGridItems().size() == 0) || getItems() == null; boolean notEmptyMessages = !Strings.isNullOrEmpty(component.getEmptyStateMessage()) || !Strings.isNullOrEmpty(component.getEmptyStateLinkMessage()); component.setShowEmptyState(emptyItems && notEmptyMessages); } protected class CellStyleGeneratorAdapter<T extends E> implements StyleGenerator<T> { protected Column<T> column; public CellStyleGeneratorAdapter(Column<T> column) { this.column = column; } @Override public String apply(T item) { //noinspection unchecked return getGeneratedCellStyle(item, (Column<E>) column); } } @Nullable protected String getGeneratedCellStyle(E item, Column<E> column) { StringBuilder joinedStyle = null; if (column.getStyleProvider() != null) { String styleName = column.getStyleProvider().apply(item); if (styleName != null) { joinedStyle = new StringBuilder(styleName); } } if (cellStyleProviders != null) { for (CellStyleProvider<? super E> styleProvider : cellStyleProviders) { String styleName = styleProvider.getStyleName(item, column.getId()); if (styleName != null) { if (joinedStyle == null) { joinedStyle = new StringBuilder(styleName); } else { joinedStyle.append(" ").append(styleName); } } } } return joinedStyle != null ? joinedStyle.toString() : null; } protected class CellDescriptionGeneratorAdapter<T extends E> implements DescriptionGenerator<T> { protected Column<T> column; public CellDescriptionGeneratorAdapter(Column<T> column) { this.column = column; } @Override public String apply(T item) { //noinspection unchecked return getGeneratedCellDescription(item, (Column<E>) column); } } protected String getGeneratedCellDescription(E item, Column<E> column) { if (column.getDescriptionProvider() != null) { return column.getDescriptionProvider().apply(item); } if (cellDescriptionProvider != null) { return cellDescriptionProvider.getDescription(item, column.getId()); } return null; } public static abstract class AbstractRenderer<T extends Entity, V> implements RendererWrapper<V> { protected com.vaadin.ui.renderers.Renderer<V> renderer; protected WebAbstractDataGrid<?, T> dataGrid; protected String nullRepresentation; protected AbstractRenderer() { } protected AbstractRenderer(String nullRepresentation) { this.nullRepresentation = nullRepresentation; } @Override public com.vaadin.ui.renderers.Renderer<V> getImplementation() { if (renderer == null) { renderer = createImplementation(); } return renderer; } protected abstract com.vaadin.ui.renderers.Renderer<V> createImplementation(); public ValueProvider<?, V> getPresentationValueProvider() { // Some renderers need specific presentation ValueProvider to be set at the same time // (see com.vaadin.ui.Grid.Column.setRenderer(com.vaadin.data.ValueProvider<V,P>, // com.vaadin.ui.renderers.Renderer<? super P>)). // Default `null` means do not use any presentation ValueProvider return null; } @Override public void resetImplementation() { renderer = null; } protected WebAbstractDataGrid<?, T> getDataGrid() { return dataGrid; } protected void setDataGrid(WebAbstractDataGrid<?, T> dataGrid) { this.dataGrid = dataGrid; } protected String getNullRepresentation() { return nullRepresentation; } protected void setNullRepresentation(String nullRepresentation) { checkRendererNotSet(); this.nullRepresentation = nullRepresentation; } protected Column<T> getColumnByGridColumn(Grid.Column<T, ?> column) { return dataGrid.getColumnByGridColumn(column); } protected void checkRendererNotSet() { if (renderer != null) { throw new IllegalStateException("Renderer parameters cannot be changed after it is set to a column"); } } } protected static class ColumnImpl<E extends Entity> implements Column<E>, HasXmlDescriptor { protected final String id; protected final MetaPropertyPath propertyPath; protected String caption; protected String collapsingToggleCaption; protected double width; protected double minWidth; protected double maxWidth; protected int expandRatio; protected boolean collapsed; protected boolean visible; protected boolean collapsible; protected boolean sortable; protected boolean resizable; protected boolean editable; protected boolean generated; protected Function<?, String> formatter; protected AbstractRenderer<E, ?> renderer; protected Function presentationProvider; protected Converter converter; protected Function<? super E, String> styleProvider; protected Function<? super E, String> descriptionProvider; protected ContentMode descriptionContentMode = ContentMode.PREFORMATTED; protected final Class type; protected Class generatedType; protected Element element; protected WebAbstractDataGrid<?, E> owner; protected Grid.Column<E, ?> gridColumn; protected ColumnEditorFieldGenerator fieldGenerator; protected Function<EditorFieldGenerationContext<E>, Field<?>> generator; public ColumnImpl(String id, @Nullable MetaPropertyPath propertyPath, WebAbstractDataGrid<?, E> owner) { this(id, propertyPath, propertyPath != null ? propertyPath.getRangeJavaClass() : String.class, owner); } public ColumnImpl(String id, Class type, WebAbstractDataGrid<?, E> owner) { this(id, null, type, owner); } protected ColumnImpl(String id, @Nullable MetaPropertyPath propertyPath, Class type, WebAbstractDataGrid<?, E> owner) { this.id = id; this.propertyPath = propertyPath; this.type = type; this.owner = owner; setupDefaults(); } protected void setupDefaults() { resizable = true; editable = true; generated = false; // the generated properties are not normally sortable, // but require special handling to enable sorting. // for now sorting for generated properties is disabled sortable = propertyPath != null && owner.isSortable(); collapsible = owner.isColumnsCollapsingAllowed(); collapsed = false; visible = true; ThemeConstants theme = App.getInstance().getThemeConstants(); width = theme.getInt("cuba.web.DataGrid.defaultColumnWidth", -1); maxWidth = theme.getInt("cuba.web.DataGrid.defaultColumnMaxWidth", -1); minWidth = theme.getInt("cuba.web.DataGrid.defaultColumnMinWidth", 10); expandRatio = theme.getInt("cuba.web.DataGrid.defaultColumnExpandRatio", -1); } @Override public String getId() { if (gridColumn != null) { return gridColumn.getId(); } return id; } @Nullable @Override public MetaPropertyPath getPropertyPath() { return propertyPath; } public Object getPropertyId() { return propertyPath != null ? propertyPath : id; } @Override public String getCaption() { if (gridColumn != null) { return gridColumn.getCaption(); } return caption; } @Override public void setCaption(String caption) { this.caption = caption; if (gridColumn != null) { gridColumn.setCaption(caption); } } @Override public String getCollapsingToggleCaption() { if (gridColumn != null) { return gridColumn.getHidingToggleCaption(); } return collapsingToggleCaption; } @Override public void setCollapsingToggleCaption(String collapsingToggleCaption) { this.collapsingToggleCaption = collapsingToggleCaption; if (gridColumn != null) { gridColumn.setHidingToggleCaption(collapsingToggleCaption); } } @Override public double getWidth() { if (gridColumn != null) { return gridColumn.getWidth(); } return width; } @Override public void setWidth(double width) { this.width = width; if (gridColumn != null) { gridColumn.setWidth(width); } } @Override public boolean isWidthAuto() { if (gridColumn != null) { return gridColumn.isWidthUndefined(); } return width < 0; } @Override public void setWidthAuto() { if (!isWidthAuto()) { width = -1; if (gridColumn != null) { gridColumn.setWidthUndefined(); } } } @Override public int getExpandRatio() { if (gridColumn != null) { return gridColumn.getExpandRatio(); } return expandRatio; } @Override public void setExpandRatio(int expandRatio) { this.expandRatio = expandRatio; if (gridColumn != null) { gridColumn.setExpandRatio(expandRatio); } } @Override public void clearExpandRatio() { setExpandRatio(-1); } @Override public double getMinimumWidth() { if (gridColumn != null) { return gridColumn.getMinimumWidth(); } return minWidth; } @Override public void setMinimumWidth(double pixels) { this.minWidth = pixels; if (gridColumn != null) { gridColumn.setMinimumWidth(pixels); } } @Override public double getMaximumWidth() { if (gridColumn != null) { return gridColumn.getMaximumWidth(); } return maxWidth; } @Override public void setMaximumWidth(double pixels) { this.maxWidth = pixels; if (gridColumn != null) { gridColumn.setMaximumWidth(pixels); } } @Override public boolean isVisible() { return visible; } @Override public void setVisible(boolean visible) { if (this.visible != visible) { this.visible = visible; Grid<E> grid = owner.getComponent(); if (visible) { Grid.Column<E, ?> gridColumn = grid.addColumn(new EntityValueProvider<>(getPropertyPath())); owner.setupGridColumnProperties(gridColumn, this); grid.setColumnOrder(owner.getColumnOrder()); } else { grid.removeColumn(getId()); setGridColumn(null); } } } @Override public boolean isCollapsed() { if (gridColumn != null) { return gridColumn.isHidden(); } return collapsed; } @Override public void setCollapsed(boolean collapsed) { this.collapsed = collapsed; if (gridColumn != null) { gridColumn.setHidden(collapsed); // Due to vaadin/framework#11419, // we explicitly send ColumnCollapsingChangeEvent with UserOriginated == false. ColumnCollapsingChangeEvent event = new ColumnCollapsingChangeEvent(owner, this, collapsed, false); owner.publish(ColumnCollapsingChangeEvent.class, event); } } @Override public boolean isCollapsible() { if (gridColumn != null) { return gridColumn.isHidable(); } return collapsible; } @Override public void setCollapsible(boolean collapsible) { this.collapsible = collapsible; updateCollapsible(); } public void updateCollapsible() { if (gridColumn != null) { gridColumn.setHidable(collapsible && owner.isColumnsCollapsingAllowed()); } } @Override public boolean isSortable() { return sortable; } @Override public void setSortable(boolean sortable) { this.sortable = sortable; updateSortable(); } public void updateSortable() { if (gridColumn != null) { gridColumn.setSortable(this.sortable && owner.isSortable()); } } @Override public boolean isResizable() { if (gridColumn != null) { return gridColumn.isResizable(); } return resizable; } @Override public void setResizable(boolean resizable) { this.resizable = resizable; if (gridColumn != null) { gridColumn.setResizable(resizable); } } @Override public Function getFormatter() { return formatter; } @Override public void setFormatter(Function formatter) { this.formatter = formatter; updateRendererInternal(); } @Nullable protected MetaProperty getMetaProperty() { return getPropertyPath() != null ? getPropertyPath().getMetaProperty() : null; } @Override public Element getXmlDescriptor() { return element; } @Override public void setXmlDescriptor(Element element) { this.element = element; } @Override public Renderer getRenderer() { return renderer; } @Override public void setRenderer(Renderer renderer) { setRenderer(renderer, null); } @Override public void setRenderer(Renderer renderer, Function presentationProvider) { if (renderer == null && this.renderer != null) { this.renderer.resetImplementation(); this.renderer.setDataGrid(null); } //noinspection unchecked this.renderer = (AbstractRenderer) renderer; this.presentationProvider = presentationProvider; if (this.renderer != null) { this.renderer.setDataGrid(owner); } updateRendererInternal(); } @SuppressWarnings({"unchecked"}) protected ValueProvider createPresentationProviderWrapper(Function presentationProvider) { return (ValueProvider) presentationProvider::apply; } @SuppressWarnings("unchecked") protected void updateRendererInternal() { if (gridColumn != null) { com.vaadin.ui.renderers.Renderer vRenderer = renderer != null ? renderer.getImplementation() : owner.getDefaultRenderer(this); // The following priority is used to determine a value provider: // a presentation provider > a converter > a formatter > a renderer's presentation provider > // a value provider that always returns its input argument > a default presentation provider //noinspection RedundantCast ValueProvider vPresentationProvider = presentationProvider != null ? createPresentationProviderWrapper(presentationProvider) : converter != null ? new DataGridConverterBasedValueProvider(converter) : formatter != null ? new FormatterBasedValueProvider(formatter) : renderer != null && renderer.getPresentationValueProvider() != null ? (ValueProvider) renderer.getPresentationValueProvider() : renderer != null // In case renderer != null and there are no other user specified value providers // We use a value provider that always returns its input argument instead of a default // value provider as we want to keep the original value type. ? ValueProvider.identity() : owner.getDefaultPresentationValueProvider(this); gridColumn.setRenderer(vPresentationProvider, vRenderer); owner.repaint(); } } @Override public Function getPresentationProvider() { return presentationProvider; } @Override public Converter<?, ?> getConverter() { return converter; } @Override public void setConverter(Converter<?, ?> converter) { this.converter = converter; updateRendererInternal(); } @Override public Class getType() { return type; } @Override public void setGeneratedType(Class generatedType) { this.generatedType = generatedType; } @Override public Class getGeneratedType() { return generatedType; } public boolean isGenerated() { return generated; } public void setGenerated(boolean generated) { this.generated = generated; } @Override public boolean isEditable() { if (gridColumn != null) { return gridColumn.isEditable(); } return isShouldBeEditable(); } public boolean isShouldBeEditable() { return editable && propertyPath != null // We can't generate field for editor in case we don't have propertyPath && (!generated && !isRepresentsCollection() || fieldGenerator != null || generator != null) && isEditingPermitted(); } protected boolean isRepresentsCollection() { if (propertyPath != null) { MetaProperty metaProperty = propertyPath.getMetaProperty(); Class<?> javaType = metaProperty.getJavaType(); return Collection.class.isAssignableFrom(javaType); } return false; } protected boolean isEditingPermitted() { if (propertyPath != null) { MetaClass metaClass = propertyPath.getMetaClass(); return owner.security.isEntityAttrUpdatePermitted(metaClass, propertyPath.toString()); } return true; } @Override public void setEditable(boolean editable) { this.editable = editable; updateEditable(); } protected void updateEditable() { if (gridColumn != null) { gridColumn.setEditable(isShouldBeEditable()); } } @Override public ColumnEditorFieldGenerator getEditorFieldGenerator() { return fieldGenerator; } @Override public void setEditorFieldGenerator(ColumnEditorFieldGenerator fieldFactory) { this.fieldGenerator = fieldFactory; updateEditable(); } @Override public Function<EditorFieldGenerationContext<E>, Field<?>> getEditFieldGenerator() { return generator; } @Override public void setEditFieldGenerator(Function<EditorFieldGenerationContext<E>, Field<?>> generator) { this.generator = generator; updateEditable(); } @SuppressWarnings("unchecked") @Override public Function<E, String> getStyleProvider() { return (Function<E, String>) styleProvider; } @Override public void setStyleProvider(Function<? super E, String> styleProvider) { this.styleProvider = styleProvider; owner.repaint(); } @SuppressWarnings("unchecked") @Override public Function<E, String> getDescriptionProvider() { return (Function<E, String>) descriptionProvider; } @Override public void setDescriptionProvider(Function<? super E, String> descriptionProvider) { setDescriptionProvider(descriptionProvider, ContentMode.PREFORMATTED); } @Override public void setDescriptionProvider(Function<? super E, String> descriptionProvider, ContentMode contentMode) { this.descriptionProvider = descriptionProvider; this.descriptionContentMode = contentMode; if (gridColumn != null) { gridColumn.getState().tooltipContentMode = WebWrapperUtils.toVaadinContentMode(contentMode); } owner.repaint(); } public ContentMode getDescriptionContentMode() { return descriptionContentMode; } public Grid.Column<E, ?> getGridColumn() { return gridColumn; } public void setGridColumn(Grid.Column<E, ?> gridColumn) { AppUI current = AppUI.getCurrent(); if (gridColumn == null && current != null && current.isTestMode()) { owner.removeColumnId(this.gridColumn); } this.gridColumn = gridColumn; } @Override public DataGrid<E> getOwner() { return owner; } @Override public void setOwner(DataGrid<E> owner) { this.owner = (WebAbstractDataGrid<?, E>) owner; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ColumnImpl column = (ColumnImpl) o; return id.equals(column.id); } @Override public int hashCode() { return id.hashCode(); } @Override public String toString() { return id == null ? super.toString() : id; } } protected abstract static class AbstractStaticRowImp<T extends StaticCell> implements StaticRow<T> { protected WebAbstractDataGrid dataGrid; protected StaticSection.StaticRow<?> gridRow; public AbstractStaticRowImp(WebAbstractDataGrid dataGrid, StaticSection.StaticRow<?> gridRow) { this.dataGrid = dataGrid; this.gridRow = gridRow; } @Override public String getStyleName() { return gridRow.getStyleName(); } @Override public void setStyleName(String styleName) { gridRow.setStyleName(styleName); } @Override public T join(String... columnIds) { return joinInternal(columnIds); } protected abstract T joinInternal(String... columnIds); @Override public T getCell(String columnId) { ColumnImpl column = (ColumnImpl) dataGrid.getColumnNN(columnId); return getCellInternal(column.getId()); } protected abstract T getCellInternal(String columnId); public StaticSection.StaticRow<?> getGridRow() { return gridRow; } } protected static class HeaderRowImpl extends AbstractStaticRowImp<HeaderCell> implements HeaderRow { public HeaderRowImpl(WebAbstractDataGrid dataGrid, Header.Row headerRow) { super(dataGrid, headerRow); } @Override public Header.Row getGridRow() { return (Header.Row) super.getGridRow(); } @Override protected HeaderCell getCellInternal(String columnId) { Header.Row.Cell gridCell = getGridRow().getCell(columnId); return new HeaderCellImpl(this, gridCell); } @Override protected HeaderCell joinInternal(String... columnIds) { Header.Row.Cell gridCell = (Header.Row.Cell) getGridRow().join(columnIds); return new HeaderCellImpl(this, gridCell); } } protected static class FooterRowImpl extends AbstractStaticRowImp<FooterCell> implements FooterRow { public FooterRowImpl(WebAbstractDataGrid dataGrid, Footer.Row footerRow) { super(dataGrid, footerRow); } @Override public Footer.Row getGridRow() { return (Footer.Row) super.getGridRow(); } @Override protected FooterCell getCellInternal(String columnId) { Footer.Row.Cell gridCell = getGridRow().getCell(columnId); return new FooterCellImpl(this, gridCell); } @Override protected FooterCell joinInternal(String... columnIds) { Footer.Row.Cell gridCell = (Footer.Row.Cell) getGridRow().join(columnIds); return new FooterCellImpl(this, gridCell); } } protected abstract static class AbstractStaticCellImpl implements StaticCell { protected StaticRow<?> row; protected com.haulmont.cuba.gui.components.Component component; public AbstractStaticCellImpl(StaticRow<?> row) { this.row = row; } @Override public StaticRow<?> getRow() { return row; } @Override public com.haulmont.cuba.gui.components.Component getComponent() { return component; } @Override public void setComponent(com.haulmont.cuba.gui.components.Component component) { this.component = component; } } protected static class HeaderCellImpl extends AbstractStaticCellImpl implements HeaderCell { protected Header.Row.Cell gridCell; public HeaderCellImpl(HeaderRow row, Header.Row.Cell gridCell) { super(row); this.gridCell = gridCell; } @Override public HeaderRow getRow() { return (HeaderRow) super.getRow(); } @Override public String getStyleName() { return gridCell.getStyleName(); } @Override public void setStyleName(String styleName) { gridCell.setStyleName(styleName); } @Override public DataGridStaticCellType getCellType() { return WebWrapperUtils.toDataGridStaticCellType(gridCell.getCellType()); } @Override public void setComponent(com.haulmont.cuba.gui.components.Component component) { super.setComponent(component); gridCell.setComponent(component.unwrap(Component.class)); } @Override public String getHtml() { return gridCell.getHtml(); } @Override public void setHtml(String html) { gridCell.setHtml(html); } @Override public String getText() { return gridCell.getText(); } @Override public void setText(String text) { gridCell.setText(text); } } protected static class FooterCellImpl extends AbstractStaticCellImpl implements FooterCell { protected Footer.Row.Cell gridCell; public FooterCellImpl(FooterRow row, Footer.Row.Cell gridCell) { super(row); this.gridCell = gridCell; } @Override public FooterRow getRow() { return (FooterRow) super.getRow(); } @Override public String getStyleName() { return gridCell.getStyleName(); } @Override public void setStyleName(String styleName) { gridCell.setStyleName(styleName); } @Override public DataGridStaticCellType getCellType() { return WebWrapperUtils.toDataGridStaticCellType(gridCell.getCellType()); } @Override public void setComponent(com.haulmont.cuba.gui.components.Component component) { super.setComponent(component); gridCell.setComponent(component.unwrap(Component.class)); } @Override public String getHtml() { return gridCell.getHtml(); } @Override public void setHtml(String html) { gridCell.setHtml(html); } @Override public String getText() { return gridCell.getText(); } @Override public void setText(String text) { gridCell.setText(text); } } public static class ActionMenuItemWrapper { protected MenuItem menuItem; protected Action action; protected boolean showIconsForPopupMenuActions; protected Consumer<PropertyChangeEvent> actionPropertyChangeListener; public ActionMenuItemWrapper(MenuItem menuItem, boolean showIconsForPopupMenuActions) { this.menuItem = menuItem; this.showIconsForPopupMenuActions = showIconsForPopupMenuActions; this.menuItem.setCommand((MenuBar.Command) selectedItem -> { if (action != null) { performAction(action); } }); } public void performAction(Action action) { action.actionPerform(null); } public MenuItem getMenuItem() { return menuItem; } public Action getAction() { return action; } public void setAction(Action action) { if (this.action != action) { if (this.action != null) { this.action.removePropertyChangeListener(actionPropertyChangeListener); } this.action = action; if (action != null) { String caption = action.getCaption(); if (!StringUtils.isEmpty(caption)) { setCaption(caption); } menuItem.setEnabled(action.isEnabled()); menuItem.setVisible(action.isVisible()); if (action.getIcon() != null) { setIcon(action.getIcon()); } actionPropertyChangeListener = evt -> { if (Action.PROP_ICON.equals(evt.getPropertyName())) { setIcon(this.action.getIcon()); } else if (Action.PROP_CAPTION.equals(evt.getPropertyName())) { setCaption(this.action.getCaption()); } else if (Action.PROP_ENABLED.equals(evt.getPropertyName())) { setEnabled(this.action.isEnabled()); } else if (Action.PROP_VISIBLE.equals(evt.getPropertyName())) { setVisible(this.action.isVisible()); } }; action.addPropertyChangeListener(actionPropertyChangeListener); } } } public void setEnabled(boolean enabled) { menuItem.setEnabled(enabled); } public void setVisible(boolean visible) { menuItem.setVisible(visible); } public void setIcon(String icon) { if (showIconsForPopupMenuActions) { if (!StringUtils.isEmpty(icon)) { menuItem.setIcon(AppBeans.get(IconResolver.class).getIconResource(icon)); } else { menuItem.setIcon(null); } } } public void setCaption(String caption) { if (action.getShortcutCombination() != null) { StringBuilder sb = new StringBuilder(); sb.append(caption); if (action.getShortcutCombination() != null) { sb.append(" (").append(action.getShortcutCombination().format()).append(")"); } caption = sb.toString(); } menuItem.setText(caption); } } protected static class GridComposition extends CubaCssActionsLayout { protected Grid<?> grid; public Grid<?> getGrid() { return grid; } public void setGrid(Grid<?> grid) { this.grid = grid; } @Override public void setHeight(float height, Unit unit) { super.setHeight(height, unit); if (getHeight() < 0) { grid.setHeightUndefined(); grid.setHeightMode(HeightMode.UNDEFINED); } else { grid.setHeight(100, Unit.PERCENTAGE); grid.setHeightMode(HeightMode.CSS); } } @Override public void setWidth(float width, Unit unit) { super.setWidth(width, unit); if (getWidth() < 0) { grid.setWidthUndefined(); } else { grid.setWidth(100, Unit.PERCENTAGE); } } } }
DataGrid generated columns that correspond to an Entity attribute must be sortable #1704
modules/web/src/com/haulmont/cuba/web/gui/components/WebAbstractDataGrid.java
DataGrid generated columns that correspond to an Entity attribute must be sortable #1704
<ide><path>odules/web/src/com/haulmont/cuba/web/gui/components/WebAbstractDataGrid.java <ide> Grid.Column<E, Object> generatedColumn = <ide> component.addColumn(createGeneratedColumnValueProvider(columnId, generator)); <ide> <del> ColumnImpl<E> column = new ColumnImpl<>(columnId, generator.getType(), this); <add> // Pass propertyPath from the existing column to support sorting <add> ColumnImpl<E> column = new ColumnImpl<>(columnId, <add> existingColumn != null ? existingColumn.getPropertyPath() : null, <add> generator.getType(), this); <ide> if (existingColumn != null) { <ide> copyColumnProperties(column, existingColumn); <ide> } else { <ide> column.setStyleProvider(existingColumn.getStyleProvider()); <ide> column.setDescriptionProvider(existingColumn.getDescriptionProvider(), <ide> ((ColumnImpl) existingColumn).getDescriptionContentMode()); <add> <add> // If the new column has propertyPath and it equals to propertyPath <add> // of the existing column, then coping the Sortable state, as it seems <add> // that the new column corresponds to the generated column that is <add> // related to the existing Entity attribute, so that this column can be sortable <add> if (column.getPropertyPath() != null <add> && column.getPropertyPath().equals(existingColumn.getPropertyPath())) { <add> column.setSortable(existingColumn.isSortable()); <add> } <ide> } <ide> <ide> @Override <ide> } <ide> <ide> protected ColumnImpl(String id, <del> @Nullable MetaPropertyPath propertyPath, Class type, WebAbstractDataGrid<?, E> owner) { <add> @Nullable MetaPropertyPath propertyPath, Class type, WebAbstractDataGrid<?, E> owner) { <ide> this.id = id; <ide> this.propertyPath = propertyPath; <ide> this.type = type;
Java
mit
4cbb96be943715505d4c92c36e182e8aa7ffc530
0
kriegfrj/robolectric,karlicoss/robolectric,erichaugh/robolectric,davidsun/robolectric,tjohn/robolectric,tec27/robolectric,diegotori/robolectric,1zaman/robolectric,diegotori/robolectric,ChengCorp/robolectric,spotify/robolectric,jingle1267/robolectric,jingle1267/robolectric,fiower/robolectric,plackemacher/robolectric,WonderCsabo/robolectric,jongerrish/robolectric,zbsz/robolectric,tuenti/robolectric,cesar1000/robolectric,zhongyu05/robolectric,erichaugh/robolectric,VikingDen/robolectric,tec27/robolectric,zbsz/robolectric,eric-kansas/robolectric,gb112211/robolectric,WonderCsabo/robolectric,hgl888/robolectric,toluju/robolectric,tuenti/robolectric,charlesmunger/robolectric,mag/robolectric,zhongyu05/robolectric,tec27/robolectric,spotify/robolectric,lexs/robolectric,tmrudick/robolectric,pivotal-oscar/robolectric,tuenti/robolectric,kriegfrj/robolectric,holmari/robolectric,jongerrish/robolectric,kriegfrj/robolectric,lexs/robolectric,macklinu/robolectric,rburgst/robolectric,macklinu/robolectric,ChengCorp/robolectric,rongou/robolectric,charlesmunger/robolectric,gruszczy/robolectric,rburgst/robolectric,mag/robolectric,paulpv/robolectric,gb112211/robolectric,eric-kansas/robolectric,spotify/robolectric,erichaugh/robolectric,tyronen/robolectric,eric-kansas/robolectric,cesar1000/robolectric,gabrielduque/robolectric,davidsun/robolectric,tjohn/robolectric,WonderCsabo/robolectric,svenji/robolectric,1zaman/robolectric,lexs/robolectric,macklinu/robolectric,tyronen/robolectric,paulpv/robolectric,amarts/robolectric,diegotori/robolectric,ChengCorp/robolectric,cc12703/robolectric,ocadotechnology/robolectric,cesar1000/robolectric,zbsz/robolectric,yuzhong-google/robolectric,toluju/robolectric,jongerrish/robolectric,paulpv/robolectric,jingle1267/robolectric,tmrudick/robolectric,gabrielduque/robolectric,holmari/robolectric,ocadotechnology/robolectric,toluju/robolectric,yuzhong-google/robolectric,pivotal-oscar/robolectric,trevorrjohn/robolectric,trevorrjohn/robolectric,karlicoss/robolectric,yuzhong-google/robolectric,cc12703/robolectric,gruszczy/robolectric,plackemacher/robolectric,amarts/robolectric,plackemacher/robolectric,rongou/robolectric,tmrudick/robolectric,hgl888/robolectric,rburgst/robolectric,svenji/robolectric,trevorrjohn/robolectric,wyvx/robolectric,ocadotechnology/robolectric,cc12703/robolectric,rongou/robolectric,karlicoss/robolectric,gabrielduque/robolectric,pivotal-oscar/robolectric,mag/robolectric,gb112211/robolectric,wyvx/robolectric,zhongyu05/robolectric,fiower/robolectric,VikingDen/robolectric,VikingDen/robolectric,tjohn/robolectric,tyronen/robolectric,wyvx/robolectric,charlesmunger/robolectric,holmari/robolectric,svenji/robolectric,hgl888/robolectric,1zaman/robolectric,fiower/robolectric,amarts/robolectric,jongerrish/robolectric,davidsun/robolectric,gruszczy/robolectric
package org.robolectric.res.builder; import android.content.ComponentName; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Pair; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import org.robolectric.AndroidManifest; import org.robolectric.Robolectric; import org.robolectric.res.ActivityData; import org.robolectric.res.ResName; import org.robolectric.res.ResourceIndex; import org.robolectric.shadows.ShadowContext; import org.robolectric.tester.android.content.pm.StubPackageManager; public class RobolectricPackageManager extends StubPackageManager { private static class IntentComparator implements Comparator<Intent> { @Override public int compare(Intent i1, Intent i2) { if (i1 == null && i2 == null) return 0; if (i1 == null && i2 != null) return -1; if (i1 != null && i2 == null) return 1; if (i1.equals(i2)) return 0; if (i1.getAction() == null && i2.getAction() != null) return -1; if (i1.getAction() != null && i2.getAction() == null) return 1; if (i1.getAction() != null && i2.getAction() != null) { if (!i1.getAction().equals(i2.getAction())) { return i1.getAction().compareTo(i2.getAction()); } } if (i1.getData() == null && i2.getData() != null) return -1; if (i1.getData() != null && i2.getData() == null) return 1; if (i1.getData() != null && i2.getData() != null) { if (!i1.getData().equals(i2.getData())) { return i1.getData().compareTo(i2.getData()); } } if (i1.getComponent() == null && i2.getComponent() != null) return -1; if (i1.getComponent() != null && i2.getComponent() == null) return 1; if (i1.getComponent() != null && i2.getComponent() != null) { if (!i1.getComponent().equals(i2.getComponent())) { return i1.getComponent().compareTo(i2.getComponent()); } } Set<String> categories1 = i1.getCategories(); Set<String> categories2 = i2.getCategories(); if (categories1 == null) return categories2 == null ? 0 : -1; if (categories2 == null) return 1; if (categories1.size() > categories2.size()) return 1; if (categories1.size() < categories2.size()) return -1; String[] array1 = categories1.toArray(new String[0]); String[] array2 = categories2.toArray(new String[0]); Arrays.sort(array1); Arrays.sort(array2); for (int i = 0; i < array1.length; ++i) { int val = array1[i].compareTo(array2[i]); if (val != 0) return val; } return 0; } @Override public boolean equals(Intent i1, Intent i2) { return compare(i1,i2) == 0; } } private final Map<String, AndroidManifest> androidManifests = new LinkedHashMap<String, AndroidManifest>(); private final Map<String, PackageInfo> packageInfos = new LinkedHashMap<String, PackageInfo>(); private Map<Intent, List<ResolveInfo>> resolveInfoForIntent = new TreeMap<Intent, List<ResolveInfo>>(new IntentComparator()); private Map<ComponentName, ComponentState> componentList = new LinkedHashMap<ComponentName, ComponentState>(); private Map<ComponentName, Drawable> drawableList = new LinkedHashMap<ComponentName, Drawable>(); private Map<String, Boolean> systemFeatureList = new LinkedHashMap<String, Boolean>(); private Map<IntentFilter, ComponentName> preferredActivities = new LinkedHashMap<IntentFilter, ComponentName>(); private Map<Pair<String, Integer>, Drawable> drawables = new LinkedHashMap<Pair<String, Integer>, Drawable>(); @Override public PackageInfo getPackageInfo(String packageName, int flags) throws NameNotFoundException { if (packageInfos.containsKey(packageName)) { return packageInfos.get(packageName); } throw new NameNotFoundException(); } @Override public ApplicationInfo getApplicationInfo(String packageName, int flags) throws NameNotFoundException { PackageInfo info = packageInfos.get(packageName); if (info != null) { return info.applicationInfo; } else { throw new NameNotFoundException(); } } @Override public ActivityInfo getActivityInfo(ComponentName className, int flags) throws NameNotFoundException { String packageName = className.getPackageName(); AndroidManifest androidManifest = androidManifests.get(packageName); String activityName = className.getClassName(); ActivityData activityData = androidManifest.getActivityData(activityName); ActivityInfo activityInfo = new ActivityInfo(); activityInfo.packageName = packageName; activityInfo.name = activityName; if (activityData != null) { ResourceIndex resourceIndex = Robolectric.getShadowApplication().getResourceLoader().getResourceIndex(); String themeRef; // Based on ShadowActivity if (activityData.getThemeRef() != null) { themeRef = activityData.getThemeRef(); } else { themeRef = androidManifest.getThemeRef(); } if (themeRef != null) { ResName style = ResName.qualifyResName(themeRef.replace("@", ""), packageName, "style"); activityInfo.theme = resourceIndex.getResourceId(style); } } activityInfo.applicationInfo = getApplicationInfo(packageName, flags); return activityInfo; } @Override public List<PackageInfo> getInstalledPackages(int flags) { return new ArrayList<PackageInfo>(packageInfos.values()); } @Override public List<ResolveInfo> queryIntentActivities(Intent intent, int flags) { return queryIntent(intent, flags); } @Override public List<ResolveInfo> queryIntentServices(Intent intent, int flags) { return queryIntent(intent, flags); } @Override public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) { return queryIntent(intent, flags); } @Override public ResolveInfo resolveActivity(Intent intent, int flags) { List<ResolveInfo> candidates = queryIntentActivities(intent, flags); return candidates.isEmpty() ? null : candidates.get(0); } @Override public ResolveInfo resolveService(Intent intent, int flags) { return resolveActivity(intent, flags); } public void addResolveInfoForIntent(Intent intent, List<ResolveInfo> info) { resolveInfoForIntent.put(intent, info); } public void addResolveInfoForIntent(Intent intent, ResolveInfo info) { List<ResolveInfo> infoList = findOrCreateInfoList(intent); infoList.add(info); } public void removeResolveInfosForIntent(Intent intent, String packageName) { List<ResolveInfo> infoList = findOrCreateInfoList(intent); for (Iterator<ResolveInfo> iterator = infoList.iterator(); iterator.hasNext(); ) { ResolveInfo resolveInfo = iterator.next(); if (resolveInfo.activityInfo.packageName.equals(packageName)) { iterator.remove(); } } } @Override public Drawable getActivityIcon(Intent intent) { return drawableList.get(intent.getComponent()); } @Override public Drawable getActivityIcon(ComponentName componentName) { return drawableList.get(componentName); } public void addActivityIcon(ComponentName component, Drawable d) { drawableList.put(component, d); } public void addActivityIcon(Intent intent, Drawable d) { drawableList.put(intent.getComponent(), d); } @Override public Intent getLaunchIntentForPackage(String packageName) { Intent intentToResolve = new Intent(Intent.ACTION_MAIN); intentToResolve.addCategory(Intent.CATEGORY_INFO); intentToResolve.setPackage(packageName); List<ResolveInfo> ris = queryIntentActivities(intentToResolve, 0); if (ris == null || ris.isEmpty()) { intentToResolve.removeCategory(Intent.CATEGORY_INFO); intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER); intentToResolve.setPackage(packageName); ris = queryIntentActivities(intentToResolve, 0); } if (ris == null || ris.isEmpty()) { return null; } Intent intent = new Intent(intentToResolve); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setClassName(ris.get(0).activityInfo.packageName, ris.get(0).activityInfo.name); return intent; } @Override public CharSequence getApplicationLabel(ApplicationInfo info) { return info.name; } @Override public void setComponentEnabledSetting(ComponentName componentName, int newState, int flags) { componentList.put(componentName, new ComponentState(newState, flags)); } public void addPreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity) { preferredActivities.put(filter, activity); } @Override public int getPreferredActivities(List<IntentFilter> outFilters, List<ComponentName> outActivities, String packageName) { if (outFilters == null) { return 0; } Set<IntentFilter> filters = preferredActivities.keySet(); for (IntentFilter filter : outFilters) { step: for (IntentFilter testFilter : filters) { ComponentName name = preferredActivities.get(testFilter); // filter out based on the given packageName; if (packageName != null && !name.getPackageName().equals(packageName)) { continue step; } // Check actions Iterator<String> iterator = filter.actionsIterator(); while (iterator.hasNext()) { if (!testFilter.matchAction(iterator.next())) { continue step; } } iterator = filter.categoriesIterator(); while (iterator.hasNext()) { if (!filter.hasCategory(iterator.next())) { continue step; } } if (outActivities == null) { outActivities = new ArrayList<ComponentName>(); } outActivities.add(name); } } return 0; } /** * Non-Android accessor. Use to make assertions on values passed to * setComponentEnabledSetting. * * @param componentName * @return */ public ComponentState getComponentState(ComponentName componentName) { return componentList.get(componentName); } /** * Non-Android accessor. Used to add a package to the list of those * already 'installed' on system. * * @param packageInfo */ public void addPackage(PackageInfo packageInfo) { packageInfos.put(packageInfo.packageName, packageInfo); } public void addPackage(String packageName) { PackageInfo packageInfo = new PackageInfo(); packageInfo.packageName = packageName; ApplicationInfo applicationInfo = new ApplicationInfo(); applicationInfo.packageName = packageName; initApplicationInfo(applicationInfo); packageInfo.applicationInfo = applicationInfo; addPackage(packageInfo); } public void addManifest(AndroidManifest androidManifest) { androidManifests.put(androidManifest.getPackageName(), androidManifest); PackageInfo packageInfo = new PackageInfo(); packageInfo.packageName = androidManifest.getPackageName(); packageInfo.versionName = androidManifest.getVersionName(); packageInfo.versionCode = androidManifest.getVersionCode(); ApplicationInfo applicationInfo = new ApplicationInfo(); applicationInfo.flags = androidManifest.getApplicationFlags(); applicationInfo.targetSdkVersion = androidManifest.getTargetSdkVersion(); applicationInfo.packageName = androidManifest.getPackageName(); applicationInfo.processName = androidManifest.getProcessName(); applicationInfo.name = androidManifest.getApplicationName(); initApplicationInfo(applicationInfo); initApplicationMetaData(applicationInfo, androidManifest); packageInfo.applicationInfo = applicationInfo; addPackage(packageInfo); } private void initApplicationInfo(ApplicationInfo applicationInfo) { applicationInfo.sourceDir = new File(".").getAbsolutePath(); applicationInfo.dataDir = ShadowContext.FILES_DIR.getAbsolutePath(); } private void initApplicationMetaData(ApplicationInfo applicationInfo, AndroidManifest androidManifest) { Map<String, String> meta = androidManifest.getApplicationMetaData(); if (meta.isEmpty()) { return; } applicationInfo.metaData = new Bundle(); for (Entry<String, String> metaEntry : meta.entrySet()) { applicationInfo.metaData.putString(metaEntry.getKey(), metaEntry.getValue()); } } public void removePackage(String packageName) { packageInfos.remove(packageName); } @Override public boolean hasSystemFeature(String name) { return systemFeatureList.containsKey(name) ? systemFeatureList.get(name) : false; } /** * Non-Android accessor. Used to declare a system feature is * or is not supported. * * @param name * @param supported */ public void setSystemFeature(String name, boolean supported) { systemFeatureList.put(name, supported); } public void addDrawableResolution(String packageName, int resourceId, Drawable drawable) { drawables.put(new Pair(packageName, resourceId), drawable); } public class ComponentState { public int newState; public int flags; public ComponentState(int newState, int flags) { this.newState = newState; this.flags = flags; } } @Override public Drawable getDrawable(String packageName, int resourceId, ApplicationInfo applicationInfo) { return drawables.get(new Pair(packageName, resourceId)); } private List<ResolveInfo> findOrCreateInfoList(Intent intent) { List<ResolveInfo> infoList = resolveInfoForIntent.get(intent); if (infoList == null) { infoList = new ArrayList<ResolveInfo>(); resolveInfoForIntent.put(intent, infoList); } return infoList; } private List<ResolveInfo> queryIntent(Intent intent, int flags) { List<ResolveInfo> result = resolveInfoForIntent.get(intent); if (result == null) { return Collections.emptyList(); } else { return result; } } }
src/main/java/org/robolectric/res/builder/RobolectricPackageManager.java
package org.robolectric.res.builder; import android.content.ComponentName; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Pair; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import org.robolectric.AndroidManifest; import org.robolectric.Robolectric; import org.robolectric.res.ActivityData; import org.robolectric.res.ResName; import org.robolectric.res.ResourceIndex; import org.robolectric.shadows.ShadowContext; import org.robolectric.tester.android.content.pm.StubPackageManager; public class RobolectricPackageManager extends StubPackageManager { private static class IntentComparator implements Comparator<Intent> { public int compare(Intent i1, Intent i2) { if (i1 == null && i2 == null) return 0; if (i1 == null && i2 != null) return -1; if (i1 != null && i2 == null) return 1; if (i1.equals(i2)) return 0; if (i1.getAction() == null && i2.getAction() != null) return -1; if (i1.getAction() != null && i2.getAction() == null) return 1; if (i1.getAction() != null && i2.getAction() != null) { if (!i1.getAction().equals(i2.getAction())) { return i1.getAction().compareTo(i2.getAction()); } } if (i1.getData() == null && i2.getData() != null) return -1; if (i1.getData() != null && i2.getData() == null) return 1; if (i1.getData() != null && i2.getData() != null) { if (!i1.getData().equals(i2.getData())) { return i1.getData().compareTo(i2.getData()); } } if (i1.getComponent() == null && i2.getComponent() != null) return -1; if (i1.getComponent() != null && i2.getComponent() == null) return 1; if (i1.getComponent() != null && i2.getComponent() != null) { if (!i1.getComponent().equals(i2.getComponent())) { return i1.getComponent().compareTo(i2.getComponent()); } } Set<String> categories1 = i1.getCategories(); Set<String> categories2 = i2.getCategories(); if (categories1 == null) return categories2 == null ? 0 : -1; if (categories2 == null) return 1; if (categories1.size() > categories2.size()) return 1; if (categories1.size() < categories2.size()) return -1; String[] array1 = categories1.toArray(new String[0]); String[] array2 = categories2.toArray(new String[0]); Arrays.sort(array1); Arrays.sort(array2); for (int i = 0; i < array1.length; ++i) { int val = array1[i].compareTo(array2[i]); if (val != 0) return val; } return 0; } public boolean equals(Intent i1, Intent i2) { return compare(i1,i2) == 0; } } private final Map<String, AndroidManifest> androidManifests = new LinkedHashMap<String, AndroidManifest>(); private final Map<String, PackageInfo> packageInfos = new LinkedHashMap<String, PackageInfo>(); private Map<Intent, List<ResolveInfo>> resolveInfoForIntent = new TreeMap<Intent, List<ResolveInfo>>(new IntentComparator()); private Map<ComponentName, ComponentState> componentList = new LinkedHashMap<ComponentName, ComponentState>(); private Map<ComponentName, Drawable> drawableList = new LinkedHashMap<ComponentName, Drawable>(); private Map<String, Boolean> systemFeatureList = new LinkedHashMap<String, Boolean>(); private Map<IntentFilter, ComponentName> preferredActivities = new LinkedHashMap<IntentFilter, ComponentName>(); private Map<Pair<String, Integer>, Drawable> drawables = new LinkedHashMap<Pair<String, Integer>, Drawable>(); @Override public PackageInfo getPackageInfo(String packageName, int flags) throws NameNotFoundException { if (packageInfos.containsKey(packageName)) { return packageInfos.get(packageName); } throw new NameNotFoundException(); } @Override public ApplicationInfo getApplicationInfo(String packageName, int flags) throws NameNotFoundException { PackageInfo info = packageInfos.get(packageName); if (info != null) { return info.applicationInfo; } else { throw new NameNotFoundException(); } } @Override public ActivityInfo getActivityInfo(ComponentName className, int flags) throws NameNotFoundException { String packageName = className.getPackageName(); AndroidManifest androidManifest = androidManifests.get(packageName); String activityName = className.getClassName(); ActivityData activityData = androidManifest.getActivityData(activityName); ActivityInfo activityInfo = new ActivityInfo(); activityInfo.packageName = packageName; activityInfo.name = activityName; if (activityData != null) { ResourceIndex resourceIndex = Robolectric.getShadowApplication().getResourceLoader().getResourceIndex(); String themeRef; // Based on ShadowActivity if (activityData.getThemeRef() != null) { themeRef = activityData.getThemeRef(); } else { themeRef = androidManifest.getThemeRef(); } if (themeRef != null) { ResName style = ResName.qualifyResName(themeRef.replace("@", ""), packageName, "style"); activityInfo.theme = resourceIndex.getResourceId(style); } } activityInfo.applicationInfo = getApplicationInfo(packageName, flags); return activityInfo; } @Override public List<PackageInfo> getInstalledPackages(int flags) { return new ArrayList<PackageInfo>(packageInfos.values()); } @Override public List<ResolveInfo> queryIntentActivities(Intent intent, int flags) { return queryIntent(intent, flags); } @Override public List<ResolveInfo> queryIntentServices(Intent intent, int flags) { return queryIntent(intent, flags); } @Override public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) { return queryIntent(intent, flags); } @Override public ResolveInfo resolveActivity(Intent intent, int flags) { List<ResolveInfo> candidates = queryIntentActivities(intent, flags); return candidates.isEmpty() ? null : candidates.get(0); } @Override public ResolveInfo resolveService(Intent intent, int flags) { return resolveActivity(intent, flags); } public void addResolveInfoForIntent(Intent intent, List<ResolveInfo> info) { resolveInfoForIntent.put(intent, info); } public void addResolveInfoForIntent(Intent intent, ResolveInfo info) { List<ResolveInfo> infoList = findOrCreateInfoList(intent); infoList.add(info); } public void removeResolveInfosForIntent(Intent intent, String packageName) { List<ResolveInfo> infoList = findOrCreateInfoList(intent); for (Iterator<ResolveInfo> iterator = infoList.iterator(); iterator.hasNext(); ) { ResolveInfo resolveInfo = iterator.next(); if (resolveInfo.activityInfo.packageName.equals(packageName)) { iterator.remove(); } } } @Override public Drawable getActivityIcon(Intent intent) { return drawableList.get(intent.getComponent()); } @Override public Drawable getActivityIcon(ComponentName componentName) { return drawableList.get(componentName); } public void addActivityIcon(ComponentName component, Drawable d) { drawableList.put(component, d); } public void addActivityIcon(Intent intent, Drawable d) { drawableList.put(intent.getComponent(), d); } @Override public Intent getLaunchIntentForPackage(String packageName) { Intent intentToResolve = new Intent(Intent.ACTION_MAIN); intentToResolve.addCategory(Intent.CATEGORY_INFO); intentToResolve.setPackage(packageName); List<ResolveInfo> ris = queryIntentActivities(intentToResolve, 0); if (ris == null || ris.isEmpty()) { intentToResolve.removeCategory(Intent.CATEGORY_INFO); intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER); intentToResolve.setPackage(packageName); ris = queryIntentActivities(intentToResolve, 0); } if (ris == null || ris.isEmpty()) { return null; } Intent intent = new Intent(intentToResolve); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setClassName(ris.get(0).activityInfo.packageName, ris.get(0).activityInfo.name); return intent; } @Override public CharSequence getApplicationLabel(ApplicationInfo info) { return info.name; } @Override public void setComponentEnabledSetting(ComponentName componentName, int newState, int flags) { componentList.put(componentName, new ComponentState(newState, flags)); } public void addPreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity) { preferredActivities.put(filter, activity); } @Override public int getPreferredActivities(List<IntentFilter> outFilters, List<ComponentName> outActivities, String packageName) { if (outFilters == null) { return 0; } Set<IntentFilter> filters = preferredActivities.keySet(); for (IntentFilter filter : outFilters) { step: for (IntentFilter testFilter : filters) { ComponentName name = preferredActivities.get(testFilter); // filter out based on the given packageName; if (packageName != null && !name.getPackageName().equals(packageName)) { continue step; } // Check actions Iterator<String> iterator = filter.actionsIterator(); while (iterator.hasNext()) { if (!testFilter.matchAction(iterator.next())) { continue step; } } iterator = filter.categoriesIterator(); while (iterator.hasNext()) { if (!filter.hasCategory(iterator.next())) { continue step; } } if (outActivities == null) { outActivities = new ArrayList<ComponentName>(); } outActivities.add(name); } } return 0; } /** * Non-Android accessor. Use to make assertions on values passed to * setComponentEnabledSetting. * * @param componentName * @return */ public ComponentState getComponentState(ComponentName componentName) { return componentList.get(componentName); } /** * Non-Android accessor. Used to add a package to the list of those * already 'installed' on system. * * @param packageInfo */ public void addPackage(PackageInfo packageInfo) { packageInfos.put(packageInfo.packageName, packageInfo); } public void addPackage(String packageName) { PackageInfo packageInfo = new PackageInfo(); packageInfo.packageName = packageName; ApplicationInfo applicationInfo = new ApplicationInfo(); applicationInfo.packageName = packageName; initApplicationInfo(applicationInfo); packageInfo.applicationInfo = applicationInfo; addPackage(packageInfo); } public void addManifest(AndroidManifest androidManifest) { androidManifests.put(androidManifest.getPackageName(), androidManifest); PackageInfo packageInfo = new PackageInfo(); packageInfo.packageName = androidManifest.getPackageName(); packageInfo.versionName = androidManifest.getVersionName(); packageInfo.versionCode = androidManifest.getVersionCode(); ApplicationInfo applicationInfo = new ApplicationInfo(); applicationInfo.flags = androidManifest.getApplicationFlags(); applicationInfo.targetSdkVersion = androidManifest.getTargetSdkVersion(); applicationInfo.packageName = androidManifest.getPackageName(); applicationInfo.processName = androidManifest.getProcessName(); applicationInfo.name = androidManifest.getApplicationName(); initApplicationInfo(applicationInfo); initApplicationMetaData(applicationInfo, androidManifest); packageInfo.applicationInfo = applicationInfo; addPackage(packageInfo); } private void initApplicationInfo(ApplicationInfo applicationInfo) { applicationInfo.sourceDir = new File(".").getAbsolutePath(); applicationInfo.dataDir = ShadowContext.FILES_DIR.getAbsolutePath(); } private void initApplicationMetaData(ApplicationInfo applicationInfo, AndroidManifest androidManifest) { Map<String, String> meta = androidManifest.getApplicationMetaData(); if (meta.isEmpty()) { return; } applicationInfo.metaData = new Bundle(); for (Entry<String, String> metaEntry : meta.entrySet()) { applicationInfo.metaData.putString(metaEntry.getKey(), metaEntry.getValue()); } } public void removePackage(String packageName) { packageInfos.remove(packageName); } @Override public boolean hasSystemFeature(String name) { return systemFeatureList.containsKey(name) ? systemFeatureList.get(name) : false; } /** * Non-Android accessor. Used to declare a system feature is * or is not supported. * * @param name * @param supported */ public void setSystemFeature(String name, boolean supported) { systemFeatureList.put(name, supported); } public void addDrawableResolution(String packageName, int resourceId, Drawable drawable) { drawables.put(new Pair(packageName, resourceId), drawable); } public class ComponentState { public int newState; public int flags; public ComponentState(int newState, int flags) { this.newState = newState; this.flags = flags; } } @Override public Drawable getDrawable(String packageName, int resourceId, ApplicationInfo applicationInfo) { return drawables.get(new Pair(packageName, resourceId)); } private List<ResolveInfo> findOrCreateInfoList(Intent intent) { List<ResolveInfo> infoList = resolveInfoForIntent.get(intent); if (infoList == null) { infoList = new ArrayList<ResolveInfo>(); resolveInfoForIntent.put(intent, infoList); } return infoList; } private List<ResolveInfo> queryIntent(Intent intent, int flags) { List<ResolveInfo> result = resolveInfoForIntent.get(intent); if (result == null) { return Collections.emptyList(); } else { return result; } } }
Added @Override to methods in IntentComparator
src/main/java/org/robolectric/res/builder/RobolectricPackageManager.java
Added @Override to methods in IntentComparator
<ide><path>rc/main/java/org/robolectric/res/builder/RobolectricPackageManager.java <ide> <ide> private static class IntentComparator implements Comparator<Intent> { <ide> <add> @Override <ide> public int compare(Intent i1, Intent i2) { <ide> if (i1 == null && i2 == null) return 0; <ide> if (i1 == null && i2 != null) return -1; <ide> return 0; <ide> } <ide> <add> @Override <ide> public boolean equals(Intent i1, Intent i2) { <ide> return compare(i1,i2) == 0; <ide> }
Java
apache-2.0
7fcd2d92f17ea8d8720168f6317d6a66fdcc6414
0
HanSolo/Enzo
/* * Copyright (c) 2013, Gerrit Grunwald * All right 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. * The names of its contributors may not 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. */ package eu.hansolo.enzo.qlocktwo; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; /** * Created by * User: hansolo * Date: 27.02.13 * Time: 15:44 */ public class QlockGerman implements Qlock { private static final QlockTwo.Language LANGUAGE = QlockTwo.Language.GERMAN; private static final String[][] MATRIX = { {"E", "S", "K", "I", "S", "T", "A", "F", "Ü", "N", "F"}, {"Z", "E", "H", "N", "Z", "W", "A", "N", "Z", "I", "G"}, {"D", "R", "E", "I", "V", "I", "E", "R", "T", "E", "L"}, {"V", "O", "R", "F", "U", "N", "K", "N", "A", "C", "H"}, {"H", "A", "L", "B", "A", "E", "L", "F", "Ü", "N", "F"}, {"E", "I", "N", "S", "X", "Ä", "M", "Z", "W", "E", "I"}, {"D", "R", "E", "I", "A", "U", "J", "V", "I", "E", "R"}, {"S", "E", "C", "H", "S", "N", "L", "A", "C", "H", "T"}, {"S", "I", "E", "B", "E", "N", "Z", "W", "Ö", "L", "F"}, {"Z", "E", "H", "N", "E", "U", "N", "K", "U", "H", "R"} }; private boolean p1; private boolean p2; private boolean p3; private boolean p4; private final ConcurrentHashMap<Integer, String> LOOKUP; private List<QlockWord> timeList; public QlockGerman() { LOOKUP = new ConcurrentHashMap<>(); LOOKUP.putAll(QlockTwo.Language.GERMAN.getLookup()); timeList = new ArrayList<>(10); } @Override public String[][] getMatrix() { return MATRIX; } @Override public List<QlockWord> getTime(int minute, int hour) { if (hour > 12) { hour -= 12; } if (hour <= 0) { hour += 12; } if (minute > 60) { minute -= 60; hour++; } if (minute < 0) { minute += 60; hour--; } if (minute %5 == 0) { p1 = false; p2 = false; p3 = false; p4 = false; } if (minute %10 == 1 || minute %10 == 6) { p1 = true; } if (minute %10 == 2 || minute %10 == 7) { p1 = true; p2 = true; } if (minute %10 == 3 || minute %10 == 8) { p1 = true; p2 = true; p3 = true; } if (minute %10 == 4 || minute %10 == 9) { p1 = true; p2 = true; p3 = true; p4 = true; } minute -= minute%5; timeList.clear(); timeList.add(QlockLanguage.ES); timeList.add(QlockLanguage.IST); switch (minute) { case 0: timeList.add(hour == 10 ? QlockLanguage.ZEHN1 : QlockLanguage.valueOf(LOOKUP.get(hour))); timeList.add(QlockLanguage.UHR); break; case 5: timeList.add(QlockLanguage.FÜNF1); timeList.add(QlockLanguage.NACH); timeList.add(hour == 10 ? QlockLanguage.ZEHN1 : QlockLanguage.valueOf(LOOKUP.get(hour))); break; case 10: timeList.add(QlockLanguage.ZEHN); timeList.add(QlockLanguage.NACH); timeList.add(hour == 10 ? QlockLanguage.ZEHN1 : QlockLanguage.valueOf(LOOKUP.get(hour))); break; case 15: timeList.add(QlockLanguage.VIERTEL); timeList.add(QlockLanguage.NACH); timeList.add(hour == 10 ? QlockLanguage.ZEHN1 : QlockLanguage.valueOf(LOOKUP.get(hour))); break; case 20: timeList.add(QlockLanguage.ZWANZIG); timeList.add(QlockLanguage.NACH); timeList.add(hour == 10 ? QlockLanguage.ZEHN1 : QlockLanguage.valueOf(LOOKUP.get(hour))); break; case 25: timeList.add(QlockLanguage.FÜNF1); timeList.add(QlockLanguage.VOR); timeList.add(hour == 10 ? QlockLanguage.ZEHN1 : QlockLanguage.HALB); addHour(timeList, hour); break; case 30: timeList.add(QlockLanguage.HALB); addHour(timeList, hour); break; case 35: timeList.add(QlockLanguage.FÜNF1); timeList.add(QlockLanguage.NACH); timeList.add(QlockLanguage.HALB); addHour(timeList, hour); break; case 40: timeList.add(QlockLanguage.ZWANZIG); timeList.add(QlockLanguage.VOR); addHour(timeList, hour); break; case 45: timeList.add(QlockLanguage.VIERTEL); timeList.add(QlockLanguage.VOR); addHour(timeList, hour); break; case 50: timeList.add(QlockLanguage.ZEHN); timeList.add(QlockLanguage.VOR); addHour(timeList, hour); break; case 55: timeList.add(QlockLanguage.FÜNF1); timeList.add(QlockLanguage.VOR); addHour(timeList, hour); break; } return timeList; } @Override public boolean isP1() { return p1; } @Override public boolean isP2() { return p2; } @Override public boolean isP3() { return p3; } @Override public boolean isP4() { return p4; } @Override public QlockTwo.Language getLanguage() { return LANGUAGE; } private void addHour(List<QlockWord> timeList, final int HOUR) { if (HOUR == 12) { timeList.add(QlockLanguage.EINS); } else if (HOUR == 5) { timeList.add(QlockLanguage.FÜNF2); } else { if (HOUR + 1 == 5) { timeList.add(QlockLanguage.FÜNF2); } else if (HOUR + 1 == 10) { timeList.add(QlockLanguage.ZEHN1); } else { timeList.add(QlockLanguage.valueOf(LOOKUP.get(HOUR + 1))); } } } private enum QlockLanguage implements QlockWord { EINS(5, 0, 3), ZWEI(5, 7, 10), DREI(2, 0, 3), VIER(6, 7, 10), FÜNF(4, 7, 10), FÜNF1(0, 7, 10), FÜNF2(4, 7, 10), SECHS(7, 0, 4), SIEBEN(8, 0, 5), ACHT(7, 7, 10), NEUN(9, 3, 6), ZEHN(1, 0, 3), ZEHN1(9, 0, 3), ELF(4, 5, 7), ZWÖLF(8, 6, 10), ES(0, 0, 1), IST(0, 3, 5), VOR(3, 0, 2), NACH(3, 7, 10), VIERTEL(2, 4, 10), DREIVIERTEL(2, 0, 10), HALB(4, 0, 3), ZWANZIG(1, 4, 10), UHR(9, 8, 10); private final int ROW; private final int START; private final int STOP; private QlockLanguage(final int ROW, final int START, final int STOP) { this.ROW = ROW; this.START = START; this.STOP = STOP; } @Override public int getRow() { return ROW; } @Override public int getStart() { return START; } @Override public int getStop() { return STOP; } } }
src/eu/hansolo/enzo/qlocktwo/QlockGerman.java
/* * Copyright (c) 2013, Gerrit Grunwald * All right 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. * The names of its contributors may not 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. */ package eu.hansolo.enzo.qlocktwo; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; /** * Created by * User: hansolo * Date: 27.02.13 * Time: 15:44 */ public class QlockGerman implements Qlock { private static final QlockTwo.Language LANGUAGE = QlockTwo.Language.GERMAN; private static final String[][] MATRIX = { {"E", "S", "K", "I", "S", "T", "A", "F", "Ü", "N", "F"}, {"Z", "E", "H", "N", "Z", "W", "A", "N", "Z", "I", "G"}, {"D", "R", "E", "I", "V", "I", "E", "R", "T", "E", "L"}, {"V", "O", "R", "F", "U", "N", "K", "N", "A", "C", "H"}, {"H", "A", "L", "B", "A", "E", "L", "F", "Ü", "N", "F"}, {"E", "I", "N", "S", "X", "Ä", "M", "Z", "W", "E", "I"}, {"D", "R", "E", "I", "A", "U", "J", "V", "I", "E", "R"}, {"S", "E", "C", "H", "S", "N", "L", "A", "C", "H", "T"}, {"S", "I", "E", "B", "E", "N", "Z", "W", "Ö", "L", "F"}, {"Z", "E", "H", "N", "E", "U", "N", "K", "U", "H", "R"} }; private boolean p1; private boolean p2; private boolean p3; private boolean p4; private final ConcurrentHashMap<Integer, String> LOOKUP; private List<QlockWord> timeList; public QlockGerman() { LOOKUP = new ConcurrentHashMap<>(); LOOKUP.putAll(QlockTwo.Language.GERMAN.getLookup()); timeList = new ArrayList<>(10); } @Override public String[][] getMatrix() { return MATRIX; } @Override public List<QlockWord> getTime(int minute, int hour) { if (hour > 12) { hour -= 12; } if (hour <= 0) { hour += 12; } if (minute > 60) { minute -= 60; hour++; } if (minute < 0) { minute += 60; hour--; } if (minute %5 == 0) { p1 = false; p2 = false; p3 = false; p4 = false; } if (minute %10 == 1 || minute %10 == 6) { p1 = true; } if (minute %10 == 2 || minute %10 == 7) { p1 = true; p2 = true; } if (minute %10 == 3 || minute %10 == 8) { p1 = true; p2 = true; p3 = true; } if (minute %10 == 4 || minute %10 == 9) { p1 = true; p2 = true; p3 = true; p4 = true; } minute -= minute%5; timeList.clear(); timeList.add(QlockLanguage.ES); timeList.add(QlockLanguage.IST); switch (minute) { case 0: timeList.add(hour == 10 ? QlockLanguage.ZEHN1 : QlockLanguage.valueOf(LOOKUP.get(hour))); timeList.add(QlockLanguage.UHR); break; case 5: timeList.add(QlockLanguage.FÜNF1); timeList.add(QlockLanguage.NACH); timeList.add(hour == 10 ? QlockLanguage.ZEHN1 : QlockLanguage.valueOf(LOOKUP.get(hour))); break; case 10: timeList.add(QlockLanguage.ZEHN); timeList.add(QlockLanguage.NACH); timeList.add(hour == 10 ? QlockLanguage.ZEHN1 : QlockLanguage.valueOf(LOOKUP.get(hour))); break; case 15: timeList.add(QlockLanguage.VIERTEL); timeList.add(QlockLanguage.NACH); timeList.add(hour == 10 ? QlockLanguage.ZEHN1 : QlockLanguage.valueOf(LOOKUP.get(hour))); break; case 20: timeList.add(QlockLanguage.ZWANZIG); timeList.add(QlockLanguage.NACH); timeList.add(hour == 10 ? QlockLanguage.ZEHN1 : QlockLanguage.valueOf(LOOKUP.get(hour))); break; case 25: timeList.add(QlockLanguage.FÜNF1); timeList.add(QlockLanguage.VOR); timeList.add(hour == 10 ? QlockLanguage.ZEHN1 : QlockLanguage.HALB); addHour(timeList, hour); break; case 30: timeList.add(QlockLanguage.HALB); addHour(timeList, hour); break; case 35: timeList.add(QlockLanguage.FÜNF1); timeList.add(QlockLanguage.NACH); timeList.add(QlockLanguage.HALB); addHour(timeList, hour); break; case 40: timeList.add(QlockLanguage.ZWANZIG); timeList.add(QlockLanguage.VOR); addHour(timeList, hour); break; case 45: timeList.add(QlockLanguage.VIERTEL); timeList.add(QlockLanguage.VOR); addHour(timeList, hour); break; case 50: timeList.add(QlockLanguage.ZEHN); timeList.add(QlockLanguage.VOR); addHour(timeList, hour); break; case 55: timeList.add(QlockLanguage.FÜNF1); timeList.add(QlockLanguage.VOR); addHour(timeList, hour); break; } return timeList; } @Override public boolean isP1() { return p1; } @Override public boolean isP2() { return p2; } @Override public boolean isP3() { return p3; } @Override public boolean isP4() { return p4; } @Override public QlockTwo.Language getLanguage() { return LANGUAGE; } private void addHour(List<QlockWord> timeList, final int HOUR) { if (HOUR == 12) { timeList.add(QlockLanguage.EINS); } else if (HOUR == 5) { timeList.add(QlockLanguage.FÜNF2); } else { if (HOUR + 1 == 5) { timeList.add(QlockLanguage.FÜNF2); } else if (HOUR + 1 == 10) { timeList.add(QlockLanguage.ZEHN1); } else { timeList.add(QlockLanguage.valueOf(LOOKUP.get(HOUR + 1))); } } } private enum QlockLanguage implements QlockWord { EINS(5, 0, 3), ZWEI(5, 7, 10), DREI(2, 0, 3), VIER(6, 7, 10), FÜNF(4, 7, 0), FÜNF1(0, 7, 10), FÜNF2(4, 7, 10), SECHS(7, 0, 4), SIEBEN(8, 0, 5), ACHT(7, 7, 10), NEUN(9, 3, 6), ZEHN(1, 0, 3), ZEHN1(9, 0, 3), ELF(4, 5, 7), ZWÖLF(8, 6, 10), ES(0, 0, 1), IST(0, 3, 5), VOR(3, 0, 2), NACH(3, 7, 10), VIERTEL(2, 4, 10), DREIVIERTEL(2, 0, 10), HALB(4, 0, 3), ZWANZIG(1, 4, 10), UHR(9, 8, 10); private final int ROW; private final int START; private final int STOP; private QlockLanguage(final int ROW, final int START, final int STOP) { this.ROW = ROW; this.START = START; this.STOP = STOP; } @Override public int getRow() { return ROW; } @Override public int getStart() { return START; } @Override public int getStop() { return STOP; } } }
fixed typo in QlockGerman
src/eu/hansolo/enzo/qlocktwo/QlockGerman.java
fixed typo in QlockGerman
<ide><path>rc/eu/hansolo/enzo/qlocktwo/QlockGerman.java <ide> ZWEI(5, 7, 10), <ide> DREI(2, 0, 3), <ide> VIER(6, 7, 10), <del> FÜNF(4, 7, 0), <add> FÜNF(4, 7, 10), <ide> FÜNF1(0, 7, 10), <ide> FÜNF2(4, 7, 10), <ide> SECHS(7, 0, 4),
JavaScript
mit
bad2069bf8d3df546037c0f31c71c5d5e4cd649e
0
tetranz/select2entity-bundle,tetranz/select2entity-bundle,tetranz/select2entity-bundle
$(document).ready(function () { $.fn.select2entity = function (options) { this.each(function () { var request; // Keep a reference to the element so we can keep the cache local to this instance and so we can // fetch config settings since select2 doesn't expose its options to the transport method. var $s2 = $(this), limit = $s2.data('page-limit') || 0, scroll = $s2.data('scroll'), prefix = Date.now(), cache = []; $s2.select2($.extend({ // Tags support createTag: function (data) { if ($s2.data('tags') && data.term.length > 0) { var text = data.term + $s2.data('tags-text'); return { id: $s2.data('new-tag-prefix')+data.term, text: text }; } }, ajax: { transport: function (params, success, failure) { // is caching enabled? if ($s2.data('ajax--cache')) { // try to make the key unique to make it less likely for a page+q to match a real query var key = prefix + ' page:' + (params.data.page || 1) + ' ' + params.data.q, cacheTimeout = $s2.data('ajax--cacheTimeout'); // no cache entry for 'term' or the cache has timed out? if (typeof cache[key] == 'undefined' || (cacheTimeout && Date.now() >= cache[key].time)) { $.ajax(params).fail(failure).done(function (data) { cache[key] = { data: data, time: cacheTimeout ? Date.now() + cacheTimeout : null }; success(data); }); } else { // return cached data with no ajax request success(cache[key].data); } } else { // no caching enabled. just do the ajax request if (request) { request.abort(); } request = $.ajax(params).fail(failure).done(success).always(function () { request = undefined; }); } }, data: function (params) { // only send the 'page' parameter if scrolling is enabled if (scroll) { return { q: params.term, page: params.page || 1 }; } return { q: params.term }; }, processResults: function (data, params) { var results, more = false, response = {}; params.page = params.page || 1; if ($.isArray(data)) { results = data; } else if (typeof data == 'object') { // assume remote result was proper object results = data.results; more = data.more; } else { // failsafe results = []; } if (scroll) { response.pagination = {more: more}; } response.results = results; return response; } } }, options || {})); }); return this; }; $('.select2entity').select2entity(); });
Resources/public/js/select2entity.js
$(document).ready(function () { $.fn.select2entity = function (options) { this.each(function () { // Keep a reference to the element so we can keep the cache local to this instance and so we can // fetch config settings since select2 doesn't expose its options to the transport method. var $s2 = $(this), limit = $s2.data('page-limit') || 0, scroll = $s2.data('scroll'), prefix = Date.now(), cache = []; $s2.select2($.extend({ // Tags support createTag: function (data) { if ($s2.data('tags') && data.term.length > 0) { var text = data.term + $s2.data('tags-text'); return { id: $s2.data('new-tag-prefix')+data.term, text: text }; } }, ajax: { transport: function (params, success, failure) { // is caching enabled? if ($s2.data('ajax--cache')) { // try to make the key unique to make it less likely for a page+q to match a real query var key = prefix + ' page:' + (params.data.page || 1) + ' ' + params.data.q, cacheTimeout = $s2.data('ajax--cacheTimeout'); // no cache entry for 'term' or the cache has timed out? if (typeof cache[key] == 'undefined' || (cacheTimeout && Date.now() >= cache[key].time)) { $.ajax(params).fail(failure).done(function (data) { cache[key] = { data: data, time: cacheTimeout ? Date.now() + cacheTimeout : null }; success(data); }); } else { // return cached data with no ajax request success(cache[key].data); } } else { // no caching enabled. just do the ajax request $.ajax(params).fail(failure).done(success); } }, data: function (params) { // only send the 'page' parameter if scrolling is enabled if (scroll) { return { q: params.term, page: params.page || 1 }; } return { q: params.term }; }, processResults: function (data, params) { var results, more = false, response = {}; params.page = params.page || 1; if ($.isArray(data)) { results = data; } else if (typeof data == 'object') { // assume remote result was proper object results = data.results; more = data.more; } else { // failsafe results = []; } if (scroll) { response.pagination = {more: more}; } response.results = results; return response; } } }, options || {})); }); return this; }; $('.select2entity').select2entity(); });
Abort previous AJAX request
Resources/public/js/select2entity.js
Abort previous AJAX request
<ide><path>esources/public/js/select2entity.js <ide> $(document).ready(function () { <ide> $.fn.select2entity = function (options) { <ide> this.each(function () { <add> var request; <add> <ide> // Keep a reference to the element so we can keep the cache local to this instance and so we can <ide> // fetch config settings since select2 doesn't expose its options to the transport method. <ide> var $s2 = $(this), <ide> } <ide> } else { <ide> // no caching enabled. just do the ajax request <del> $.ajax(params).fail(failure).done(success); <add> if (request) { <add> request.abort(); <add> } <add> request = $.ajax(params).fail(failure).done(success).always(function () { <add> request = undefined; <add> }); <ide> } <ide> }, <ide> data: function (params) {
Java
lgpl-2.1
b115de13764e32bbd9a8ec40926f949ea066393e
0
janissl/languagetool,jimregan/languagetool,janissl/languagetool,languagetool-org/languagetool,meg0man/languagetool,janissl/languagetool,meg0man/languagetool,languagetool-org/languagetool,meg0man/languagetool,janissl/languagetool,languagetool-org/languagetool,lopescan/languagetool,meg0man/languagetool,lopescan/languagetool,jimregan/languagetool,janissl/languagetool,jimregan/languagetool,meg0man/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,lopescan/languagetool,janissl/languagetool,lopescan/languagetool,jimregan/languagetool,jimregan/languagetool,lopescan/languagetool
/* LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * Copyright (C) 2013 Stefan Lotties * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.tagging.disambiguation.rules; import org.languagetool.AnalyzedSentence; import org.languagetool.AnalyzedToken; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.chunking.ChunkTag; import org.languagetool.rules.patterns.*; import org.languagetool.tools.StringTools; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @since 2.3 */ class DisambiguationPatternRuleReplacer extends AbstractPatternRulePerformer { List<Boolean> elementsMatched; public DisambiguationPatternRuleReplacer(DisambiguationPatternRule rule) { super(rule, rule.getLanguage().getDisambiguationUnifier()); elementsMatched = new ArrayList<>(rule.getPatternElements().size()); } public final AnalyzedSentence replace(final AnalyzedSentence sentence) throws IOException { List<ElementMatcher> elementMatchers = createElementMatchers(); final AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace(); AnalyzedTokenReadings[] whTokens = sentence.getTokens(); final int[] tokenPositions = new int[tokens.length + 1]; final int patternSize = elementMatchers.size(); final int limit = Math.max(0, tokens.length - patternSize + 1); ElementMatcher elem = null; boolean changed = false; elementsMatched.clear(); for (int j = 0; j < patternSize; j++) { elementsMatched.add(false); } int i = 0; int minOccurCorrection = getMinOccurrenceCorrection(); while (i < limit + minOccurCorrection && !(rule.isSentStart() && i > 0)) { boolean allElementsMatch = false; unifiedTokens = null; for (boolean elementMatched : elementsMatched) { elementMatched = false; } int matchingTokens = 0; int skipShiftTotal = 0; int firstMatchToken = -1; int lastMatchToken = -1; int firstMarkerMatchToken = -1; int lastMarkerMatchToken = -1; int prevSkipNext = 0; if (rule.isTestUnification()) { unifier.reset(); } int minOccurSkip = 0; for (int k = 0; k < patternSize; k++) { final ElementMatcher prevElement = elem; elem = elementMatchers.get(k); elem.resolveReference(firstMatchToken, tokens, rule.getLanguage()); final int nextPos = i + k + skipShiftTotal - minOccurSkip; prevMatched = false; if (prevSkipNext + nextPos >= tokens.length || prevSkipNext < 0) { // SENT_END? prevSkipNext = tokens.length - (nextPos + 1); } final int maxTok = Math.min(nextPos + prevSkipNext, tokens.length - (patternSize - k) + minOccurCorrection); for (int m = nextPos; m <= maxTok; m++) { allElementsMatch = testAllReadings(tokens, elem, prevElement, m, firstMatchToken, prevSkipNext); if (elem.getElement().getMinOccurrence() == 0) { final ElementMatcher nextElement = elementMatchers.get(k + 1); final boolean nextElementMatch = testAllReadings(tokens, nextElement, elem, m, firstMatchToken, prevSkipNext); if (nextElementMatch) { // this element doesn't match, but it's optional so accept this and continue allElementsMatch = true; minOccurSkip++; elementsMatched.set(k, false); break; } } if (allElementsMatch) { elementsMatched.set(k, true); int skipForMax = skipMaxTokens(tokens, elem, firstMatchToken, prevSkipNext, prevElement, m, patternSize - k -1); lastMatchToken = m + skipForMax; final int skipShift = lastMatchToken - nextPos; tokenPositions[matchingTokens] = skipShift + 1; prevSkipNext = elem.getElement().getSkipNext(); matchingTokens++; skipShiftTotal += skipShift; if (firstMatchToken == -1) { firstMatchToken = lastMatchToken - skipForMax; } if (firstMarkerMatchToken == -1 && elem.getElement().isInsideMarker()) { firstMarkerMatchToken = lastMatchToken - skipForMax; } if (elem.getElement().isInsideMarker()) { lastMarkerMatchToken = lastMatchToken; } break; } } if (!allElementsMatch) { break; } } if (allElementsMatch && matchingTokens == patternSize || matchingTokens == patternSize - minOccurSkip && firstMatchToken != -1) { whTokens = executeAction(sentence, whTokens, unifiedTokens, firstMatchToken, lastMarkerMatchToken, matchingTokens, tokenPositions); changed = true; } i++; } if (changed) { return new AnalyzedSentence(whTokens, sentence.getWhPositions()); } return sentence; } @Override protected int skipMaxTokens(AnalyzedTokenReadings[] tokens, ElementMatcher elem, int firstMatchToken, int prevSkipNext, ElementMatcher prevElement, int m, int remainingElems) throws IOException { int maxSkip = 0; int maxOccurrences = elem.getElement().getMaxOccurrence() == -1 ? Integer.MAX_VALUE : elem.getElement().getMaxOccurrence(); for (int j = 1; j < maxOccurrences && m+j < tokens.length - remainingElems; j++) { boolean nextAllElementsMatch = testAllReadings(tokens, elem, prevElement, m+j, firstMatchToken, prevSkipNext); if (nextAllElementsMatch) { maxSkip++; } else { break; } } return maxSkip; } private AnalyzedTokenReadings[] executeAction(final AnalyzedSentence sentence, final AnalyzedTokenReadings[] whiteTokens, final AnalyzedTokenReadings[] unifiedTokens, final int firstMatchToken, int lastMatchToken, final int matchingTokens, final int[] tokenPositions) { final AnalyzedTokenReadings[] whTokens = whiteTokens.clone(); final DisambiguationPatternRule rule = (DisambiguationPatternRule) this.rule; int correctedStPos = 0; int startPositionCorrection = rule.getStartPositionCorrection(); int endPositionCorrection = rule.getEndPositionCorrection(); int matchingTokensWithCorrection = matchingTokens; int w = startPositionCorrection; for (int j = 0; j < w; j++) { if (!elementsMatched.get(j)) { startPositionCorrection--; } } if (startPositionCorrection > 0) { for (int l = 0; l <= startPositionCorrection; l++) { correctedStPos += tokenPositions[l]; } correctedStPos--; } // adjust positions in case elements with min="0" were not matched before the starting position for (int j = 0; j <= startPositionCorrection && j < elementsMatched.size(); j++) { if (!elementsMatched.get(j)) { correctedStPos -= tokenPositions[j]; } } int j = 0; while (startPositionCorrection + j < elementsMatched.size() && !elementsMatched.get(startPositionCorrection + j)) { correctedStPos += tokenPositions[j]; j++; } if (endPositionCorrection < 0) { // adjust the end position correction if one of the elements has not been matched for (int d = startPositionCorrection; d < elementsMatched.size(); d++) { if (!elementsMatched.get(d)) { endPositionCorrection++; } } } if (lastMatchToken != -1) { int maxPosCorrection = 0; maxPosCorrection = Math.max((lastMatchToken + 1 - (firstMatchToken + correctedStPos)) - matchingTokens, 0); matchingTokensWithCorrection += maxPosCorrection; } final int fromPos = sentence.getOriginalPosition(firstMatchToken + correctedStPos); final boolean spaceBefore = whTokens[fromPos].isWhitespaceBefore(); boolean filtered = false; final DisambiguationPatternRule.DisambiguatorAction disAction = rule.getAction(); final AnalyzedToken[] newTokenReadings = rule.getNewTokenReadings(); final Match matchElement = rule.getMatchElement(); final String disambiguatedPOS = rule.getDisambiguatedPOS(); switch (disAction) { case UNIFY: if (unifiedTokens != null) { //TODO: unifiedTokens.length is larger > matchingTokensWithCorrection in cases where there are no markers... if (unifiedTokens.length == matchingTokensWithCorrection - startPositionCorrection + endPositionCorrection) { if (whTokens[sentence.getOriginalPosition(firstMatchToken + correctedStPos + unifiedTokens.length - 1)].isSentenceEnd()) { unifiedTokens[unifiedTokens.length - 1].setSentEnd(); } for (int i = 0; i < unifiedTokens.length; i++) { final int position = sentence.getOriginalPosition(firstMatchToken + correctedStPos + i); unifiedTokens[i].setStartPos(whTokens[position].getStartPos()); final String prevValue = whTokens[position].toString(); final String prevAnot = whTokens[position].getHistoricalAnnotations(); List<ChunkTag> chTags = whTokens[position].getChunkTags(); whTokens[position] = unifiedTokens[i]; whTokens[position].setChunkTags(chTags); annotateChange(whTokens[position], prevValue, prevAnot); } } } break; case REMOVE: if (newTokenReadings != null && newTokenReadings.length > 0) { if (newTokenReadings.length == matchingTokensWithCorrection - startPositionCorrection + endPositionCorrection) { for (int i = 0; i < newTokenReadings.length; i++) { final int position = sentence.getOriginalPosition(firstMatchToken + correctedStPos + i); final String prevValue = whTokens[position].toString(); final String prevAnot = whTokens[position].getHistoricalAnnotations(); whTokens[position].removeReading(newTokenReadings[i]); annotateChange(whTokens[position], prevValue, prevAnot); } } } else if (!StringTools.isEmpty(disambiguatedPOS)) { // negative filtering Pattern p = Pattern.compile(disambiguatedPOS); AnalyzedTokenReadings tmp = new AnalyzedTokenReadings(whTokens[fromPos].getReadings(), whTokens[fromPos].getStartPos()); for (AnalyzedToken analyzedToken : tmp) { if (analyzedToken.getPOSTag() != null) { final Matcher mPos = p.matcher(analyzedToken.getPOSTag()); if (mPos.matches()) { final int position = sentence.getOriginalPosition(firstMatchToken + correctedStPos); final String prevValue = whTokens[position].toString(); final String prevAnot = whTokens[position].getHistoricalAnnotations(); whTokens[position].removeReading(analyzedToken); annotateChange(whTokens[position], prevValue, prevAnot); } } } } break; case ADD: if (newTokenReadings != null) { if (newTokenReadings.length == matchingTokensWithCorrection - startPositionCorrection + endPositionCorrection) { for (int i = 0; i < newTokenReadings.length; i++) { final String token; final int position = sentence.getOriginalPosition(firstMatchToken + correctedStPos + i); if ("".equals(newTokenReadings[i].getToken())) { // empty token token = whTokens[position].getToken(); } else { token = newTokenReadings[i].getToken(); } final String lemma; if (newTokenReadings[i].getLemma() == null) { // empty lemma lemma = token; } else { lemma = newTokenReadings[i].getLemma(); } final AnalyzedToken newTok = new AnalyzedToken(token, newTokenReadings[i].getPOSTag(), lemma); final String prevValue = whTokens[position].toString(); final String prevAnot = whTokens[position].getHistoricalAnnotations(); whTokens[position].addReading(newTok); annotateChange(whTokens[position], prevValue, prevAnot); } } } break; case FILTERALL: for (int i = 0; i < matchingTokensWithCorrection - startPositionCorrection + endPositionCorrection; i++) { final int position = sentence.getOriginalPosition(firstMatchToken + correctedStPos + i); Element myEl; if (elementsMatched.get(i + startPositionCorrection)) { myEl = rule.getPatternElements().get(i + startPositionCorrection); } else { int k = 1; while (i + startPositionCorrection + k < rule.getPatternElements().size() + endPositionCorrection && !elementsMatched.get(i + startPositionCorrection + k)) { k++; } //FIXME: this is left to see whether this fails anywhere assert(i + k + startPositionCorrection < rule.getPatternElements().size()); myEl = rule.getPatternElements().get(i + k + startPositionCorrection); } final Match tmpMatchToken = new Match(myEl.getPOStag(), null, true, myEl.getPOStag(), null, Match.CaseConversion.NONE, false, false, Match.IncludeRange.NONE); MatchState matchState = tmpMatchToken.createState(rule.getLanguage().getSynthesizer(), whTokens[position]); final String prevValue = whTokens[position].toString(); final String prevAnot = whTokens[position].getHistoricalAnnotations(); whTokens[position] = matchState.filterReadings(); annotateChange(whTokens[position], prevValue, prevAnot); } break; case IMMUNIZE: for (int i = 0; i < matchingTokensWithCorrection - startPositionCorrection + endPositionCorrection; i++) { whTokens[sentence.getOriginalPosition(firstMatchToken + correctedStPos + i)].immunize(); } break; case IGNORE_SPELLING: for (int i = 0; i < matchingTokensWithCorrection - startPositionCorrection + endPositionCorrection; i++) { whTokens[sentence.getOriginalPosition(firstMatchToken + correctedStPos + i)].ignoreSpelling(); } break; case FILTER: if (matchElement == null) { // same as REPLACE if using <match> final Match tmpMatchToken = new Match(disambiguatedPOS, null, true, disambiguatedPOS, null, Match.CaseConversion.NONE, false, false, Match.IncludeRange.NONE); final MatchState matchState = tmpMatchToken.createState(rule.getLanguage().getSynthesizer(), whTokens[fromPos]); final String prevValue = whTokens[fromPos].toString(); final String prevAnot = whTokens[fromPos].getHistoricalAnnotations(); whTokens[fromPos] = matchState.filterReadings(); annotateChange(whTokens[fromPos], prevValue, prevAnot); filtered = true; } //fallthrough case REPLACE: default: if (!filtered) { if (newTokenReadings != null && newTokenReadings.length > 0) { if (newTokenReadings.length == matchingTokensWithCorrection - startPositionCorrection + endPositionCorrection) { for (int i = 0; i < newTokenReadings.length; i++) { final String token; final int position = sentence.getOriginalPosition(firstMatchToken + correctedStPos + i); if ("".equals(newTokenReadings[i].getToken())) { // empty token token = whTokens[position].getToken(); } else { token = newTokenReadings[i].getToken(); } final String lemma; if (newTokenReadings[i].getLemma() == null) { // empty lemma lemma = token; } else { lemma = newTokenReadings[i].getLemma(); } final AnalyzedToken analyzedToken = new AnalyzedToken(token, newTokenReadings[i].getPOSTag(), lemma); final AnalyzedTokenReadings toReplace = new AnalyzedTokenReadings( analyzedToken, whTokens[fromPos].getStartPos()); whTokens[position] = replaceTokens( whTokens[position], toReplace); } } } else if (matchElement == null) { String lemma = ""; for (AnalyzedToken analyzedToken : whTokens[fromPos]) { if (analyzedToken.getPOSTag() != null && analyzedToken.getPOSTag().equals(disambiguatedPOS) && analyzedToken.getLemma() != null) { lemma = analyzedToken.getLemma(); } } if (StringTools.isEmpty(lemma)) { lemma = whTokens[fromPos].getAnalyzedToken(0).getLemma(); } final AnalyzedToken analyzedToken = new AnalyzedToken(whTokens[fromPos].getToken(), disambiguatedPOS, lemma); final AnalyzedTokenReadings toReplace = new AnalyzedTokenReadings( analyzedToken, whTokens[fromPos].getStartPos()); whTokens[fromPos] = replaceTokens(whTokens[fromPos], toReplace); } else { // using the match element final MatchState matchElementState = matchElement.createState(rule.getLanguage().getSynthesizer(), whTokens[fromPos]); final String prevValue = whTokens[fromPos].toString(); final String prevAnot = whTokens[fromPos].getHistoricalAnnotations(); whTokens[fromPos] = matchElementState.filterReadings(); whTokens[fromPos].setWhitespaceBefore(spaceBefore); annotateChange(whTokens[fromPos], prevValue, prevAnot); } } } return whTokens; } private void annotateChange(AnalyzedTokenReadings atr, final String prevValue, String prevAnot) { atr.setHistoricalAnnotations(prevAnot + "\n" + rule.getId() + ":" + rule.getSubId() + " " + prevValue + " -> " + atr.toString()); } private AnalyzedTokenReadings replaceTokens(AnalyzedTokenReadings oldAtr, final AnalyzedTokenReadings newAtr) { final String prevValue = oldAtr.toString(); final String prevAnot = oldAtr.getHistoricalAnnotations(); final boolean isSentEnd = oldAtr.isSentenceEnd(); final boolean isParaEnd = oldAtr.isParagraphEnd(); final boolean spaceBefore = oldAtr.isWhitespaceBefore(); final int startPosition = oldAtr.getStartPos(); final List<ChunkTag> chunkTags = oldAtr.getChunkTags(); if (isSentEnd) { newAtr.setSentEnd(); } if (isParaEnd) { newAtr.setParagraphEnd(); } newAtr.setWhitespaceBefore(spaceBefore); newAtr.setStartPos(startPosition); newAtr.setChunkTags(chunkTags); if (oldAtr.isImmunized()) { newAtr.immunize(); } annotateChange(newAtr, prevValue, prevAnot); return newAtr; } }
languagetool-core/src/main/java/org/languagetool/tagging/disambiguation/rules/DisambiguationPatternRuleReplacer.java
/* LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * Copyright (C) 2013 Stefan Lotties * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.tagging.disambiguation.rules; import org.languagetool.AnalyzedSentence; import org.languagetool.AnalyzedToken; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.chunking.ChunkTag; import org.languagetool.rules.patterns.*; import org.languagetool.tools.StringTools; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @since 2.3 */ class DisambiguationPatternRuleReplacer extends AbstractPatternRulePerformer { List<Boolean> elementsMatched; public DisambiguationPatternRuleReplacer(DisambiguationPatternRule rule) { super(rule, rule.getLanguage().getDisambiguationUnifier()); elementsMatched = new ArrayList<>(rule.getPatternElements().size()); } public final AnalyzedSentence replace(final AnalyzedSentence sentence) throws IOException { List<ElementMatcher> elementMatchers = createElementMatchers(); final AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace(); AnalyzedTokenReadings[] whTokens = sentence.getTokens(); final int[] tokenPositions = new int[tokens.length + 1]; final int patternSize = elementMatchers.size(); final int limit = Math.max(0, tokens.length - patternSize + 1); ElementMatcher elem = null; boolean changed = false; elementsMatched.clear(); for (int j = 0; j < patternSize; j++) { elementsMatched.add(false); } int i = 0; int minOccurCorrection = getMinOccurrenceCorrection(); while (i < limit + minOccurCorrection && !(rule.isSentStart() && i > 0)) { boolean allElementsMatch = false; unifiedTokens = null; for (boolean elementMatched : elementsMatched) { elementMatched = false; } int matchingTokens = 0; int skipShiftTotal = 0; int firstMatchToken = -1; int lastMatchToken = -1; int firstMarkerMatchToken = -1; int lastMarkerMatchToken = -1; int prevSkipNext = 0; if (rule.isTestUnification()) { unifier.reset(); } int minOccurSkip = 0; for (int k = 0; k < patternSize; k++) { final ElementMatcher prevElement = elem; elem = elementMatchers.get(k); elem.resolveReference(firstMatchToken, tokens, rule.getLanguage()); final int nextPos = i + k + skipShiftTotal - minOccurSkip; prevMatched = false; if (prevSkipNext + nextPos >= tokens.length || prevSkipNext < 0) { // SENT_END? prevSkipNext = tokens.length - (nextPos + 1); } final int maxTok = Math.min(nextPos + prevSkipNext, tokens.length - (patternSize - k) + minOccurCorrection); for (int m = nextPos; m <= maxTok; m++) { allElementsMatch = testAllReadings(tokens, elem, prevElement, m, firstMatchToken, prevSkipNext); if (elem.getElement().getMinOccurrence() == 0) { final ElementMatcher nextElement = elementMatchers.get(k + 1); final boolean nextElementMatch = testAllReadings(tokens, nextElement, elem, m, firstMatchToken, prevSkipNext); if (nextElementMatch) { // this element doesn't match, but it's optional so accept this and continue allElementsMatch = true; minOccurSkip++; elementsMatched.set(k, false); break; } } if (allElementsMatch) { elementsMatched.set(k, true); int skipForMax = skipMaxTokens(tokens, elem, firstMatchToken, prevSkipNext, prevElement, m, patternSize - k -1); lastMatchToken = m + skipForMax; final int skipShift = lastMatchToken - nextPos; tokenPositions[matchingTokens] = skipShift + 1; prevSkipNext = elem.getElement().getSkipNext(); matchingTokens++; skipShiftTotal += skipShift; if (firstMatchToken == -1) { firstMatchToken = lastMatchToken - skipForMax; } if (firstMarkerMatchToken == -1 && elem.getElement().isInsideMarker()) { firstMarkerMatchToken = lastMatchToken - skipForMax; } if (elem.getElement().isInsideMarker()) { lastMarkerMatchToken = lastMatchToken; } break; } } if (!allElementsMatch) { break; } } if (allElementsMatch && matchingTokens == patternSize || matchingTokens == patternSize - minOccurSkip && firstMatchToken != -1) { whTokens = executeAction(sentence, whTokens, unifiedTokens, firstMatchToken, lastMarkerMatchToken, matchingTokens, tokenPositions); changed = true; } i++; } if (changed) { return new AnalyzedSentence(whTokens, sentence.getWhPositions()); } return sentence; } @Override protected int skipMaxTokens(AnalyzedTokenReadings[] tokens, ElementMatcher elem, int firstMatchToken, int prevSkipNext, ElementMatcher prevElement, int m, int remainingElems) throws IOException { int maxSkip = 0; int maxOccurrences = elem.getElement().getMaxOccurrence() == -1 ? Integer.MAX_VALUE : elem.getElement().getMaxOccurrence(); for (int j = 1; j < maxOccurrences && m+j < tokens.length - remainingElems; j++) { boolean nextAllElementsMatch = testAllReadings(tokens, elem, prevElement, m+j, firstMatchToken, prevSkipNext); if (nextAllElementsMatch) { maxSkip++; } else { break; } } return maxSkip; } private AnalyzedTokenReadings[] executeAction(final AnalyzedSentence sentence, final AnalyzedTokenReadings[] whiteTokens, final AnalyzedTokenReadings[] unifiedTokens, final int firstMatchToken, int lastMatchToken, final int matchingTokens, final int[] tokenPositions) { final AnalyzedTokenReadings[] whTokens = whiteTokens.clone(); final DisambiguationPatternRule rule = (DisambiguationPatternRule) this.rule; int correctedStPos = 0; int startPositionCorrection = rule.getStartPositionCorrection(); int endPositionCorrection = rule.getEndPositionCorrection(); int matchingTokensWithCorrection = matchingTokens; int w = startPositionCorrection; for (int j = 0; j < w; j++) { if (!elementsMatched.get(j)) { startPositionCorrection--; } } if (startPositionCorrection > 0) { for (int l = 0; l <= startPositionCorrection; l++) { correctedStPos += tokenPositions[l]; } correctedStPos--; } // adjust positions in case elements with min="0" were not matched before the starting position for (int j = 0; j <= startPositionCorrection && j < elementsMatched.size(); j++) { if (!elementsMatched.get(j)) { correctedStPos -= tokenPositions[j]; } } int j = 0; while (startPositionCorrection + j < elementsMatched.size() && !elementsMatched.get(startPositionCorrection + j)) { correctedStPos += tokenPositions[j]; j++; } if (endPositionCorrection < 0) { // adjust the end position correction if one of the elements has not been matched for (int d = startPositionCorrection; d < elementsMatched.size(); d++) { if (!elementsMatched.get(d)) { endPositionCorrection++; } } } if (lastMatchToken != -1) { int maxPosCorrection = 0; maxPosCorrection = Math.max((lastMatchToken + 1 - (firstMatchToken + correctedStPos)) - matchingTokens, 0); matchingTokensWithCorrection += maxPosCorrection; } final int fromPos = sentence.getOriginalPosition(firstMatchToken + correctedStPos); final boolean spaceBefore = whTokens[fromPos].isWhitespaceBefore(); boolean filtered = false; final DisambiguationPatternRule.DisambiguatorAction disAction = rule.getAction(); final AnalyzedToken[] newTokenReadings = rule.getNewTokenReadings(); final Match matchElement = rule.getMatchElement(); final String disambiguatedPOS = rule.getDisambiguatedPOS(); switch (disAction) { case UNIFY: if (unifiedTokens != null) { //TODO: unifiedTokens.length is larger > matchingTokensWithCorrection in cases where there are no markers... if (unifiedTokens.length == matchingTokensWithCorrection - startPositionCorrection + endPositionCorrection) { if (whTokens[sentence.getOriginalPosition(firstMatchToken + correctedStPos + unifiedTokens.length - 1)].isSentenceEnd()) { unifiedTokens[unifiedTokens.length - 1].setSentEnd(); } for (int i = 0; i < unifiedTokens.length; i++) { final int position = sentence.getOriginalPosition(firstMatchToken + correctedStPos + i); unifiedTokens[i].setStartPos(whTokens[position].getStartPos()); final String prevValue = whTokens[position].toString(); final String prevAnot = whTokens[position].getHistoricalAnnotations(); whTokens[position] = unifiedTokens[i]; annotateChange(whTokens[position], prevValue, prevAnot); } } } break; case REMOVE: if (newTokenReadings != null && newTokenReadings.length > 0) { if (newTokenReadings.length == matchingTokensWithCorrection - startPositionCorrection + endPositionCorrection) { for (int i = 0; i < newTokenReadings.length; i++) { final int position = sentence.getOriginalPosition(firstMatchToken + correctedStPos + i); final String prevValue = whTokens[position].toString(); final String prevAnot = whTokens[position].getHistoricalAnnotations(); whTokens[position].removeReading(newTokenReadings[i]); annotateChange(whTokens[position], prevValue, prevAnot); } } } else if (!StringTools.isEmpty(disambiguatedPOS)) { // negative filtering Pattern p = Pattern.compile(disambiguatedPOS); AnalyzedTokenReadings tmp = new AnalyzedTokenReadings(whTokens[fromPos].getReadings(), whTokens[fromPos].getStartPos()); for (AnalyzedToken analyzedToken : tmp) { if (analyzedToken.getPOSTag() != null) { final Matcher mPos = p.matcher(analyzedToken.getPOSTag()); if (mPos.matches()) { final int position = sentence.getOriginalPosition(firstMatchToken + correctedStPos); final String prevValue = whTokens[position].toString(); final String prevAnot = whTokens[position].getHistoricalAnnotations(); whTokens[position].removeReading(analyzedToken); annotateChange(whTokens[position], prevValue, prevAnot); } } } } break; case ADD: if (newTokenReadings != null) { if (newTokenReadings.length == matchingTokensWithCorrection - startPositionCorrection + endPositionCorrection) { for (int i = 0; i < newTokenReadings.length; i++) { final String token; final int position = sentence.getOriginalPosition(firstMatchToken + correctedStPos + i); if ("".equals(newTokenReadings[i].getToken())) { // empty token token = whTokens[position].getToken(); } else { token = newTokenReadings[i].getToken(); } final String lemma; if (newTokenReadings[i].getLemma() == null) { // empty lemma lemma = token; } else { lemma = newTokenReadings[i].getLemma(); } final AnalyzedToken newTok = new AnalyzedToken(token, newTokenReadings[i].getPOSTag(), lemma); final String prevValue = whTokens[position].toString(); final String prevAnot = whTokens[position].getHistoricalAnnotations(); whTokens[position].addReading(newTok); annotateChange(whTokens[position], prevValue, prevAnot); } } } break; case FILTERALL: for (int i = 0; i < matchingTokensWithCorrection - startPositionCorrection + endPositionCorrection; i++) { final int position = sentence.getOriginalPosition(firstMatchToken + correctedStPos + i); Element myEl; if (elementsMatched.get(i + startPositionCorrection)) { myEl = rule.getPatternElements().get(i + startPositionCorrection); } else { int k = 1; while (i + startPositionCorrection + k < rule.getPatternElements().size() + endPositionCorrection && !elementsMatched.get(i + startPositionCorrection + k)) { k++; } //FIXME: this is left to see whether this fails anywhere assert(i + k + startPositionCorrection < rule.getPatternElements().size()); myEl = rule.getPatternElements().get(i + k + startPositionCorrection); } final Match tmpMatchToken = new Match(myEl.getPOStag(), null, true, myEl.getPOStag(), null, Match.CaseConversion.NONE, false, false, Match.IncludeRange.NONE); MatchState matchState = tmpMatchToken.createState(rule.getLanguage().getSynthesizer(), whTokens[position]); final String prevValue = whTokens[position].toString(); final String prevAnot = whTokens[position].getHistoricalAnnotations(); whTokens[position] = matchState.filterReadings(); annotateChange(whTokens[position], prevValue, prevAnot); } break; case IMMUNIZE: for (int i = 0; i < matchingTokensWithCorrection - startPositionCorrection + endPositionCorrection; i++) { whTokens[sentence.getOriginalPosition(firstMatchToken + correctedStPos + i)].immunize(); } break; case IGNORE_SPELLING: for (int i = 0; i < matchingTokensWithCorrection - startPositionCorrection + endPositionCorrection; i++) { whTokens[sentence.getOriginalPosition(firstMatchToken + correctedStPos + i)].ignoreSpelling(); } break; case FILTER: if (matchElement == null) { // same as REPLACE if using <match> final Match tmpMatchToken = new Match(disambiguatedPOS, null, true, disambiguatedPOS, null, Match.CaseConversion.NONE, false, false, Match.IncludeRange.NONE); final MatchState matchState = tmpMatchToken.createState(rule.getLanguage().getSynthesizer(), whTokens[fromPos]); final String prevValue = whTokens[fromPos].toString(); final String prevAnot = whTokens[fromPos].getHistoricalAnnotations(); whTokens[fromPos] = matchState.filterReadings(); annotateChange(whTokens[fromPos], prevValue, prevAnot); filtered = true; } //fallthrough case REPLACE: default: if (!filtered) { if (newTokenReadings != null && newTokenReadings.length > 0) { if (newTokenReadings.length == matchingTokensWithCorrection - startPositionCorrection + endPositionCorrection) { for (int i = 0; i < newTokenReadings.length; i++) { final String token; final int position = sentence.getOriginalPosition(firstMatchToken + correctedStPos + i); if ("".equals(newTokenReadings[i].getToken())) { // empty token token = whTokens[position].getToken(); } else { token = newTokenReadings[i].getToken(); } final String lemma; if (newTokenReadings[i].getLemma() == null) { // empty lemma lemma = token; } else { lemma = newTokenReadings[i].getLemma(); } final AnalyzedToken analyzedToken = new AnalyzedToken(token, newTokenReadings[i].getPOSTag(), lemma); final AnalyzedTokenReadings toReplace = new AnalyzedTokenReadings( analyzedToken, whTokens[fromPos].getStartPos()); whTokens[position] = replaceTokens( whTokens[position], toReplace); } } } else if (matchElement == null) { String lemma = ""; for (AnalyzedToken analyzedToken : whTokens[fromPos]) { if (analyzedToken.getPOSTag() != null && analyzedToken.getPOSTag().equals(disambiguatedPOS) && analyzedToken.getLemma() != null) { lemma = analyzedToken.getLemma(); } } if (StringTools.isEmpty(lemma)) { lemma = whTokens[fromPos].getAnalyzedToken(0).getLemma(); } final AnalyzedToken analyzedToken = new AnalyzedToken(whTokens[fromPos].getToken(), disambiguatedPOS, lemma); final AnalyzedTokenReadings toReplace = new AnalyzedTokenReadings( analyzedToken, whTokens[fromPos].getStartPos()); whTokens[fromPos] = replaceTokens(whTokens[fromPos], toReplace); } else { // using the match element final MatchState matchElementState = matchElement.createState(rule.getLanguage().getSynthesizer(), whTokens[fromPos]); final String prevValue = whTokens[fromPos].toString(); final String prevAnot = whTokens[fromPos].getHistoricalAnnotations(); whTokens[fromPos] = matchElementState.filterReadings(); whTokens[fromPos].setWhitespaceBefore(spaceBefore); annotateChange(whTokens[fromPos], prevValue, prevAnot); } } } return whTokens; } private void annotateChange(AnalyzedTokenReadings atr, final String prevValue, String prevAnot) { atr.setHistoricalAnnotations(prevAnot + "\n" + rule.getId() + ":" + rule.getSubId() + " " + prevValue + " -> " + atr.toString()); } private AnalyzedTokenReadings replaceTokens(AnalyzedTokenReadings oldAtr, final AnalyzedTokenReadings newAtr) { final String prevValue = oldAtr.toString(); final String prevAnot = oldAtr.getHistoricalAnnotations(); final boolean isSentEnd = oldAtr.isSentenceEnd(); final boolean isParaEnd = oldAtr.isParagraphEnd(); final boolean spaceBefore = oldAtr.isWhitespaceBefore(); final int startPosition = oldAtr.getStartPos(); final List<ChunkTag> chunkTags = oldAtr.getChunkTags(); if (isSentEnd) { newAtr.setSentEnd(); } if (isParaEnd) { newAtr.setParagraphEnd(); } newAtr.setWhitespaceBefore(spaceBefore); newAtr.setStartPos(startPosition); newAtr.setChunkTags(chunkTags); if (oldAtr.isImmunized()) { newAtr.immunize(); } annotateChange(newAtr, prevValue, prevAnot); return newAtr; } }
fix bug -- unification removed chunk info
languagetool-core/src/main/java/org/languagetool/tagging/disambiguation/rules/DisambiguationPatternRuleReplacer.java
fix bug -- unification removed chunk info
<ide><path>anguagetool-core/src/main/java/org/languagetool/tagging/disambiguation/rules/DisambiguationPatternRuleReplacer.java <ide> unifiedTokens[i].setStartPos(whTokens[position].getStartPos()); <ide> final String prevValue = whTokens[position].toString(); <ide> final String prevAnot = whTokens[position].getHistoricalAnnotations(); <add> List<ChunkTag> chTags = whTokens[position].getChunkTags(); <ide> whTokens[position] = unifiedTokens[i]; <add> whTokens[position].setChunkTags(chTags); <ide> annotateChange(whTokens[position], prevValue, prevAnot); <ide> } <ide> }
Java
unlicense
4d1469192c9396383d4521efd9ed84868a074be9
0
noritersand/laboratory,noritersand/laboratory,noritersand/laboratory
package thirdparty.com.fasterxml.jackson; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * com.fasterxml.jackson 테스트 유닛 * * @since 2019-01-23 * @author fixalot */ public class JacksonTest { @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(JacksonTest.class); private ObjectMapper mapper = new ObjectMapper(); /** * JSON 문자열 -> 인스턴스 * * @throws JsonParseException * @throws JsonMappingException * @throws IOException * @author fixalot */ @Test public void testReadValue() throws JsonParseException, JsonMappingException, IOException { String jsonText = "[{\"html1\":\"<p>홀홀</p>\",\"html2\":\"<p>ㅗㅎ롷ㄹ</p>\"}]"; final List<HashMap<String, Object>> collection = mapper.readValue(jsonText, new TypeReference<ArrayList<HashMap<String, Object>>>() {}); Assert.assertEquals(1, collection.size()); Assert.assertEquals("<p>홀홀</p>", collection.get(0).get("html1")); Assert.assertEquals("<p>ㅗㅎ롷ㄹ</p>", collection.get(0).get("html2")); } /** * 인스턴스 -> JSON 문자열 * * @throws JsonProcessingException * @author fixalot */ @Test public void testWriteValue() throws JsonProcessingException { HashMap<String, String> map = new HashMap<>(); map.put("name", "steave"); map.put("age", "32"); map.put("job", "baker"); final String jsonText = mapper.writeValueAsString(map); Assert.assertEquals("{\"name\":\"steave\",\"job\":\"baker\",\"age\":\"32\"}", jsonText); } /** * 컬렉션 -> Plain Object로 변환 * * @author fixalot */ @Test public void testConvertValue() { // #1: map -> po HashMap<String, Object> map = new HashMap<>(); map.put("name", "steave"); map.put("age", "32"); map.put("dead", "true"); PlainObject po = mapper.convertValue(map, PlainObject.class); Assert.assertEquals("steave", po.getName()); Assert.assertEquals(Integer.valueOf(32), po.getAge()); // #2: list<map> -> po HashMap<String, Object> map2 = new HashMap<>(); map2.put("name", "soap"); map2.put("age", 43); map2.put("dead", true); ArrayList<HashMap<String, Object>> list = new ArrayList<>(); list.add(map); list.add(map2); ArrayList<PlainObject> poList = mapper.convertValue(list, new TypeReference<ArrayList<PlainObject>>() {}); Assert.assertEquals("soap", poList.get(1).getName()); Assert.assertEquals(Integer.valueOf(32), poList.get(0).getAge()); Assert.assertEquals(Integer.valueOf(43), poList.get(1).getAge()); Assert.assertEquals(true, poList.get(0).isDead()); Assert.assertEquals(true, poList.get(1).isDead()); } }
src/test/java/thirdparty/com/fasterxml/jackson/JacksonTest.java
package thirdparty.com.fasterxml.jackson; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * com.fasterxml.jackson 테스트 유닛 * * @since 2019-01-23 * @author fixalot */ public class JacksonTest { @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(JacksonTest.class); private ObjectMapper mapper = new ObjectMapper(); /** * JSON 문자열 -> 인스턴스 * * @throws JsonParseException * @throws JsonMappingException * @throws IOException * @author fixalot */ @Test public void testReadValue() throws JsonParseException, JsonMappingException, IOException { String jsonText = "[{\"html1\":\"<p>홀홀</p>\",\"html2\":\"<p>ㅗㅎ롷ㄹ</p>\"}]"; final List<Map<String, Object>> collection = mapper.readValue(jsonText, new TypeReference<ArrayList<HashMap<String, Object>>>() {}); Assert.assertEquals(1, collection.size()); Assert.assertEquals("<p>홀홀</p>", collection.get(0).get("html1")); Assert.assertEquals("<p>ㅗㅎ롷ㄹ</p>", collection.get(0).get("html2")); } /** * 인스턴스 -> JSON 문자열 * * @throws JsonProcessingException * @author fixalot */ @Test public void testWriteValue() throws JsonProcessingException { HashMap<String, String> map = new HashMap<>(); map.put("name", "steave"); map.put("age", "32"); map.put("job", "baker"); final String jsonText = mapper.writeValueAsString(map); Assert.assertEquals("{\"name\":\"steave\",\"job\":\"baker\",\"age\":\"32\"}", jsonText); } /** * 컬렉션 -> Plain Object로 변환 * * @author fixalot */ @Test public void testConvertValue() { // #1: map -> po HashMap<String, Object> map = new HashMap<>(); map.put("name", "steave"); map.put("age", "32"); map.put("dead", "true"); PlainObject po = mapper.convertValue(map, PlainObject.class); Assert.assertEquals("steave", po.getName()); Assert.assertEquals(Integer.valueOf(32), po.getAge()); // #2: list<map> -> po HashMap<String, Object> map2 = new HashMap<>(); map2.put("name", "soap"); map2.put("age", 43); map2.put("dead", true); ArrayList<HashMap<String, Object>> list = new ArrayList<>(); list.add(map); list.add(map2); ArrayList<PlainObject> poList = mapper.convertValue(list, new TypeReference<List<PlainObject>>() {}); Assert.assertEquals("soap", poList.get(1).getName()); Assert.assertEquals(Integer.valueOf(32), poList.get(0).getAge()); Assert.assertEquals(Integer.valueOf(43), poList.get(1).getAge()); Assert.assertEquals(true, poList.get(0).isDead()); Assert.assertEquals(true, poList.get(1).isDead()); } }
fix compile error
src/test/java/thirdparty/com/fasterxml/jackson/JacksonTest.java
fix compile error
<ide><path>rc/test/java/thirdparty/com/fasterxml/jackson/JacksonTest.java <ide> @Test <ide> public void testReadValue() throws JsonParseException, JsonMappingException, IOException { <ide> String jsonText = "[{\"html1\":\"<p>홀홀</p>\",\"html2\":\"<p>ㅗㅎ롷ㄹ</p>\"}]"; <del> final List<Map<String, Object>> collection <add> final List<HashMap<String, Object>> collection <ide> = mapper.readValue(jsonText, new TypeReference<ArrayList<HashMap<String, Object>>>() {}); <ide> Assert.assertEquals(1, collection.size()); <ide> Assert.assertEquals("<p>홀홀</p>", collection.get(0).get("html1")); <ide> list.add(map); <ide> list.add(map2); <ide> <del> ArrayList<PlainObject> poList = mapper.convertValue(list, new TypeReference<List<PlainObject>>() {}); <add> ArrayList<PlainObject> poList = mapper.convertValue(list, new TypeReference<ArrayList<PlainObject>>() {}); <ide> Assert.assertEquals("soap", poList.get(1).getName()); <ide> Assert.assertEquals(Integer.valueOf(32), poList.get(0).getAge()); <ide> Assert.assertEquals(Integer.valueOf(43), poList.get(1).getAge());
JavaScript
mit
ca2956149615aa3ef9ee825fed14cf2a21f31955
0
Socialsquare/dr-bybilleder,Socialsquare/dr-bybilleder
import React, { Component, PropTypes } from 'react'; import './CollageCanvas.css'; const CSS_PREFIXES = { 'transform': ['-webkit-transform', '-ms-transform'] }; const generatePrefixes = attributes => { const result = {}; // Loop through the attributes Object.keys(attributes).forEach(key => { const value = attributes[key]; // Add the original value to the result result[key] = value; // If prefixes exists if(key in CSS_PREFIXES) { const prefixes = CSS_PREFIXES[key]; // Add values for each prefix to the attributes prefixes.forEach(prefix => { result[prefix] = value; }); } }); return result; }; const generateStyle = attributes => { const prefixedAttributes = generatePrefixes(attributes); return Object.keys(prefixedAttributes).map(key => { const value = prefixedAttributes[key]; return key + ':' + value + ';'; }).join(''); }; const addSource = (element, url, type) => { const sourceElement = document.createElement('source'); sourceElement.setAttribute('src', url); sourceElement.setAttribute('type', type); element.appendChild(sourceElement); }; const fullscreen = { is: () => { const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement; return !!fullscreenElement; }, request: e => { const req = e.requestFullscreen || e.msRequestFullscreen || e.mozRequestFullScreen || e.webkitRequestFullscreen; if(req) { req.call(e); } }, exit: () => { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } }, addListener: listener => { document.addEventListener('fullscreenchange', listener); document.addEventListener('webkitfullscreenchange', listener); document.addEventListener('mozfullscreenchange', listener); document.addEventListener('MSFullscreenChange', listener); }, removeListener: listener => { document.removeEventListener('fullscreenchange', listener); document.removeEventListener('webkitfullscreenchange', listener); document.removeEventListener('mozfullscreenchange', listener); document.removeEventListener('MSFullscreenChange', listener); } }; // import DogGridSvg from '../svgs/dot-grid.svg'; // import PlaySvg from '../svgs/play.svg'; import FullscreenSvg from '../svgs/fullscreen.svg'; import FullscreenOffSvg from '../svgs/fullscreen-off.svg'; class CollageCanvas extends Component { resources = {}; state = { controlsVisible: false, facebookHref: 'http://www.facebook.com/sharer.php?u=' }; constructor() { super(); this.resized = this.resized.bind(this); this.play = this.play.bind(this); this.fullscreen = this.fullscreen.bind(this); this.showControls = this.showControls.bind(this); this.hideControls = this.hideControls.bind(this); this.redraw = this.redraw.bind(this); } redraw() { const devicePixelRatio = window.devicePixelRatio || 1; // Initiate the canvas const ctx = this.canvas.getContext('2d'); if(this.resources.background) { const background = this.backgroundPosition(); ctx.drawImage(this.resources.background, background.x, background.y, background.width, background.height); if(this.resources.videos) { this.resources.videos.forEach(video => { const width = video.width * background.width; const height = video.height * background.height; const x = background.x + video.x * background.width; const y = background.y + video.y * background.height; const rotationDeg = video.rotation / (2 * Math.PI) * 360; if(video.player.isFullscreen()) { // Make sure full-screening is not distroyed by a strange position. video.player.setAttribute('style', ''); } else { const style = { width: width / devicePixelRatio + 'px', height: height / devicePixelRatio + 'px', left: x / devicePixelRatio + 'px', top: y / devicePixelRatio + 'px', transform: 'rotate(' + rotationDeg + 'deg)', 'transform-origin': '0 0' // Rotate around the upper left corner }; video.player.setAttribute('style', generateStyle(style)); } }); } } } resized() { // Considering the device pixels might be different from "pixels" const devicePixelRatio = window.devicePixelRatio || 1; // Set the height to the height of the element this.canvas.height = this.canvas.offsetHeight * devicePixelRatio; this.canvas.width = this.canvas.offsetWidth * devicePixelRatio; this.redraw(); } /* Loads the background image and all the videos that makes up the collage */ loadResources() { const collage = this.props.collage; // The background image const backgroundElement = document.createElement('img'); backgroundElement.addEventListener('load', () => { // When loaded, add this as a resource this.resources.background = backgroundElement; // Add a class to display the videos this.videoContainer.className += ' CollageCanvas__video-container--visible'; this.redraw(); }); backgroundElement.src = collage.image; // The videos this.resources.videos = []; collage.videos.forEach(video => { const element = document.createElement('video'); const classes = 'video-js vjs-default-skin CollageCanvas__video'; element.setAttribute('class', classes); // TODO: Consider putting a thumbnail in the videos poster attribute addSource(element, video.videoData.files.hls, 'application/x-mpegURL'); addSource(element, video.videoData.files.rtmpMpeg4, 'rtmp/mp4'); addSource(element, video.videoData.files.rtmpFlv, 'rtmp/flv'); this.videoContainer.appendChild(element); const player = window.videojs(element, { controls: 'auto', loop: true, autoplay: true, preload: 'auto', muted: true, bigPlayButton: false, inactivityTimeout: 500, poster: video.videoData.files.thumbnail, techOrder: ['html5', 'flash'] }); this.resources.videos.push({ element, player, x: video.xPos, y: video.yPos, width: video.width, height: video.height, rotation: video.rotation }); // If the video needs a user gesture to start, we show the controls. player.on('suspend', (e) => { if(player.paused()) { this.showControls(); } }); // When the video starts playing the large collage control get hidden. player.on('play', this.hideControls); player.on('useractive', () => { // and start playing this player.play(); // unmute player.muted(false); // Mute all other players this.muteAllPlayers(player); }); // TODO: Add a listner on error as well ... }); this.redraw(); } play() { // Loop though all the video elements and start playback this.resources.videos.forEach(video => { if(!video.player.paused()) { video.player.pause(); } video.player.play(); }); } fullscreen() { if (!fullscreen.is()) { fullscreen.request(this.everything); } else { fullscreen.exit(); } // Update the state this.setState({ fullscreen: fullscreen.is() }); } showControls() { this.setState({ controlsVisible: true }); } hideControls() { this.setState({ controlsVisible: false }); } muteAllPlayers(exceptPlayer) { this.resources.videos.forEach(video => { if(video.player !== exceptPlayer) { video.player.muted(true); } }); } backgroundPosition() { const background = this.resources.background; const canvas = this.canvas; const canvasRatio = canvas.width / canvas.height; const backgroundRatio = background.width / background.height; if(canvasRatio > backgroundRatio) { const height = canvas.height; const width = canvas.height * backgroundRatio; return { height, width, x: (canvas.width - width) / 2, y: 0 } } else { const height = canvas.width / backgroundRatio; const width = canvas.width; return { height, width, x: 0, y: (canvas.height - height) / 2 } } } componentDidMount() { window.addEventListener('resize', this.resized); this.resized(); this.loadResources(); // Redraw when fullscreen changes fullscreen.addListener(this.redraw); // Set the facebook url to share the current URL const url = location.href; this.setState({ facebookHref: 'http://www.facebook.com/sharer.php?u=' + url }); } componentDidUpdate(prevProps, prevState) { if(prevProps.collage.id !== this.props.collage.id) { this.loadResources(); } } componentWillUnmount() { window.removeEventListener('resize', this.resized); this.resources.videos.forEach(video => { video.player.off('suspend'); video.player.off('play'); video.player.off('volumechange'); }); // Redraw when fullscreen changes fullscreen.removeListener(this.redraw); } render() { return ( <div className="CollageCanvas" ref={(e) => { this.everything = e; }}> <canvas className="CollageCanvas__canvas" ref={(e) => { this.canvas = e; }} /> <div className="CollageCanvas__video-container" ref={(e) => { this.videoContainer = e; }} /> <a className="CollageCanvas__facebook-btn" href={this.state.facebookHref}> Del på Facebook </a> <div className="CollageCanvas__fullscreen-btn" onClick={this.fullscreen}> {this.state.fullscreen ? ( <img src={FullscreenOffSvg} alt="Luk fuld skærm" /> ) : ( <img src={FullscreenSvg} alt="Åbn i fuld skærm" /> )} </div> </div> ); } } CollageCanvas.propTypes = { collage: PropTypes.object.isRequired }; export default CollageCanvas;
client/src/presentationals/CollageCanvas.js
import React, { Component, PropTypes } from 'react'; import './CollageCanvas.css'; const generateStyle = attributes => { return Object.keys(attributes).map(key => { const value = attributes[key]; return key + ':' + value + ';'; }).join(''); }; const addSource = (element, url, type) => { const sourceElement = document.createElement('source'); sourceElement.setAttribute('src', url); sourceElement.setAttribute('type', type); element.appendChild(sourceElement); }; const fullscreen = { is: () => { const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement; return !!fullscreenElement; }, request: e => { const req = e.requestFullscreen || e.msRequestFullscreen || e.mozRequestFullScreen || e.webkitRequestFullscreen; if(req) { req.call(e); } }, exit: () => { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } }, addListener: listener => { document.addEventListener('fullscreenchange', listener); document.addEventListener('webkitfullscreenchange', listener); document.addEventListener('mozfullscreenchange', listener); document.addEventListener('MSFullscreenChange', listener); }, removeListener: listener => { document.removeEventListener('fullscreenchange', listener); document.removeEventListener('webkitfullscreenchange', listener); document.removeEventListener('mozfullscreenchange', listener); document.removeEventListener('MSFullscreenChange', listener); } }; // import DogGridSvg from '../svgs/dot-grid.svg'; import PlaySvg from '../svgs/play.svg'; import FullscreenSvg from '../svgs/fullscreen.svg'; import FullscreenOffSvg from '../svgs/fullscreen-off.svg'; class CollageCanvas extends Component { resources = {}; state = { controlsVisible: false, facebookHref: 'http://www.facebook.com/sharer.php?u=' }; constructor() { super(); this.resized = this.resized.bind(this); this.play = this.play.bind(this); this.fullscreen = this.fullscreen.bind(this); this.showControls = this.showControls.bind(this); this.hideControls = this.hideControls.bind(this); this.redraw = this.redraw.bind(this); } redraw() { const devicePixelRatio = window.devicePixelRatio || 1; // Initiate the canvas const ctx = this.canvas.getContext('2d'); if(this.resources.background) { const background = this.backgroundPosition(); ctx.drawImage(this.resources.background, background.x, background.y, background.width, background.height); if(this.resources.videos) { this.resources.videos.forEach(video => { const width = video.width * background.width; const height = video.height * background.height; const x = background.x + video.x * background.width; const y = background.y + video.y * background.height; const rotationDeg = video.rotation / (2 * Math.PI) * 360; if(video.player.isFullscreen()) { // Make sure full-screening is not distroyed by a strange position. video.player.setAttribute('style', ''); } else { const style = { width: width / devicePixelRatio + 'px', height: height / devicePixelRatio + 'px', left: x / devicePixelRatio + 'px', top: y / devicePixelRatio + 'px', transform: 'rotate(' + rotationDeg + 'deg)', 'transform-origin': '0 0' // Rotate around the upper left corner }; video.player.setAttribute('style', generateStyle(style)); } }); } } } resized() { // Considering the device pixels might be different from "pixels" const devicePixelRatio = window.devicePixelRatio || 1; // Set the height to the height of the element this.canvas.height = this.canvas.offsetHeight * devicePixelRatio; this.canvas.width = this.canvas.offsetWidth * devicePixelRatio; this.redraw(); } /* Loads the background image and all the videos that makes up the collage */ loadResources() { const collage = this.props.collage; // The background image const backgroundElement = document.createElement('img'); backgroundElement.addEventListener('load', () => { // When loaded, add this as a resource this.resources.background = backgroundElement; // Add a class to display the videos this.videoContainer.className += ' CollageCanvas__video-container--visible'; this.redraw(); }); backgroundElement.src = collage.image; // The videos this.resources.videos = []; collage.videos.forEach(video => { const element = document.createElement('video'); const classes = 'video-js vjs-default-skin CollageCanvas__video'; element.setAttribute('class', classes); // TODO: Consider putting a thumbnail in the videos poster attribute addSource(element, video.videoData.files.hls, 'application/x-mpegURL'); addSource(element, video.videoData.files.rtmpMpeg4, 'rtmp/mp4'); addSource(element, video.videoData.files.rtmpFlv, 'rtmp/flv'); this.videoContainer.appendChild(element); const player = window.videojs(element, { controls: 'auto', loop: true, autoplay: true, preload: 'auto', muted: true, bigPlayButton: false, inactivityTimeout: 500, controlBar: { children: { fullscreenToggle: true } }, poster: video.videoData.files.thumbnail, techOrder: ['html5', 'flash'] }); this.resources.videos.push({ element, player, x: video.xPos, y: video.yPos, width: video.width, height: video.height, rotation: video.rotation }); // If the video needs a user gesture to start, we show the controls. player.on('suspend', (e) => { if(player.paused()) { this.showControls(); } }); // When the video starts playing the large collage control get hidden. player.on('play', this.hideControls); player.on('useractive', () => { // Mute all other players this.muteAllPlayers(player); // unmute player.muted(false); // and start playing this player.play(); }); // TODO: Add a listner on error as well ... }); this.redraw(); } play() { // Loop though all the video elements and start playback this.resources.videos.forEach(video => { if(!video.player.paused()) { video.player.pause(); } video.player.play(); }); } fullscreen() { if (!fullscreen.is()) { fullscreen.request(this.everything); } else { fullscreen.exit(); } // Update the state this.setState({ fullscreen: fullscreen.is() }); } showControls() { this.setState({ controlsVisible: true }); } hideControls() { this.setState({ controlsVisible: false }); } muteAllPlayers(exceptPlayer) { this.resources.videos.forEach(video => { if(video.player !== exceptPlayer) { video.player.muted(true); } }); } backgroundPosition() { const background = this.resources.background; const canvas = this.canvas; const canvasRatio = canvas.width / canvas.height; const backgroundRatio = background.width / background.height; if(canvasRatio > backgroundRatio) { const height = canvas.height; const width = canvas.height * backgroundRatio; return { height, width, x: (canvas.width - width) / 2, y: 0 } } else { const height = canvas.width / backgroundRatio; const width = canvas.width; return { height, width, x: 0, y: (canvas.height - height) / 2 } } } componentDidMount() { window.addEventListener('resize', this.resized); this.resized(); this.loadResources(); // Redraw when fullscreen changes fullscreen.addListener(this.redraw); // Set the facebook url to share the current URL const url = location.href; this.setState({ facebookHref: 'http://www.facebook.com/sharer.php?u=' + url }); } componentDidUpdate(prevProps, prevState) { if(prevProps.collage.id !== this.props.collage.id) { this.loadResources(); } } componentWillUnmount() { window.removeEventListener('resize', this.resized); this.resources.videos.forEach(video => { video.player.off('suspend'); video.player.off('play'); video.player.off('volumechange'); }); // Redraw when fullscreen changes fullscreen.removeListener(this.redraw); } render() { return ( <div className="CollageCanvas" ref={(e) => { this.everything = e; }}> <canvas className="CollageCanvas__canvas" ref={(e) => { this.canvas = e; }} /> <div className="CollageCanvas__video-container" ref={(e) => { this.videoContainer = e; }} /> <a className="CollageCanvas__facebook-btn" href={this.state.facebookHref}> Del på Facebook </a> <div className="CollageCanvas__fullscreen-btn" onClick={this.fullscreen}> {this.state.fullscreen ? ( <img src={FullscreenOffSvg} alt="Luk fuld skærm" /> ) : ( <img src={FullscreenSvg} alt="Åbn i fuld skærm" /> )} </div> </div> ); } } CollageCanvas.propTypes = { collage: PropTypes.object.isRequired }; export default CollageCanvas;
Fixing CSS prefixing at runtime and
client/src/presentationals/CollageCanvas.js
Fixing CSS prefixing at runtime and
<ide><path>lient/src/presentationals/CollageCanvas.js <ide> <ide> import './CollageCanvas.css'; <ide> <add>const CSS_PREFIXES = { <add> 'transform': ['-webkit-transform', '-ms-transform'] <add>}; <add> <add>const generatePrefixes = attributes => { <add> const result = {}; <add> // Loop through the attributes <add> Object.keys(attributes).forEach(key => { <add> const value = attributes[key]; <add> // Add the original value to the result <add> result[key] = value; <add> // If prefixes exists <add> if(key in CSS_PREFIXES) { <add> const prefixes = CSS_PREFIXES[key]; <add> // Add values for each prefix to the attributes <add> prefixes.forEach(prefix => { <add> result[prefix] = value; <add> }); <add> } <add> }); <add> return result; <add>}; <add> <ide> const generateStyle = attributes => { <del> return Object.keys(attributes).map(key => { <del> const value = attributes[key]; <add> const prefixedAttributes = generatePrefixes(attributes); <add> return Object.keys(prefixedAttributes).map(key => { <add> const value = prefixedAttributes[key]; <ide> return key + ':' + value + ';'; <ide> }).join(''); <ide> }; <ide> }; <ide> <ide> // import DogGridSvg from '../svgs/dot-grid.svg'; <del>import PlaySvg from '../svgs/play.svg'; <add>// import PlaySvg from '../svgs/play.svg'; <ide> import FullscreenSvg from '../svgs/fullscreen.svg'; <ide> import FullscreenOffSvg from '../svgs/fullscreen-off.svg'; <ide> <ide> muted: true, <ide> bigPlayButton: false, <ide> inactivityTimeout: 500, <del> controlBar: { <del> children: { <del> fullscreenToggle: true <del> } <del> }, <ide> poster: video.videoData.files.thumbnail, <ide> techOrder: ['html5', 'flash'] <ide> }); <ide> // When the video starts playing the large collage control get hidden. <ide> player.on('play', this.hideControls); <ide> player.on('useractive', () => { <add> // and start playing this <add> player.play(); <add> // unmute <add> player.muted(false); <ide> // Mute all other players <ide> this.muteAllPlayers(player); <del> // unmute <del> player.muted(false); <del> // and start playing this <del> player.play(); <ide> }); <ide> // TODO: Add a listner on error as well ... <ide> });
JavaScript
agpl-3.0
14cd4c7c5e00e9c98d78704f04500eb3d1451618
0
ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs
/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ $( function () { var cDate = Asc.cDate; function toFixed( n ) { return n;//.toFixed( AscCommonExcel.cExcelSignificantDigits ) - 0; } function difBetween( a, b ) { return Math.abs( a - b ) < dif } function _getPMT( fZins, fZzr, fBw, fZw, nF ){ var fRmz; if( fZins == 0.0 ) fRmz = ( fBw + fZw ) / fZzr; else{ var fTerm = Math.pow( 1.0 + fZins, fZzr ); if( nF > 0 ) fRmz = ( fZw * fZins / ( fTerm - 1.0 ) + fBw * fZins / ( 1.0 - 1.0 / fTerm ) ) / ( 1.0 + fZins ); else fRmz = fZw * fZins / ( fTerm - 1.0 ) + fBw * fZins / ( 1.0 - 1.0 / fTerm ); } return -fRmz; } function _getFV( fZins, fZzr, fRmz, fBw, nF ){ var fZw; if( fZins == 0.0 ) fZw = fBw + fRmz * fZzr; else{ var fTerm = Math.pow( 1.0 + fZins, fZzr ); if( nF > 0 ) fZw = fBw * fTerm + fRmz * ( 1.0 + fZins ) * ( fTerm - 1.0 ) / fZins; else fZw = fBw * fTerm + fRmz * ( fTerm - 1.0 ) / fZins; } return -fZw; } function _getDDB( cost, salvage, life, period, factor ) { var ddb, ipmt, oldCost, newCost; ipmt = factor / life; if ( ipmt >= 1 ) { ipmt = 1; if ( period == 1 ) oldCost = cost; else oldCost = 0; } else oldCost = cost * Math.pow( 1 - ipmt, period - 1 ); newCost = cost * Math.pow( 1 - ipmt, period ); if ( newCost < salvage ) ddb = oldCost - salvage; else ddb = oldCost - newCost; if ( ddb < 0 ) ddb = 0; return ddb; } function _getIPMT(rate, per, pv, type, pmt) { var ipmt; if ( per == 1 ) { if ( type > 0 ) ipmt = 0; else ipmt = -pv; } else { if ( type > 0 ) ipmt = _getFV( rate, per - 2, pmt, pv, 1 ) - pmt; else ipmt = _getFV( rate, per - 1, pmt, pv, 0 ); } return ipmt * rate } function _diffDate(d1, d2, mode){ var date1 = d1.getDate(), month1 = d1.getMonth(), year1 = d1.getFullYear(), date2 = d2.getDate(), month2 = d2.getMonth(), year2 = d2.getFullYear(); switch ( mode ) { case 0: return Math.abs( GetDiffDate360( date1, month1, year1, date2, month2, year2, true ) ); case 1: var yc = Math.abs( year2 - year1 ), sd = year1 > year2 ? d2 : d1, yearAverage = sd.isLeapYear() ? 366 : 365, dayDiff = Math.abs( d2 - d1 ); for ( var i = 0; i < yc; i++ ) { sd.addYears( 1 ); yearAverage += sd.isLeapYear() ? 366 : 365; } yearAverage /= (yc + 1); dayDiff /= c_msPerDay; return dayDiff; case 2: var dayDiff = Math.abs( d2 - d1 ); dayDiff /= c_msPerDay; return dayDiff; case 3: var dayDiff = Math.abs( d2 - d1 ); dayDiff /= c_msPerDay; return dayDiff; case 4: return Math.abs( GetDiffDate360( date1, month1, year1, date2, month2, year2, false ) ); default: return "#NUM!"; } } function _yearFrac(d1, d2, mode) { var date1 = d1.getDate(), month1 = d1.getMonth()+1, year1 = d1.getFullYear(), date2 = d2.getDate(), month2 = d2.getMonth()+1, year2 = d2.getFullYear(); switch ( mode ) { case 0: return Math.abs( GetDiffDate360( date1, month1, year1, date2, month2, year2, true ) ) / 360; case 1: var yc = /*Math.abs*/( year2 - year1 ), sd = year1 > year2 ? new cDate(d2) : new cDate(d1), yearAverage = sd.isLeapYear() ? 366 : 365, dayDiff = /*Math.abs*/( d2 - d1 ); for ( var i = 0; i < yc; i++ ) { sd.addYears( 1 ); yearAverage += sd.isLeapYear() ? 366 : 365; } yearAverage /= (yc + 1); dayDiff /= (yearAverage * c_msPerDay); return dayDiff; case 2: var dayDiff = Math.abs( d2 - d1 ); dayDiff /= (360 * c_msPerDay); return dayDiff; case 3: var dayDiff = Math.abs( d2 - d1 ); dayDiff /= (365 * c_msPerDay); return dayDiff; case 4: return Math.abs( GetDiffDate360( date1, month1, year1, date2, month2, year2, false ) ) / 360; default: return "#NUM!"; } } function _lcl_GetCouppcd(settl, matur, freq){ matur.setFullYear( settl.getFullYear() ); if( matur < settl ) matur.addYears( 1 ); while( matur > settl ){ matur.addMonths( -12 / freq ); } } function _lcl_GetCoupncd( settl, matur, freq ){ matur.setFullYear( settl.getFullYear() ); if( matur > settl ) matur.addYears( -1 ); while( matur <= settl ){ matur.addMonths( 12 / freq ); } } function _getcoupdaybs( settl, matur, frequency, basis ) { _lcl_GetCouppcd( settl, matur, frequency ); return _diffDate( settl, matur, basis ); } function _getcoupdays( settl, matur, frequency, basis ) { _lcl_GetCouppcd( settl, matur, frequency ); var n = new cDate( matur ); n.addMonths( 12 / frequency ); return _diffDate( matur, n, basis ); } function _getdiffdate( d1,d2, nMode ){ var bNeg = d1 > d2; if( bNeg ) { var n = d2; d2 = d1; d1 = n; } var nRet,pOptDaysIn1stYear; var nD1 = d1.getDate(), nM1 = d1.getMonth(), nY1 = d1.getFullYear(), nD2 = d2.getDate(), nM2 = d2.getMonth(), nY2 = d2.getFullYear(); switch( nMode ) { case 0: // 0=USA (NASD) 30/360 case 4: // 4=Europe 30/360 { var bLeap = d1.isLeapYear(); var nDays, nMonths/*, nYears*/; nMonths = nM2 - nM1; nDays = nD2 - nD1; nMonths += ( nY2 - nY1 ) * 12; nRet = nMonths * 30 + nDays; if( nMode == 0 && nM1 == 2 && nM2 != 2 && nY1 == nY2 ) nRet -= bLeap? 1 : 2; pOptDaysIn1stYear = 360; } break; case 1: // 1=exact/exact pOptDaysIn1stYear = d1.isLeapYear() ? 366 : 365; nRet = d2 - d1; break; case 2: // 2=exact/360 nRet = d2 - d1; pOptDaysIn1stYear = 360; break; case 3: //3=exact/365 nRet = d2 - d1; pOptDaysIn1stYear = 365; break; } return (bNeg ? -nRet : nRet) / c_msPerDay / pOptDaysIn1stYear; } function _getprice( nSettle, nMat, fRate, fYield, fRedemp, nFreq, nBase ){ var fdays = AscCommonExcel.getcoupdays( new cDate(nSettle), new cDate(nMat), nFreq, nBase ), fdaybs = AscCommonExcel.getcoupdaybs( new cDate(nSettle), new cDate(nMat), nFreq, nBase ), fnum = AscCommonExcel.getcoupnum( new cDate(nSettle), (nMat), nFreq, nBase ), fdaysnc = ( fdays - fdaybs ) / fdays, fT1 = 100 * fRate / nFreq, fT2 = 1 + fYield / nFreq, res = fRedemp / ( Math.pow( 1 + fYield / nFreq, fnum - 1 + fdaysnc ) ); /*var fRet = fRedemp / ( Math.pow( 1.0 + fYield / nFreq, fnum - 1.0 + fdaysnc ) ); fRet -= 100.0 * fRate / nFreq * fdaybs / fdays; var fT1 = 100.0 * fRate / nFreq; var fT2 = 1.0 + fYield / nFreq; for( var fK = 0.0 ; fK < fnum ; fK++ ){ fRet += fT1 / Math.pow( fT2, fK + fdaysnc ); } return fRet;*/ if( fnum == 1){ return (fRedemp + fT1) / (1 + fdaysnc * fYield / nFreq) - 100 * fRate / nFreq * fdaybs / fdays; } res -= 100 * fRate / nFreq * fdaybs / fdays; for ( var i = 0; i < fnum; i++ ) { res += fT1 / Math.pow( fT2, i + fdaysnc ); } return res; } function _getYield( nSettle, nMat, fCoup, fPrice, fRedemp, nFreq, nBase ){ var fRate = fCoup, fPriceN = 0.0, fYield1 = 0.0, fYield2 = 1.0; var fPrice1 = _getprice( nSettle, nMat, fRate, fYield1, fRedemp, nFreq, nBase ); var fPrice2 = _getprice( nSettle, nMat, fRate, fYield2, fRedemp, nFreq, nBase ); var fYieldN = ( fYield2 - fYield1 ) * 0.5; for( var nIter = 0 ; nIter < 100 && fPriceN != fPrice ; nIter++ ) { fPriceN = _getprice( nSettle, nMat, fRate, fYieldN, fRedemp, nFreq, nBase ); if( fPrice == fPrice1 ) return fYield1; else if( fPrice == fPrice2 ) return fYield2; else if( fPrice == fPriceN ) return fYieldN; else if( fPrice < fPrice2 ) { fYield2 *= 2.0; fPrice2 = _getprice( nSettle, nMat, fRate, fYield2, fRedemp, nFreq, nBase ); fYieldN = ( fYield2 - fYield1 ) * 0.5; } else { if( fPrice < fPriceN ) { fYield1 = fYieldN; fPrice1 = fPriceN; } else { fYield2 = fYieldN; fPrice2 = fPriceN; } fYieldN = fYield2 - ( fYield2 - fYield1 ) * ( ( fPrice - fPrice2 ) / ( fPrice1 - fPrice2 ) ); } } if( Math.abs( fPrice - fPriceN ) > fPrice / 100.0 ) return "#NUM!"; // result not precise enough return fYieldN; } function _getyieldmat( nSettle, nMat, nIssue, fRate, fPrice, nBase ){ var fIssMat = _yearFrac( nIssue, nMat, nBase ); var fIssSet = _yearFrac( nIssue, nSettle, nBase ); var fSetMat = _yearFrac( nSettle, nMat, nBase ); var y = 1.0 + fIssMat * fRate; y /= fPrice / 100.0 + fIssSet * fRate; y--; y /= fSetMat; return y; } function _coupnum( settlement, maturity, frequency, basis ) { basis = ( basis !== undefined ? basis : 0 ); var n = new cDate(maturity); _lcl_GetCouppcd( settlement, n, frequency ); var nMonths = (maturity.getFullYear() - n.getFullYear()) * 12 + maturity.getMonth() - n.getMonth(); return nMonths * frequency / 12 ; } function _duration( settlement, maturity, coupon, yld, frequency, basis ){ var dbc = AscCommonExcel.getcoupdaybs(new cDate( settlement ),new cDate( maturity ),frequency,basis), coupD = AscCommonExcel.getcoupdays(new cDate( settlement ),new cDate( maturity ),frequency,basis), numCoup = AscCommonExcel.getcoupnum(new cDate( settlement ),new cDate( maturity ),frequency); if ( settlement >= maturity || basis < 0 || basis > 4 || ( frequency != 1 && frequency != 2 && frequency != 4 ) || yld < 0 || coupon < 0 ){ return "#NUM!"; } var duration = 0, p = 0; var dsc = coupD - dbc; var diff = dsc / coupD - 1; yld = yld / frequency + 1; coupon *= 100/frequency; for(var index = 1; index <= numCoup; index++ ){ var di = index + diff; var yldPOW = Math.pow( yld, di); duration += di * coupon / yldPOW; p += coupon / yldPOW; } duration += (diff + numCoup) * 100 / Math.pow( yld, diff + numCoup); p += 100 / Math.pow( yld, diff + numCoup); return duration / p / frequency ; } function numDivFact(num, fact){ var res = num / Math.fact(fact); res = res.toString(); return res; } function testArrayFormula(func, dNotSupportAreaArg) { var getValue = function(ref) { oParser = new parserFormula( func + "(" + ref + ")", "A2", ws ); ok( oParser.parse() ); return oParser.calculate().getValue(); }; //***array-formula*** ws.getRange2( "A100" ).setValue( "1" ); ws.getRange2( "B100" ).setValue( "3" ); ws.getRange2( "C100" ).setValue( "-4" ); ws.getRange2( "A101" ).setValue( "2" ); ws.getRange2( "B101" ).setValue( "4" ); ws.getRange2( "C101" ).setValue( "5" ); oParser = new parserFormula( func + "(A100:C101)", "A1", ws ); oParser.setArrayFormulaRef(ws.getRange2("E106:H107").bbox); ok( oParser.parse() ); var array = oParser.calculate(); if(AscCommonExcel.cElementType.array === array.type) { strictEqual( array.getElementRowCol(0,0).getValue(), getValue("A100")); strictEqual( array.getElementRowCol(0,1).getValue(), getValue("B100")); strictEqual( array.getElementRowCol(0,2).getValue(), getValue("C100")); strictEqual( array.getElementRowCol(1,0).getValue(), getValue("A101")); strictEqual( array.getElementRowCol(1,1).getValue(), getValue("B101")); strictEqual( array.getElementRowCol(1,2).getValue(), getValue("C101")); } else { if(!dNotSupportAreaArg) { strictEqual( false, true); } consoleLog("func: " + func + " don't return area array"); } oParser = new parserFormula( func + "({1,2,-3})", "A1", ws ); oParser.setArrayFormulaRef(ws.getRange2("E106:H107").bbox); ok( oParser.parse() ); array = oParser.calculate(); strictEqual( array.getElementRowCol(0,0).getValue(), getValue(1)); strictEqual( array.getElementRowCol(0,1).getValue(), getValue(2)); strictEqual( array.getElementRowCol(0,2).getValue(), getValue(-3)); } //returnOnlyValue - те функции, на вход которых всегда должны подаваться массивы и которые возвращают единственное значение function testArrayFormula2(func, minArgCount, maxArgCount, dNotSupportAreaArg, returnOnlyValue) { var getValue = function(ref, countArg) { var argStr = "("; for(var j = 1; j <= countArg; j++) { argStr += ref; if(i !== j) { argStr += ","; } else { argStr += ")"; } } oParser = new parserFormula( func + argStr, "A2", ws ); ok( oParser.parse() ); return oParser.calculate().getValue(); }; //***array-formula*** ws.getRange2( "A100" ).setValue( "1" ); ws.getRange2( "B100" ).setValue( "3" ); ws.getRange2( "C100" ).setValue( "-4" ); ws.getRange2( "A101" ).setValue( "2" ); ws.getRange2( "B101" ).setValue( "4" ); ws.getRange2( "C101" ).setValue( "5" ); //формируем массив значений var randomArray = []; var randomStrArray = "{"; var maxArg = 4; for(var i = 1; i <= maxArg; i++) { var randVal = Math.random(); randomArray.push(randVal); randomStrArray += randVal; if(i !== maxArg) { randomStrArray += ","; } else { randomStrArray += "}"; } } for(var i = minArgCount; i <= maxArgCount; i++) { var argStrArr = "("; var randomArgStrArr = "("; for(var j = 1; j <= i; j++) { argStrArr += "A100:C101"; randomArgStrArr += randomStrArray; if(i !== j) { argStrArr += ","; randomArgStrArr += ","; } else { argStrArr += ")"; randomArgStrArr += ")"; } } oParser = new parserFormula( func + argStrArr, "A1", ws ); oParser.setArrayFormulaRef(ws.getRange2("E106:H107").bbox); ok( oParser.parse() ); var array = oParser.calculate(); if(AscCommonExcel.cElementType.array === array.type) { strictEqual( array.getElementRowCol(0,0).getValue(), getValue("A100", i)); strictEqual( array.getElementRowCol(0,1).getValue(), getValue("B100", i)); strictEqual( array.getElementRowCol(0,2).getValue(), getValue("C100", i)); strictEqual( array.getElementRowCol(1,0).getValue(), getValue("A101", i)); strictEqual( array.getElementRowCol(1,1).getValue(), getValue("B101", i)); strictEqual( array.getElementRowCol(1,2).getValue(), getValue("C101", i)); } else { if(!(dNotSupportAreaArg || returnOnlyValue)) { strictEqual( false, true); } consoleLog("func: " + func + " don't return area array"); } oParser = new parserFormula( func + randomArgStrArr, "A1", ws ); oParser.setArrayFormulaRef(ws.getRange2("E106:H107").bbox); ok( oParser.parse() ); array = oParser.calculate(); if(AscCommonExcel.cElementType.array === array.type) { strictEqual( array.getElementRowCol(0,0).getValue(), getValue(randomArray[0], i)); strictEqual( array.getElementRowCol(0,1).getValue(), getValue(randomArray[1], i)); strictEqual( array.getElementRowCol(0,2).getValue(), getValue(randomArray[2], i)); } else { if(!returnOnlyValue) { strictEqual( false, true); } consoleLog("func: " + func + " don't return array"); } } } function testArrayFormulaEqualsValues(str, formula,isNotLowerCase) { //***array-formula*** ws.getRange2( "A1" ).setValue( "1" ); ws.getRange2( "B1" ).setValue( "3.123" ); ws.getRange2( "C1" ).setValue( "-4" ); ws.getRange2( "A2" ).setValue( "2" ); ws.getRange2( "B2" ).setValue( "4" ); ws.getRange2( "C2" ).setValue( "5" ); oParser = new parserFormula( formula, "A1", ws ); oParser.setArrayFormulaRef(ws.getRange2("E6:H8").bbox); ok( oParser.parse() ); var array = oParser.calculate(); var splitStr = str.split(";"); for(var i = 0; i < splitStr.length; i++) { var subSplitStr = splitStr[i].split(","); for(var j = 0; j < subSplitStr.length; j++) { var valMs = subSplitStr[j]; var element; if(array.getElementRowCol) { var row = 1 === array.array.length ? 0 : i; var col = 1 === array.array[0].length ? 0 : j; if(array.array[row] && array.array[row][col]) { element = array.getElementRowCol(row, col); } else { element = new window['AscCommonExcel'].cError(window['AscCommonExcel'].cErrorType.not_available); } } else { element = array; } var ourVal = element && undefined != element.value ? element.value.toString() : "#N/A"; if(!isNotLowerCase) { valMs = valMs.toLowerCase(); ourVal = ourVal.toLowerCase(); } strictEqual(valMs, ourVal, "formula: " + formula + " i: " + i + " j: " + j) } } } function consoleLog(val) { //console.log(val); } var newFormulaParser = false; var c_msPerDay = AscCommonExcel.c_msPerDay; var parserFormula = AscCommonExcel.parserFormula; var GetDiffDate360 = AscCommonExcel.GetDiffDate360; var fSortAscending = AscCommon.fSortAscending; var g_oIdCounter = AscCommon.g_oIdCounter; var oParser, wb, ws, dif = 1e-9, sData = AscCommon.getEmpty(), tmp; if ( AscCommon.c_oSerFormat.Signature === sData.substring( 0, AscCommon.c_oSerFormat.Signature.length ) ) { wb = new AscCommonExcel.Workbook( new AscCommonExcel.asc_CHandlersList(), {wb:{getWorksheet:function(){}}} ); AscCommon.History.init(wb); AscCommon.g_oTableId.init(); if ( this.User ) g_oIdCounter.Set_UserId(this.User.asc_getId()); AscCommonExcel.g_oUndoRedoCell = new AscCommonExcel.UndoRedoCell(wb); AscCommonExcel.g_oUndoRedoWorksheet = new AscCommonExcel.UndoRedoWoorksheet(wb); AscCommonExcel.g_oUndoRedoWorkbook = new AscCommonExcel.UndoRedoWorkbook(wb); AscCommonExcel.g_oUndoRedoCol = new AscCommonExcel.UndoRedoRowCol(wb, false); AscCommonExcel.g_oUndoRedoRow = new AscCommonExcel.UndoRedoRowCol(wb, true); AscCommonExcel.g_oUndoRedoComment = new AscCommonExcel.UndoRedoComment(wb); AscCommonExcel.g_oUndoRedoAutoFilters = new AscCommonExcel.UndoRedoAutoFilters(wb); AscCommonExcel.g_DefNameWorksheet = new AscCommonExcel.Worksheet(wb, -1); g_oIdCounter.Set_Load(false); var oBinaryFileReader = new AscCommonExcel.BinaryFileReader(); oBinaryFileReader.Read( sData, wb ); ws = wb.getWorksheet( wb.getActive() ); AscCommonExcel.getFormulasInfo(); } /*QUnit.log( function ( details ) { console.log( "Log: " + details.name + ", result - " + details.result ); } );*/ wb.dependencyFormulas.lockRecal(); module( "Formula" ); test( "Test: \"ABS\"", function () { ws.getRange2( "A22" ).setValue( "-4" ); oParser = new parserFormula( "ABS(2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "ABS(-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "ABS(A22)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); testArrayFormula("ABS"); } ); test( "Test: \"Absolute reference\"", function () { ws.getRange2( "A7" ).setValue( "1" ); ws.getRange2( "A8" ).setValue( "2" ); ws.getRange2( "A9" ).setValue( "3" ); oParser = new parserFormula( 'A$7+A8', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( 'A$7+A$8', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( '$A$7+$A$8', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( 'SUM($A$7:$A$9)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); } ); test( "Test: \"Asc\"", function () { oParser = new parserFormula( 'ASC("teSt")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "teSt" ); oParser = new parserFormula( 'ASC("デジタル")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "デジタル" ); oParser = new parserFormula( 'ASC("￯")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "" ); } ); test( "Test: \"Cross\"", function () { ws.getRange2( "A7" ).setValue( "1" ); ws.getRange2( "A8" ).setValue( "2" ); ws.getRange2( "A9" ).setValue( "3" ); oParser = new parserFormula( 'A7:A9', null, ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().cross(new Asc.Range(0, 5, 0, 5), ws.getId()).getValue(), "#VALUE!" ); strictEqual( oParser.calculate().cross(new Asc.Range(0, 6, 0, 6), ws.getId()).getValue(), 1 ); strictEqual( oParser.calculate().cross(new Asc.Range(0, 7, 0, 7), ws.getId()).getValue(), 2 ); strictEqual( oParser.calculate().cross(new Asc.Range(0, 8, 0, 8), ws.getId()).getValue(), 3 ); strictEqual( oParser.calculate().cross(new Asc.Range(0, 9, 0, 9), ws.getId()).getValue(), "#VALUE!" ); } ); test( "Test: \"Defined names cycle\"", function () { var newNameQ = new Asc.asc_CDefName("q", "SUM('"+ws.getName()+"'!A2)"); wb.editDefinesNames(null, newNameQ); ws.getRange2( "Q1" ).setValue( "=q" ); ws.getRange2( "Q2" ).setValue( "=q" ); ws.getRange2( "Q3" ).setValue( "1" ); strictEqual( ws.getRange2( "Q1" ).getValueWithFormat(), "1" ); strictEqual( ws.getRange2( "Q2" ).getValueWithFormat(), "1" ); var newNameW = new Asc.asc_CDefName("w", "'"+ws.getName()+"'!A1"); wb.editDefinesNames(null, newNameW); ws.getRange2( "Q4" ).setValue( "=w" ); strictEqual( ws.getRange2( "Q4" ).getValueWithFormat(), "#REF!" ); //clean up ws.getRange2( "Q1:Q4" ).cleanAll(); wb.delDefinesNames(newNameW); wb.delDefinesNames(newNameQ); }); test( "Test: \"Parse intersection\"", function () { ws.getRange2( "A7" ).setValue( "1" ); ws.getRange2( "A8" ).setValue( "2" ); ws.getRange2( "A9" ).setValue( "3" ); oParser = new parserFormula( '1 + ( A7 +A8 ) * 2', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.assemble(), "1+(A7+A8)*2" ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( 'sum A1:A5', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.assemble(), "sum A1:A5" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( 'sum( A1:A5 , B1:B5 ) ', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.assemble(), "SUM(A1:A5,B1:B5)" ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( 'sum( A1:A5 , B1:B5 , " 3 , 14 15 92 6 " ) ', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.assemble(), 'SUM(A1:A5,B1:B5," 3 , 14 15 92 6 ")' ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); } ); test( "Test: \"Arithmetical operations\"", function () { oParser = new parserFormula( '1+3', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( '(1+2)*4+3', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), (1 + 2) * 4 + 3 ); oParser = new parserFormula( '2^52', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.pow( 2, 52 ) ); oParser = new parserFormula( '-10', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -10 ); oParser = new parserFormula( '-10*2', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -20 ); oParser = new parserFormula( '-10+10', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( '12%', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0.12 ); oParser = new parserFormula( "2<>\"3\"", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE", "2<>\"3\"" ); oParser = new parserFormula( "2=\"3\"", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE", "2=\"3\"" ); oParser = new parserFormula( "2>\"3\"", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE", "2>\"3\"" ); oParser = new parserFormula( "\"f\">\"3\"", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( "\"f\"<\"3\"", "A1", ws ); ok( oParser.parse() ); strictEqual( "FALSE", oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( "FALSE>=FALSE", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( "\"TRUE\"&\"TRUE\"", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUETRUE" ); oParser = new parserFormula( "10*\"\"", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "-TRUE", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1 ); } ); test( "Test: \"ACOS\"", function () { oParser = new parserFormula( 'ACOS(-0.5)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 2.094395102 ); testArrayFormula("ACOS"); } ); test( "Test: \"ACOSH\"", function () { oParser = new parserFormula( 'ACOSH(1)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( 'ACOSH(10)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 2.9932228 ); testArrayFormula("ACOSH"); } ); test( "Test: \"ASIN\"", function () { oParser = new parserFormula( 'ASIN(-0.5)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, -0.523598776 ); testArrayFormula("ASIN"); } ); test( "Test: \"ASINH\"", function () { oParser = new parserFormula( 'ASINH(-2.5)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, -1.647231146 ); oParser = new parserFormula( 'ASINH(10)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 2.99822295 ); testArrayFormula("ASINH"); } ); test( "Test: \"SIN have wrong arguments count\"", function () { oParser = new parserFormula( 'SIN(3.1415926,3.1415926*2)', "A1", ws ); ok( !oParser.parse() ); } ); test( "Test: \"SIN(3.1415926)\"", function () { oParser = new parserFormula( 'SIN(3.1415926)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.sin( 3.1415926 ) ); testArrayFormula("SIN"); } ); test( "Test: \"SQRT\"", function () { ws.getRange2( "A202" ).setValue( "-16" ); oParser = new parserFormula( 'SQRT(16)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( 'SQRT(A202)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( 'SQRT(ABS(A202))', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); testArrayFormula("SQRT"); } ); test( "Test: \"SQRTPI\"", function () { oParser = new parserFormula( 'SQRTPI(1)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 1.772454 ); oParser = new parserFormula( 'SQRTPI(2)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 2.506628 ); testArrayFormula("SQRTPI", true); } ); test( "Test: \"COS(PI()/2)\"", function () { oParser = new parserFormula( 'COS(PI()/2)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.cos( Math.PI / 2 ) ); } ); test( "Test: \"ACOT(2)\"", function () { oParser = new parserFormula( 'ACOT(2)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.PI / 2 - Math.atan(2) ); } ); test( "Test: \"ACOTH(6)\"", function () { oParser = new parserFormula( 'ACOTH(6)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.atanh(1 / 6) ); testArrayFormula("ACOTH"); } ); test( "Test: \"COT\"", function () { oParser = new parserFormula( 'COT(30)', "A1", ws ); ok( oParser.parse(), 'COT(30)' ); strictEqual( oParser.calculate().getValue().toFixed(3) - 0, -0.156, 'COT(30)' ); oParser = new parserFormula( 'COT(0)', "A1", ws ); ok( oParser.parse(), 'COT(0)' ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", 'COT(0)' ); oParser = new parserFormula( 'COT(1000000000)', "A1", ws ); ok( oParser.parse(), 'COT(1000000000)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'COT(1000000000)' ); oParser = new parserFormula( 'COT(-1000000000)', "A1", ws ); ok( oParser.parse(), 'COT(-1000000000)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'COT(-1000000000)' ); oParser = new parserFormula( 'COT(test)', "A1", ws ); ok( oParser.parse(), 'COT(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'COT(test)' ); oParser = new parserFormula( 'COT("test")', "A1", ws ); ok( oParser.parse(), 'COT("test")' ); strictEqual( oParser.calculate().getValue(), "#VALUE!", 'COT("test")' ); testArrayFormula("COT"); } ); test( "Test: \"COTH\"", function () { oParser = new parserFormula( 'COTH(2)', "A1", ws ); ok( oParser.parse(), 'COTH(2)' ); strictEqual( oParser.calculate().getValue().toFixed(3) - 0, 1.037, 'COTH(2)' ); oParser = new parserFormula( 'COTH(0)', "A1", ws ); ok( oParser.parse(), 'COTH(0)' ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", 'COTH(0)' ); oParser = new parserFormula( 'COTH(1000000000)', "A1", ws ); ok( oParser.parse(), 'COTH(1000000000)' ); strictEqual( oParser.calculate().getValue(), 1, 'COTH(1000000000)' ); oParser = new parserFormula( 'COTH(-1000000000)', "A1", ws ); ok( oParser.parse(), 'COTH(-1000000000)' ); strictEqual( oParser.calculate().getValue(), -1, 'COTH(-1000000000)' ); oParser = new parserFormula( 'COTH(test)', "A1", ws ); ok( oParser.parse(), 'COTH(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'COTH(test)' ); oParser = new parserFormula( 'COTH("test")', "A1", ws ); ok( oParser.parse(), 'COTH("test")' ); strictEqual( oParser.calculate().getValue(), "#VALUE!", 'COTH("test")' ); testArrayFormula("COTH"); } ); test( "Test: \"CSC\"", function () { oParser = new parserFormula( 'CSC(15)', "A1", ws ); ok( oParser.parse(), 'CSC(15)' ); strictEqual( oParser.calculate().getValue().toFixed(3) - 0, 1.538, 'CSC(15)' ); oParser = new parserFormula( 'CSC(0)', "A1", ws ); ok( oParser.parse(), 'CSC(0)' ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", 'CSC(0)' ); oParser = new parserFormula( 'CSC(1000000000)', "A1", ws ); ok( oParser.parse(), 'CSC(1000000000)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'CSC(1000000000)' ); oParser = new parserFormula( 'CSC(-1000000000)', "A1", ws ); ok( oParser.parse(), 'CSC(-1000000000)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'CSC(-1000000000)' ); oParser = new parserFormula( 'CSC(test)', "A1", ws ); ok( oParser.parse(), 'CSC(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'CSC(test)' ); oParser = new parserFormula( 'CSC("test")', "A1", ws ); ok( oParser.parse(), 'CSC("test")' ); strictEqual( oParser.calculate().getValue(), "#VALUE!", 'CSC("test")' ); testArrayFormula("CSC"); } ); test( "Test: \"CSCH\"", function () { oParser = new parserFormula( 'CSCH(1.5)', "A1", ws ); ok( oParser.parse(), 'CSCH(1.5)' ); strictEqual( oParser.calculate().getValue().toFixed(4) - 0, 0.4696, 'CSCH(1.5)' ); oParser = new parserFormula( 'CSCH(0)', "A1", ws ); ok( oParser.parse(), 'CSCH(0)' ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", 'CSCH(0)' ); oParser = new parserFormula( 'CSCH(1000000000)', "A1", ws ); ok( oParser.parse(), 'CSCH(1000000000)' ); strictEqual( oParser.calculate().getValue(), 0, 'CSCH(1000000000)' ); oParser = new parserFormula( 'CSCH(-1000000000)', "A1", ws ); ok( oParser.parse(), 'CSCH(-1000000000)' ); strictEqual( oParser.calculate().getValue(), 0, 'CSCH(-1000000000)' ); oParser = new parserFormula( 'CSCH(test)', "A1", ws ); ok( oParser.parse(), 'CSCH(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'CSCH(test)' ); oParser = new parserFormula( 'CSCH("test")', "A1", ws ); ok( oParser.parse(), 'CSCH("test")' ); strictEqual( oParser.calculate().getValue(), "#VALUE!", 'CSCH("test")' ); testArrayFormula("CSCH"); } ); test( "Test: \"CLEAN\"", function () { ws.getRange2( "A202" ).setValue( '=CHAR(9)&"Monthly report"&CHAR(10)' ); oParser = new parserFormula( 'CLEAN(A202)', "A1", ws ); ok( oParser.parse()); strictEqual( oParser.calculate().getValue(), "Monthly report" ); testArrayFormula("CLEAN"); } ); test( "Test: \"DEGREES\"", function () { oParser = new parserFormula( 'DEGREES(PI())', "A1", ws ); ok( oParser.parse(), 'DEGREES(PI())' ); strictEqual( oParser.calculate().getValue(), 180, 'DEGREES(PI())' ); testArrayFormula("DEGREES"); } ); test( "Test: \"SEC\"", function () { oParser = new parserFormula( 'SEC(45)', "A1", ws ); ok( oParser.parse(), 'SEC(45)' ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 1.90359, 'SEC(45)' ); oParser = new parserFormula( 'SEC(30)', "A1", ws ); ok( oParser.parse(), 'SEC(30)' ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 6.48292, 'SEC(30)' ); oParser = new parserFormula( 'SEC(0)', "A1", ws ); ok( oParser.parse(), 'SEC(0)' ); strictEqual( oParser.calculate().getValue(), 1, 'SEC(0)' ); oParser = new parserFormula( 'SEC(1000000000)', "A1", ws ); ok( oParser.parse(), 'SEC(1000000000)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'SEC(1000000000)' ); oParser = new parserFormula( 'SEC(test)', "A1", ws ); ok( oParser.parse(), 'SEC(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'SEC(test)' ); oParser = new parserFormula( 'SEC("test")', "A1", ws ); ok( oParser.parse(), 'SEC("test")' ); strictEqual( oParser.calculate().getValue(), "#VALUE!", 'SEC("test")' ); testArrayFormula("SEC"); } ); test( "Test: \"SECH\"", function () { oParser = new parserFormula( 'SECH(5)', "A1", ws ); ok( oParser.parse(), 'SECH(5)' ); strictEqual( oParser.calculate().getValue().toFixed(3) - 0, 0.013, 'SECH(5)' ); oParser = new parserFormula( 'SECH(0)', "A1", ws ); ok( oParser.parse(), 'SECH(0)' ); strictEqual( oParser.calculate().getValue(), 1, 'SECH(0)' ); oParser = new parserFormula( 'SECH(1000000000)', "A1", ws ); ok( oParser.parse(), 'SECH(1000000000)' ); strictEqual( oParser.calculate().getValue(), 0, 'SECH(1000000000)' ); oParser = new parserFormula( 'SECH(test)', "A1", ws ); ok( oParser.parse(), 'SECH(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'SECH(test)' ); oParser = new parserFormula( 'SECH("test")', "A1", ws ); ok( oParser.parse(), 'SECH("test")' ); strictEqual( oParser.calculate().getValue(), "#VALUE!", 'SECH("test")' ); testArrayFormula("SECH"); } ); test( "Test: \"SECOND\"", function () { ws.getRange2( "A202" ).setValue( "12:45:03 PM" ); ws.getRange2( "A203" ).setValue( "4:48:18 PM" ); ws.getRange2( "A204" ).setValue( "4:48 PM" ); oParser = new parserFormula( "SECOND(A202)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "SECOND(A203)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 18 ); oParser = new parserFormula( "SECOND(A204)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); testArrayFormula2("SECOND",1,1); } ); test( "Test: \"FLOOR\"", function () { oParser = new parserFormula( 'FLOOR(3.7,2)', "A1", ws ); ok( oParser.parse(), 'FLOOR(3.7,2)' ); strictEqual( oParser.calculate().getValue(), 2, 'FLOOR(3.7,2)' ); oParser = new parserFormula( 'FLOOR(-2.5,-2)', "A1", ws ); ok( oParser.parse(), 'FLOOR(-2.5,-2)' ); strictEqual( oParser.calculate().getValue(), -2, 'FLOOR(-2.5,-2)' ); oParser = new parserFormula( 'FLOOR(2.5,-2)', "A1", ws ); ok( oParser.parse(), 'FLOOR(2.5,-2)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'FLOOR(2.5,-2)' ); oParser = new parserFormula( 'FLOOR(1.58,0.1)', "A1", ws ); ok( oParser.parse(), 'FLOOR(1.58,0.1)' ); strictEqual( oParser.calculate().getValue(), 1.5, 'FLOOR(1.58,0.1)' ); oParser = new parserFormula( 'FLOOR(0.234,0.01)', "A1", ws ); ok( oParser.parse(), 'FLOOR(0.234,0.01)' ); strictEqual( oParser.calculate().getValue(), 0.23, 'FLOOR(0.234,0.01)' ); testArrayFormula2("FLOOR", 2, 2); } ); test( "Test: \"FLOOR.PRECISE\"", function () { oParser = new parserFormula( 'FLOOR.PRECISE(-3.2, -1)', "A1", ws ); ok( oParser.parse(), 'FLOOR.PRECISE(-3.2, -1)' ); strictEqual( oParser.calculate().getValue(), -4, 'FLOOR.PRECISE(-3.2, -1)' ); oParser = new parserFormula( 'FLOOR.PRECISE(3.2, 1)', "A1", ws ); ok( oParser.parse(), 'FLOOR.PRECISE(3.2, 1)' ); strictEqual( oParser.calculate().getValue(), 3, 'FLOOR.PRECISE(3.2, 1)' ); oParser = new parserFormula( 'FLOOR.PRECISE(-3.2, 1)', "A1", ws ); ok( oParser.parse(), 'FLOOR.PRECISE(-3.2, 1)' ); strictEqual( oParser.calculate().getValue(), -4, 'FLOOR.PRECISE(-3.2, 1)' ); oParser = new parserFormula( 'FLOOR.PRECISE(3.2, -1)', "A1", ws ); ok( oParser.parse(), 'FLOOR.PRECISE(3.2, -1)' ); strictEqual( oParser.calculate().getValue(), 3, 'FLOOR.PRECISE(3.2, -1)' ); oParser = new parserFormula( 'FLOOR.PRECISE(3.2)', "A1", ws ); ok( oParser.parse(), 'FLOOR.PRECISE(3.2)' ); strictEqual( oParser.calculate().getValue(), 3, 'FLOOR.PRECISE(3.2)' ); oParser = new parserFormula( 'FLOOR.PRECISE(test)', "A1", ws ); ok( oParser.parse(), 'FLOOR.PRECISE(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'FLOOR.PRECISE(test)' ); testArrayFormula2("FLOOR.PRECISE", 1, 2); } ); test( "Test: \"FLOOR.MATH\"", function () { oParser = new parserFormula( 'FLOOR.MATH(24.3, 5)', "A1", ws ); ok( oParser.parse(), 'FLOOR.MATH(24.3, 5)' ); strictEqual( oParser.calculate().getValue(), 20, 'FLOOR.MATH(24.3, 5)' ); oParser = new parserFormula( 'FLOOR.MATH(6.7)', "A1", ws ); ok( oParser.parse(), 'FLOOR.MATH(6.7)' ); strictEqual( oParser.calculate().getValue(), 6, 'FLOOR.MATH(6.7)' ); oParser = new parserFormula( 'FLOOR.MATH(-8.1, 5)', "A1", ws ); ok( oParser.parse(), 'FLOOR.MATH(-8.1, 5)' ); strictEqual( oParser.calculate().getValue(), -10, 'FLOOR.MATH(-8.1, 5)' ); oParser = new parserFormula( 'FLOOR.MATH(-5.5, 2, -1)', "A1", ws ); ok( oParser.parse(), 'FLOOR.MATH(-5.5, 2, -1)' ); strictEqual( oParser.calculate().getValue(), -4, 'FLOOR.MATH(-5.5, 2, -1)' ); testArrayFormula2("FLOOR.MATH", 1, 3); } ); test( "Test: \"CEILING.MATH\"", function () { oParser = new parserFormula( 'CEILING.MATH(24.3, 5)', "A1", ws ); ok( oParser.parse(), 'CEILING.MATH(24.3, 5)' ); strictEqual( oParser.calculate().getValue(), 25, 'CEILING.MATH(24.3, 5)' ); oParser = new parserFormula( 'CEILING.MATH(6.7)', "A1", ws ); ok( oParser.parse(), 'CEILING.MATH(6.7)' ); strictEqual( oParser.calculate().getValue(), 7, 'CEILING.MATH(6.7)' ); oParser = new parserFormula( 'CEILING.MATH(-8.1, 2)', "A1", ws ); ok( oParser.parse(), 'CEILING.MATH(-8.1, 2)' ); strictEqual( oParser.calculate().getValue(), -8, 'CEILING.MATH(-8.1, 2)' ); oParser = new parserFormula( 'CEILING.MATH(-5.5, 2, -1)', "A1", ws ); ok( oParser.parse(), 'CEILING.MATH(-5.5, 2, -1)' ); strictEqual( oParser.calculate().getValue(), -6, 'CEILING.MATH(-5.5, 2, -1)' ); testArrayFormula2("CEILING.MATH", 1, 3); } ); test( "Test: \"CEILING.PRECISE\"", function () { oParser = new parserFormula( 'CEILING.PRECISE(4.3)', "A1", ws ); ok( oParser.parse(), 'CEILING.PRECISE(4.3)' ); strictEqual( oParser.calculate().getValue(), 5, 'CEILING.PRECISE(4.3)' ); oParser = new parserFormula( 'CEILING.PRECISE(-4.3)', "A1", ws ); ok( oParser.parse(), 'CEILING.PRECISE(-4.3)' ); strictEqual( oParser.calculate().getValue(), -4, 'CEILING.PRECISE(-4.3)' ); oParser = new parserFormula( 'CEILING.PRECISE(4.3, 2)', "A1", ws ); ok( oParser.parse(), 'CEILING.PRECISE(4.3, 2)' ); strictEqual( oParser.calculate().getValue(), 6, 'CEILING.PRECISE(4.3, 2)' ); oParser = new parserFormula( 'CEILING.PRECISE(4.3,-2)', "A1", ws ); ok( oParser.parse(), 'CEILING.PRECISE(4.3,-2)' ); strictEqual( oParser.calculate().getValue(), 6, 'CEILING.PRECISE(4.3,-2)' ); oParser = new parserFormula( 'CEILING.PRECISE(-4.3,2)', "A1", ws ); ok( oParser.parse(), 'CEILING.PRECISE(-4.3,2)' ); strictEqual( oParser.calculate().getValue(), -4, 'CEILING.PRECISE(-4.3,2)' ); oParser = new parserFormula( 'CEILING.PRECISE(-4.3,-2)', "A1", ws ); ok( oParser.parse(), 'CEILING.PRECISE(-4.3,-2)' ); strictEqual( oParser.calculate().getValue(), -4, 'CEILING.PRECISE(-4.3,-2)' ); oParser = new parserFormula( 'CEILING.PRECISE(test)', "A1", ws ); ok( oParser.parse(), 'CEILING.PRECISE(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'CEILING.PRECISE(test)' ); testArrayFormula2("CEILING.PRECISE", 1, 2); } ); test( "Test: \"ISO.CEILING\"", function () { oParser = new parserFormula( 'ISO.CEILING(4.3)', "A1", ws ); ok( oParser.parse(), 'ISO.CEILING(4.3)' ); strictEqual( oParser.calculate().getValue(), 5, 'ISO.CEILING(4.3)' ); oParser = new parserFormula( 'ISO.CEILING(-4.3)', "A1", ws ); ok( oParser.parse(), 'ISO.CEILING(-4.3)' ); strictEqual( oParser.calculate().getValue(), -4, 'ISO.CEILING(-4.3)' ); oParser = new parserFormula( 'ISO.CEILING(4.3, 2)', "A1", ws ); ok( oParser.parse(), 'ISO.CEILING(4.3, 2)' ); strictEqual( oParser.calculate().getValue(), 6, 'ISO.CEILING(4.3, 2)' ); oParser = new parserFormula( 'ISO.CEILING(4.3,-2)', "A1", ws ); ok( oParser.parse(), 'ISO.CEILING(4.3,-2)' ); strictEqual( oParser.calculate().getValue(), 6, 'ISO.CEILING(4.3,-2)' ); oParser = new parserFormula( 'ISO.CEILING(-4.3,2)', "A1", ws ); ok( oParser.parse(), 'ISO.CEILING(-4.3,2)' ); strictEqual( oParser.calculate().getValue(), -4, 'ISO.CEILING(-4.3,2)' ); oParser = new parserFormula( 'ISO.CEILING(-4.3,-2)', "A1", ws ); ok( oParser.parse(), 'ISO.CEILING(-4.3,-2)' ); strictEqual( oParser.calculate().getValue(), -4, 'ISO.CEILING(-4.3,-2)' ); testArrayFormula2("ISO.CEILING", 1, 2); } ); test( "Test: \"ISBLANK\"", function () { ws.getRange2( "A202" ).setValue( "" ); ws.getRange2( "A203" ).setValue( "test" ); oParser = new parserFormula( 'ISBLANK(A202)', "A1", ws ); ok( oParser.parse(), 'ISBLANK(A202)' ); strictEqual( oParser.calculate().getValue(), "TRUE", 'ISBLANK(A202)' ); oParser = new parserFormula( 'ISBLANK(A203)', "A1", ws ); ok( oParser.parse(), 'ISBLANK(A203)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISBLANK(A203)' ); testArrayFormula2("ISBLANK", 1, 1); } ); test( "Test: \"ISERROR\"", function () { ws.getRange2( "A202" ).setValue( "" ); ws.getRange2( "A203" ).setValue( "#N/A" ); oParser = new parserFormula( 'ISERROR(A202)', "A1", ws ); ok( oParser.parse(), 'ISERROR(A202)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISERROR(A202)' ); oParser = new parserFormula( 'ISERROR(A203)', "A1", ws ); ok( oParser.parse(), 'ISERROR(A203)' ); strictEqual( oParser.calculate().getValue(), "TRUE", 'ISERROR(A203)' ); testArrayFormula2("ISERROR", 1, 1); } ); test( "Test: \"ISERR\"", function () { ws.getRange2( "A202" ).setValue( "" ); ws.getRange2( "A203" ).setValue( "#N/A" ); ws.getRange2( "A204" ).setValue( "#VALUE!" ); oParser = new parserFormula( 'ISERR(A202)', "A1", ws ); ok( oParser.parse(), 'ISERR(A202)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISERR(A202)' ); oParser = new parserFormula( 'ISERR(A203)', "A1", ws ); ok( oParser.parse(), 'ISERR(A203)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISERR(A203)' ); oParser = new parserFormula( 'ISERR(A203)', "A1", ws ); ok( oParser.parse(), 'ISERR(A203)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISERR(A203)' ); testArrayFormula2("ISERR", 1, 1); } ); test( "Test: \"ISEVEN\"", function () { oParser = new parserFormula( 'ISEVEN(-1)', "A1", ws ); ok( oParser.parse(), 'ISEVEN(-1)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISEVEN(-1)' ); oParser = new parserFormula( 'ISEVEN(2.5)', "A1", ws ); ok( oParser.parse(), 'ISEVEN(2.5)' ); strictEqual( oParser.calculate().getValue(), "TRUE", 'ISEVEN(2.5)' ); oParser = new parserFormula( 'ISEVEN(5)', "A1", ws ); ok( oParser.parse(), 'ISEVEN(5)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISEVEN(5)' ); oParser = new parserFormula( 'ISEVEN(0)', "A1", ws ); ok( oParser.parse(), 'ISEVEN(0)' ); strictEqual( oParser.calculate().getValue(), "TRUE", 'ISEVEN(0)' ); oParser = new parserFormula( 'ISEVEN(12/23/2011)', "A1", ws ); ok( oParser.parse(), 'ISEVEN(12/23/2011)' ); strictEqual( oParser.calculate().getValue(), "TRUE", 'ISEVEN(12/23/2011)' ); testArrayFormula2("ISEVEN", 1, 1, true); } ); test( "Test: \"ISLOGICAL\"", function () { oParser = new parserFormula( 'ISLOGICAL(TRUE)', "A1", ws ); ok( oParser.parse(), 'ISLOGICAL(TRUE)' ); strictEqual( oParser.calculate().getValue(), "TRUE", 'ISLOGICAL(TRUE)' ); oParser = new parserFormula( 'ISLOGICAL("TRUE")', "A1", ws ); ok( oParser.parse(), 'ISLOGICAL("TRUE")' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISLOGICAL("TRUE")' ); testArrayFormula2("ISLOGICAL", 1, 1); } ); test( "Test: \"CEILING\"", function () { oParser = new parserFormula( 'CEILING(2.5, 1)', "A1", ws ); ok( oParser.parse(), 'CEILING(2.5, 1)' ); strictEqual( oParser.calculate().getValue(), 3, 'CEILING(2.5, 1)' ); oParser = new parserFormula( 'CEILING(-2.5, -2)', "A1", ws ); ok( oParser.parse(), 'CEILING(-2.5, -2)' ); strictEqual( oParser.calculate().getValue(), -4, 'CEILING(-2.5, -2)' ); oParser = new parserFormula( 'CEILING(-2.5, 2)', "A1", ws ); ok( oParser.parse(), 'CEILING(-2.5, 2)' ); strictEqual( oParser.calculate().getValue(), -2, 'CEILING(-2.5, 2)' ); oParser = new parserFormula( 'CEILING(1.5, 0.1)', "A1", ws ); ok( oParser.parse(), 'CEILING(1.5, 0.1)' ); strictEqual( oParser.calculate().getValue(), 1.5, 'CEILING(1.5, 0.1)' ); oParser = new parserFormula( 'CEILING(0.234, 0.01)', "A1", ws ); ok( oParser.parse(), 'CEILING(0.234, 0.01)' ); strictEqual( oParser.calculate().getValue(), 0.24, 'CEILING(0.234, 0.01)' ); testArrayFormula2("CEILING", 2, 2); } ); test( "Test: \"ECMA.CEILING\"", function () { oParser = new parserFormula( 'ECMA.CEILING(2.5, 1)', "A1", ws ); ok( oParser.parse(), 'ECMA.CEILING(2.5, 1)' ); strictEqual( oParser.calculate().getValue(), 3, 'ECMA.CEILING(2.5, 1)' ); oParser = new parserFormula( 'ECMA.CEILING(-2.5, -2)', "A1", ws ); ok( oParser.parse(), 'ECMA.CEILING(-2.5, -2)' ); strictEqual( oParser.calculate().getValue(), -4, 'ECMA.CEILING(-2.5, -2)' ); oParser = new parserFormula( 'ECMA.CEILING(-2.5, 2)', "A1", ws ); ok( oParser.parse(), 'ECMA.CEILING(-2.5, 2)' ); strictEqual( oParser.calculate().getValue(), -2, 'ECMA.CEILING(-2.5, 2)' ); oParser = new parserFormula( 'ECMA.CEILING(1.5, 0.1)', "A1", ws ); ok( oParser.parse(), 'ECMA.CEILING(1.5, 0.1)' ); strictEqual( oParser.calculate().getValue(), 1.5, 'ECMA.CEILING(1.5, 0.1)' ); oParser = new parserFormula( 'ECMA.CEILING(0.234, 0.01)', "A1", ws ); ok( oParser.parse(), 'ECMA.CEILING(0.234, 0.01)' ); strictEqual( oParser.calculate().getValue(), 0.24, 'ECMA.CEILING(0.234, 0.01)' ); } ); test( "Test: \"COMBINA\"", function () { oParser = new parserFormula( 'COMBINA(4,3)', "A1", ws ); ok( oParser.parse(), 'COMBINA(4,3)' ); strictEqual( oParser.calculate().getValue(), 20, 'COMBINA(4,3)' ); oParser = new parserFormula( 'COMBINA(10,3)', "A1", ws ); ok( oParser.parse(), 'COMBINA(10,3)' ); strictEqual( oParser.calculate().getValue(), 220, 'COMBINA(10,3)' ); oParser = new parserFormula( 'COMBINA(3,10)', "A1", ws ); ok( oParser.parse(), 'COMBINA(3,10)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'COMBINA(10,3)' ); oParser = new parserFormula( 'COMBINA(10,-3)', "A1", ws ); ok( oParser.parse(), 'COMBINA(10,-3)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'COMBINA(10,-3)' ); testArrayFormula2("COMBINA", 2, 2) } ); test( "Test: \"DECIMAL\"", function () { oParser = new parserFormula( 'DECIMAL("FF",16)', "A1", ws ); ok( oParser.parse(), 'DECIMAL("FF",16)' ); strictEqual( oParser.calculate().getValue(), 255, 'DECIMAL("FF",16)' ); oParser = new parserFormula( 'DECIMAL(111,2)', "A1", ws ); ok( oParser.parse(), 'DECIMAL(111,2)' ); strictEqual( oParser.calculate().getValue(), 7, 'DECIMAL(111,2)' ); oParser = new parserFormula( 'DECIMAL("zap",36)', "A1", ws ); ok( oParser.parse(), 'DECIMAL("zap",36)' ); strictEqual( oParser.calculate().getValue(), 45745, 'DECIMAL("zap",36)' ); oParser = new parserFormula( 'DECIMAL("00FF",16)', "A1", ws ); ok( oParser.parse(), 'DECIMAL("00FF",16)' ); strictEqual( oParser.calculate().getValue(), 255, 'DECIMAL("00FF",16)' ); oParser = new parserFormula( 'DECIMAL("101b",2)', "A1", ws ); ok( oParser.parse(), 'DECIMAL("101b",2)' ); strictEqual( oParser.calculate().getValue(), 5, 'DECIMAL("101b",2)' ); testArrayFormula2("DECIMAL", 2, 2); } ); test( "Test: \"BASE\"", function () { oParser = new parserFormula( 'BASE(7,2)', "A1", ws ); ok( oParser.parse(), 'BASE(7,2)' ); strictEqual( oParser.calculate().getValue(), "111", 'BASE(7,2)' ); oParser = new parserFormula( 'BASE(100,16)', "A1", ws ); ok( oParser.parse(), 'BASE(100,16)' ); strictEqual( oParser.calculate().getValue(), "64", 'BASE(100,16)' ); oParser = new parserFormula( 'BASE(15,2,10)', "A1", ws ); ok( oParser.parse(), 'BASE(15,2,10)' ); strictEqual( oParser.calculate().getValue(), "0000001111", 'BASE(15,2,10)' ); testArrayFormula2("BASE", 2, 3); } ); test( "Test: \"ARABIC('LVII')\"", function () { oParser = new parserFormula( 'ARABIC("LVII")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 57 ); } ); test( "Test: \"TDIST\"", function () { oParser = new parserFormula( "TDIST(60,1,2)", "A1", ws ); ok( oParser.parse(), "TDIST(60,1,2)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.010609347, "TDIST(60,1,2)" ); oParser = new parserFormula( "TDIST(8,3,1)", "A1", ws ); ok( oParser.parse(), "TDIST(8,3,1)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.002038289, "TDIST(8,3,1)" ); ws.getRange2( "A2" ).setValue( "1.959999998" ); ws.getRange2( "A3" ).setValue( "60" ); oParser = new parserFormula( "TDIST(A2,A3,2)", "A1", ws ); ok( oParser.parse(), "TDIST(A2,A3,2)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.054644930, "TDIST(A2,A3,2)" ); oParser = new parserFormula( "TDIST(A2,A3,1)", "A1", ws ); ok( oParser.parse(), "TDIST(A2,A3,1)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.027322465, "TDIST(A2,A3,1)" ); testArrayFormula2("TDIST", 3, 3); } ); test( "Test: \"T.DIST\"", function () { oParser = new parserFormula( "T.DIST(60,1,TRUE)", "A1", ws ); ok( oParser.parse(), "T.DIST(60,1,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.99469533, "T.DIST(60,1,TRUE)" ); oParser = new parserFormula( "T.DIST(8,3,FALSE)", "A1", ws ); ok( oParser.parse(), "T.DIST(8,3,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.00073691, "T.DIST(8,3,FALSE)" ); testArrayFormula2("T.DIST", 3, 3); } ); test( "Test: \"T.DIST.2T\"", function () { ws.getRange2( "A2" ).setValue( "1.959999998" ); ws.getRange2( "A3" ).setValue( "60" ); oParser = new parserFormula( "T.DIST.2T(A2,A3)", "A1", ws ); ok( oParser.parse(), "T.DIST.2T(A2,A3)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.054644930, "T.DIST.2T(A2,A3)" ); testArrayFormula2("T.DIST.2T", 2, 2) } ); test( "Test: \"T.DIST.RT\"", function () { ws.getRange2( "A2" ).setValue( "1.959999998" ); ws.getRange2( "A3" ).setValue( "60" ); oParser = new parserFormula( "T.DIST.RT(A2,A3)", "A1", ws ); ok( oParser.parse(), "T.DIST.RT(A2,A3)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.027322, "T.DIST.RT(A2,A3)" ); testArrayFormula2("T.DIST.RT", 2, 2); } ); test( "Test: \"TTEST\"", function () { ws.getRange2( "A2" ).setValue( "3" ); ws.getRange2( "A3" ).setValue( "4" ); ws.getRange2( "A4" ).setValue( "5" ); ws.getRange2( "A5" ).setValue( "8" ); ws.getRange2( "A6" ).setValue( "9" ); ws.getRange2( "A7" ).setValue( "1" ); ws.getRange2( "A8" ).setValue( "2" ); ws.getRange2( "A9" ).setValue( "4" ); ws.getRange2( "A10" ).setValue( "5" ); ws.getRange2( "B2" ).setValue( "6" ); ws.getRange2( "B3" ).setValue( "19" ); ws.getRange2( "B4" ).setValue( "3" ); ws.getRange2( "B5" ).setValue( "2" ); ws.getRange2( "B6" ).setValue( "14" ); ws.getRange2( "B7" ).setValue( "4" ); ws.getRange2( "B8" ).setValue( "5" ); ws.getRange2( "B9" ).setValue( "17" ); ws.getRange2( "B10" ).setValue( "1" ); oParser = new parserFormula( "TTEST(A2:A10,B2:B10,2,1)", "A1", ws ); ok( oParser.parse(), "TTEST(A2:A10,B2:B10,2,1)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.196016, "TTEST(A2:A10,B2:B10,2,1)" ); //TODO нужна другая функция для тестирования //testArrayFormula2("TTEST", 4, 4, null, true); } ); test( "Test: \"T.TEST\"", function () { ws.getRange2( "A2" ).setValue( "3" ); ws.getRange2( "A3" ).setValue( "4" ); ws.getRange2( "A4" ).setValue( "5" ); ws.getRange2( "A5" ).setValue( "8" ); ws.getRange2( "A6" ).setValue( "9" ); ws.getRange2( "A7" ).setValue( "1" ); ws.getRange2( "A8" ).setValue( "2" ); ws.getRange2( "A9" ).setValue( "4" ); ws.getRange2( "A10" ).setValue( "5" ); ws.getRange2( "B2" ).setValue( "6" ); ws.getRange2( "B3" ).setValue( "19" ); ws.getRange2( "B4" ).setValue( "3" ); ws.getRange2( "B5" ).setValue( "2" ); ws.getRange2( "B6" ).setValue( "14" ); ws.getRange2( "B7" ).setValue( "4" ); ws.getRange2( "B8" ).setValue( "5" ); ws.getRange2( "B9" ).setValue( "17" ); ws.getRange2( "B10" ).setValue( "1" ); oParser = new parserFormula( "T.TEST(A2:A10,B2:B10,2,1)", "A1", ws ); ok( oParser.parse(), "T.TEST(A2:A10,B2:B10,2,1)" ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 0.19602, "T.TEST(A2:A10,B2:B10,2,1)" ); } ); test( "Test: \"ZTEST\"", function () { ws.getRange2( "A2" ).setValue( "3" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "7" ); ws.getRange2( "A5" ).setValue( "8" ); ws.getRange2( "A6" ).setValue( "6" ); ws.getRange2( "A7" ).setValue( "5" ); ws.getRange2( "A8" ).setValue( "4" ); ws.getRange2( "A9" ).setValue( "2" ); ws.getRange2( "A10" ).setValue( "1" ); ws.getRange2( "A11" ).setValue( "9" ); oParser = new parserFormula( "ZTEST(A2:A11,4)", "A1", ws ); ok( oParser.parse(), "ZTEST(A2:A11,4)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.090574, "ZTEST(A2:A11,4)" ); oParser = new parserFormula( "2 * MIN(ZTEST(A2:A11,4), 1 - ZTEST(A2:A11,4))", "A1", ws ); ok( oParser.parse(), "2 * MIN(ZTEST(A2:A11,4), 1 - ZTEST(A2:A11,4))" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.181148, "2 * MIN(ZTEST(A2:A11,4), 1 - ZTEST(A2:A11,4))" ); oParser = new parserFormula( "ZTEST(A2:A11,6)", "A1", ws ); ok( oParser.parse(), "ZTEST(A2:A11,6)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.863043, "ZTEST(A2:A11,6)" ); oParser = new parserFormula( "2 * MIN(ZTEST(A2:A11,6), 1 - ZTEST(A2:A11,6))", "A1", ws ); ok( oParser.parse(), "2 * MIN(ZTEST(A2:A11,6), 1 - ZTEST(A2:A11,6))" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.273913, "2 * MIN(ZTEST(A2:A11,6), 1 - ZTEST(A2:A11,6))" ); //TODO нужна другая функция для тестирования //testArrayFormula2("Z.TEST", 2, 3, null, true); } ); test( "Test: \"Z.TEST\"", function () { ws.getRange2( "A2" ).setValue( "3" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "7" ); ws.getRange2( "A5" ).setValue( "8" ); ws.getRange2( "A6" ).setValue( "6" ); ws.getRange2( "A7" ).setValue( "5" ); ws.getRange2( "A8" ).setValue( "4" ); ws.getRange2( "A9" ).setValue( "2" ); ws.getRange2( "A10" ).setValue( "1" ); ws.getRange2( "A11" ).setValue( "9" ); oParser = new parserFormula( "Z.TEST(A2:A11,4)", "A1", ws ); ok( oParser.parse(), "Z.TEST(A2:A11,4)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.090574, "Z.TEST(A2:A11,4)" ); oParser = new parserFormula( "2 * MIN(Z.TEST(A2:A11,4), 1 - Z.TEST(A2:A11,4))", "A1", ws ); ok( oParser.parse(), "2 * MIN(Z.TEST(A2:A11,4), 1 - Z.TEST(A2:A11,4))" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.181148, "2 * MIN(Z.TEST(A2:A11,4), 1 - Z.TEST(A2:A11,4))" ); oParser = new parserFormula( "Z.TEST(A2:A11,6)", "A1", ws ); ok( oParser.parse(), "Z.TEST(A2:A11,6)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.863043, "Z.TEST(A2:A11,6)" ); oParser = new parserFormula( "2 * MIN(Z.TEST(A2:A11,6), 1 - Z.TEST(A2:A11,6))", "A1", ws ); ok( oParser.parse(), "2 * MIN(Z.TEST(A2:A11,6), 1 - Z.TEST(A2:A11,6))" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.273913, "2 * MIN(Z.TEST(A2:A11,6), 1 - Z.TEST(A2:A11,6))" ); //TODO нужна другая функция для тестирования //testArrayFormula2("Z.TEST", 2, 3, null, true); } ); test( "Test: \"F.DIST\"", function () { ws.getRange2( "A2" ).setValue( "15.2069" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "4" ); oParser = new parserFormula( "F.DIST(A2,A3,A4,TRUE)", "A1", ws ); ok( oParser.parse(), "F.DIST(A2,A3,A4,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.99, "F.DIST(A2,A3,A4,TRUE)" ); oParser = new parserFormula( "F.DIST(A2,A3,A4,FALSE)", "A1", ws ); ok( oParser.parse(), "F.DIST(A2,A3,A4,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0012238, "F.DIST(A2,A3,A4,FALSE)" ); testArrayFormula2("F.DIST", 4, 4); } ); test( "Test: \"F.DIST.RT\"", function () { ws.getRange2( "A2" ).setValue( "15.2069" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "4" ); oParser = new parserFormula( "F.DIST.RT(A2,A3,A4)", "A1", ws ); ok( oParser.parse(), "F.DIST.RT(A2,A3,A4)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.01, "F.DIST.RT(A2,A3,A4)" ); testArrayFormula2("F.DIST.RT", 3, 3); } ); test( "Test: \"FDIST\"", function () { ws.getRange2( "A2" ).setValue( "15.2069" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "4" ); oParser = new parserFormula( "FDIST(A2,A3,A4)", "A1", ws ); ok( oParser.parse(), "FDIST(A2,A3,A4)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.01, "FDIST(A2,A3,A4)" ); } ); test( "Test: \"FINV\"", function () { ws.getRange2( "A2" ).setValue( "0.01" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "4" ); oParser = new parserFormula( "FINV(A2,A3,A4)", "A1", ws ); ok( oParser.parse(), "FINV(A2,A3,A4)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 15.206865, "FINV(A2,A3,A4)" ); testArrayFormula2("FINV", 3, 3); } ); test( "Test: \"F.INV\"", function () { ws.getRange2( "A2" ).setValue( "0.01" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "4" ); oParser = new parserFormula( "F.INV(A2,A3,A4)", "A1", ws ); ok( oParser.parse(), "F.INV(A2,A3,A4)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.10930991, "F.INV(A2,A3,A4)" ); testArrayFormula2("F.INV", 3, 3); } ); test( "Test: \"F.INV.RT\"", function () { ws.getRange2( "A2" ).setValue( "0.01" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "4" ); oParser = new parserFormula( "F.INV.RT(A2,A3,A4)", "A1", ws ); ok( oParser.parse(), "F.INV.RT(A2,A3,A4)" ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 15.20686, "F.INV.RT(A2,A3,A4)" ); } ); function fTestFormulaTest(){ ws.getRange2( "A2" ).setValue( "6" ); ws.getRange2( "A3" ).setValue( "7" ); ws.getRange2( "A4" ).setValue( "9" ); ws.getRange2( "A5" ).setValue( "15" ); ws.getRange2( "A6" ).setValue( "21" ); ws.getRange2( "B2" ).setValue( "20" ); ws.getRange2( "B3" ).setValue( "28" ); ws.getRange2( "B4" ).setValue( "31" ); ws.getRange2( "B5" ).setValue( "38" ); ws.getRange2( "B6" ).setValue( "40" ); oParser = new parserFormula( "FTEST(A2:A6,B2:B6)", "A1", ws ); ok( oParser.parse(), "FTEST(A2:A6,B2:B6)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.64831785, "FTEST(A2:A6,B2:B6)" ); oParser = new parserFormula( "FTEST(A2,B2:B6)", "A1", ws ); ok( oParser.parse(), "FTEST(A2,B2:B6)" ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", "FTEST(A2,B2:B6)" ); oParser = new parserFormula( "FTEST(1,B2:B6)", "A1", ws ); ok( oParser.parse(), "FTEST(1,B2:B6)" ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", "FTEST(1,B2:B6)" ); oParser = new parserFormula( "FTEST({1,2,3},{2,3,4,5})", "A1", ws ); ok( oParser.parse(), "FTEST({1,2,3},{2,3,4,5})" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.792636779, "FTEST({1,2,3},{2,3,4,5})" ); oParser = new parserFormula( "FTEST({1,\"test\",\"test\"},{2,3,4,5})", "A1", ws ); ok( oParser.parse(), "FTEST({1,\"test\",\"test\"},{2,3,4,5})" ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", "FTEST({1,\"test\",\"test\"},{2,3,4,5})" ); } test( "Test: \"FTEST\"", function () { fTestFormulaTest(); testArrayFormula2("FTEST", 2, 2, null, true); } ); test( "Test: \"F.TEST\"", function () { fTestFormulaTest(); testArrayFormula2("F.TEST", 2, 2, null, true); } ); test( "Test: \"T.INV\"", function () { oParser = new parserFormula( "T.INV(0.75,2)", "A1", ws ); ok( oParser.parse(), "T.INV(0.75,2)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.8164966, "T.INV(0.75,2)" ); testArrayFormula2("T.INV", 2, 2); } ); test( "Test: \"T.INV.2T\"", function () { ws.getRange2( "A2" ).setValue( "0.546449" ); ws.getRange2( "A3" ).setValue( "60" ); oParser = new parserFormula( "T.INV.2T(A2,A3)", "A1", ws ); ok( oParser.parse(), "T.INV.2T(A2,A3)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.606533, "T.INV.2T(A2,A3)" ); testArrayFormula2("T.INV.2T", 2, 2); } ); test( "Test: \"RANK\"", function () { ws.getRange2( "A2" ).setValue( "7" ); ws.getRange2( "A3" ).setValue( "3.5" ); ws.getRange2( "A4" ).setValue( "3.5" ); ws.getRange2( "A5" ).setValue( "1" ); ws.getRange2( "A6" ).setValue( "2" ); oParser = new parserFormula( "RANK(A3,A2:A6,1)", "A1", ws ); ok( oParser.parse(), "RANK(A3,A2:A6,1)" ); strictEqual( oParser.calculate().getValue(), 3, "RANK(A3,A2:A6,1)" ); oParser = new parserFormula( "RANK(A2,A2:A6,1)", "A1", ws ); ok( oParser.parse(), "RANK(A2,A2:A6,1)" ); strictEqual( oParser.calculate().getValue(), 5, "RANK(A2,A2:A6,1)" ); } ); test( "Test: \"RANK.EQ\"", function () { ws.getRange2( "A2" ).setValue( "7" ); ws.getRange2( "A3" ).setValue( "3.5" ); ws.getRange2( "A4" ).setValue( "3.5" ); ws.getRange2( "A5" ).setValue( "1" ); ws.getRange2( "A6" ).setValue( "2" ); oParser = new parserFormula( "RANK.EQ(A2,A2:A6,1)", "A1", ws ); ok( oParser.parse(), "RANK.EQ(A2,A2:A6,1)" ); strictEqual( oParser.calculate().getValue(), 5, "RANK.EQ(A2,A2:A6,1)" ); oParser = new parserFormula( "RANK.EQ(A6,A2:A6)", "A1", ws ); ok( oParser.parse(), "RANK.EQ(A6,A2:A6)" ); strictEqual( oParser.calculate().getValue(), 4, "RANK.EQ(A6,A2:A6)" ); oParser = new parserFormula( "RANK.EQ(A3,A2:A6,1)", "A1", ws ); ok( oParser.parse(), "RANK.EQ(A3,A2:A6,1)" ); strictEqual( oParser.calculate().getValue(), 3, "RANK.EQ(A3,A2:A6,1)" ); } ); test( "Test: \"RANK.AVG\"", function () { ws.getRange2( "A2" ).setValue( "89" ); ws.getRange2( "A3" ).setValue( "88" ); ws.getRange2( "A4" ).setValue( "92" ); ws.getRange2( "A5" ).setValue( "101" ); ws.getRange2( "A6" ).setValue( "94" ); ws.getRange2( "A7" ).setValue( "97" ); ws.getRange2( "A8" ).setValue( "95" ); oParser = new parserFormula( "RANK.AVG(94,A2:A8)", "A1", ws ); ok( oParser.parse(), "RANK.AVG(94,A2:A8)" ); strictEqual( oParser.calculate().getValue(), 4, "RANK.AVG(94,A2:A8)" ); } ); test( "Test: \"RADIANS\"", function () { oParser = new parserFormula( "RADIANS(270)", "A1", ws ); ok( oParser.parse(), "RADIANS(270)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 4.712389 ); testArrayFormula("RADIANS"); } ); test( "Test: \"LOG\"", function () { oParser = new parserFormula( "LOG(10)", "A1", ws ); ok( oParser.parse(), "LOG(10)" ); strictEqual( oParser.calculate().getValue(), 1, "LOG(10)" ); oParser = new parserFormula( "LOG(8,2)", "A1", ws ); ok( oParser.parse(), "LOG(8,2)" ); strictEqual( oParser.calculate().getValue(), 3, "LOG(8,2)" ); oParser = new parserFormula( "LOG(86, 2.7182818)", "A1", ws ); ok( oParser.parse(), "LOG(86, 2.7182818)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 4.4543473, "LOG(86, 2.7182818)" ); oParser = new parserFormula( "LOG(8,1)", "A1", ws ); ok( oParser.parse(), "LOG(8,1)" ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", "LOG(8,1)" ); testArrayFormula("LOG", 1, 2); } ); test( "Test: \"LOGNORM.DIST\"", function () { ws.getRange2( "A2" ).setValue( "4" ); ws.getRange2( "A3" ).setValue( "3.5" ); ws.getRange2( "A4" ).setValue( "1.2" ); oParser = new parserFormula( "LOGNORM.DIST(A2,A3,A4,TRUE)", "A1", ws ); ok( oParser.parse(), "LOGNORM.DIST(A2,A3,A4,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0390836, "LOGNORM.DIST(A2,A3,A4,TRUE)" ); oParser = new parserFormula( "LOGNORM.DIST(A2,A3,A4,FALSE)", "A1", ws ); ok( oParser.parse(), "LOGNORM.DIST(A2,A3,A4,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0176176, "LOGNORM.DIST(A2,A3,A4,FALSE)" ); testArrayFormula2("LOGNORM.DIST", 4, 4); } ); test( "Test: \"LOGNORM.INV\"", function () { ws.getRange2( "A2" ).setValue( "0.039084" ); ws.getRange2( "A3" ).setValue( "3.5" ); ws.getRange2( "A4" ).setValue( "1.2" ); oParser = new parserFormula( "LOGNORM.INV(A2, A3, A4)", "A1", ws ); ok( oParser.parse(), "LOGNORM.INV(A2, A3, A4)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 4.0000252, "LOGNORM.INV(A2, A3, A4)" ); testArrayFormula2("LOGNORM.INV", 3, 3); } ); test( "Test: \"LOGNORMDIST\"", function () { ws.getRange2( "A2" ).setValue( "4" ); ws.getRange2( "A3" ).setValue( "3.5" ); ws.getRange2( "A4" ).setValue( "1.2" ); oParser = new parserFormula( "LOGNORMDIST(A2, A3, A4)", "A1", ws ); ok( oParser.parse(), "LOGNORMDIST(A2, A3, A4)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0390836, "LOGNORMDIST(A2, A3, A4)" ); testArrayFormula2("LOGNORMDIST", 3, 3); } ); test( "Test: \"LOWER\"", function () { ws.getRange2( "A2" ).setValue( "E. E. Cummings" ); ws.getRange2( "A3" ).setValue( "Apt. 2B" ); oParser = new parserFormula( "LOWER(A2)", "A1", ws ); ok( oParser.parse(), "LOWER(A2)" ); strictEqual( oParser.calculate().getValue(), "e. e. cummings", "LOWER(A2)" ); oParser = new parserFormula( "LOWER(A3)", "A1", ws ); ok( oParser.parse(), "LOWER(A3)" ); strictEqual( oParser.calculate().getValue(), "apt. 2b", "LOWER(A3)" ); testArrayFormula2("LOWER", 1, 1); } ); test( "Test: \"EXPON.DIST\"", function () { ws.getRange2( "A2" ).setValue( "0.2" ); ws.getRange2( "A3" ).setValue( "10" ); oParser = new parserFormula( "EXPON.DIST(A2,A3,TRUE)", "A1", ws ); ok( oParser.parse(), "EXPON.DIST(A2,A3,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.86466472, "EXPON.DIST(A2,A3,TRUE)" ); oParser = new parserFormula( "EXPON.DIST(0.2,10,FALSE)", "A1", ws ); ok( oParser.parse(), "EXPON.DIST(0.2,10,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 1.35335283, "EXPON.DIST(0.2,10,FALSE)" ); testArrayFormula2("EXPON.DIST", 3, 3); } ); test( "Test: \"GAMMA.DIST\"", function () { ws.getRange2( "A2" ).setValue( "10.00001131" ); ws.getRange2( "A3" ).setValue( "9" ); ws.getRange2( "A4" ).setValue( "2" ); oParser = new parserFormula( "GAMMA.DIST(A2,A3,A4,FALSE)", "A1", ws ); ok( oParser.parse(), "GAMMA.DIST(A2,A3,A4,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.032639, "GAMMA.DIST(A2,A3,A4,FALSE)" ); oParser = new parserFormula( "GAMMA.DIST(A2,A3,A4,TRUE)", "A1", ws ); ok( oParser.parse(), "GAMMA.DIST(A2,A3,A4,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.068094, "GAMMA.DIST(A2,A3,A4,TRUE)" ); testArrayFormula2("GAMMA.DIST", 4, 4); } ); test( "Test: \"GAMMADIST\"", function () { ws.getRange2( "A2" ).setValue( "10.00001131" ); ws.getRange2( "A3" ).setValue( "9" ); ws.getRange2( "A4" ).setValue( "2" ); oParser = new parserFormula( "GAMMADIST(A2,A3,A4,FALSE)", "A1", ws ); ok( oParser.parse(), "GAMMADIST(A2,A3,A4,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.032639, "GAMMADIST(A2,A3,A4,FALSE)" ); oParser = new parserFormula( "GAMMADIST(A2,A3,A4,TRUE)", "A1", ws ); ok( oParser.parse(), "GAMMADIST(A2,A3,A4,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.068094, "GAMMADIST(A2,A3,A4,TRUE)" ); } ); test( "Test: \"GAMMADIST\"", function () { oParser = new parserFormula( "GAMMADIST(A2,A3,A4,FALSE)", "A1", ws ); ok( oParser.parse(), "GAMMADIST(A2,A3,A4,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.032639, "GAMMADIST(A2,A3,A4,FALSE)" ); oParser = new parserFormula( "GAMMADIST(A2,A3,A4,TRUE)", "A1", ws ); ok( oParser.parse(), "GAMMADIST(A2,A3,A4,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.068094, "GAMMADIST(A2,A3,A4,TRUE)" ); } ); test( "Test: \"GAMMA\"", function () { oParser = new parserFormula( "GAMMA(2.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(3), "1.329" ); oParser = new parserFormula( "GAMMA(-3.75)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(3), "0.268" ); oParser = new parserFormula( "GAMMA(0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "GAMMA(-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("GAMMA", 1, 1); } ); test( "Test: \"CHITEST\"", function () { ws.getRange2( "A2" ).setValue( "58" ); ws.getRange2( "A3" ).setValue( "11" ); ws.getRange2( "A4" ).setValue( "10" ); ws.getRange2( "A5" ).setValue( "x" ); ws.getRange2( "A6" ).setValue( "45.35" ); ws.getRange2( "A7" ).setValue( "17.56" ); ws.getRange2( "A8" ).setValue( "16.09" ); ws.getRange2( "B2" ).setValue( "35" ); ws.getRange2( "B3" ).setValue( "25" ); ws.getRange2( "B4" ).setValue( "23" ); ws.getRange2( "B5" ).setValue( "x" ); ws.getRange2( "B6" ).setValue( "47.65" ); ws.getRange2( "B7" ).setValue( "18.44" ); ws.getRange2( "B8" ).setValue( "16.91" ); oParser = new parserFormula( "CHITEST(A2:B4,A6:B8)", "A1", ws ); ok( oParser.parse(), "CHITEST(A2:B4,A6:B8)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0003082, "CHITEST(A2:B4,A6:B8)" ); testArrayFormula2("CHITEST", 2, 2, null, true); } ); test( "Test: \"CHISQ.TEST\"", function () { ws.getRange2( "A2" ).setValue( "58" ); ws.getRange2( "A3" ).setValue( "11" ); ws.getRange2( "A4" ).setValue( "10" ); ws.getRange2( "A5" ).setValue( "x" ); ws.getRange2( "A6" ).setValue( "45.35" ); ws.getRange2( "A7" ).setValue( "17.56" ); ws.getRange2( "A8" ).setValue( "16.09" ); ws.getRange2( "B2" ).setValue( "35" ); ws.getRange2( "B3" ).setValue( "25" ); ws.getRange2( "B4" ).setValue( "23" ); ws.getRange2( "B5" ).setValue( "x" ); ws.getRange2( "B6" ).setValue( "47.65" ); ws.getRange2( "B7" ).setValue( "18.44" ); ws.getRange2( "B8" ).setValue( "16.91" ); oParser = new parserFormula( "CHISQ.TEST(A2:B4,A6:B8)", "A1", ws ); ok( oParser.parse(), "CHISQ.TEST(A2:B4,A6:B8)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0003082, "CHISQ.TEST(A2:B4,A6:B8)" ); } ); test( "Test: \"CHITEST\"", function () { ws.getRange2( "A2" ).setValue( "18.307" ); ws.getRange2( "A3" ).setValue( "10" ); oParser = new parserFormula( "CHIDIST(A2,A3)", "A1", ws ); ok( oParser.parse(), "CHIDIST(A2,A3)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0500006, "CHIDIST(A2,A3)" ); testArrayFormula2("CHIDIST", 2, 2); } ); test( "Test: \"GAUSS\"", function () { oParser = new parserFormula( "GAUSS(2)", "A1", ws ); ok( oParser.parse(), "GAUSS(2)" ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 0.47725, "GAUSS(2)" ); testArrayFormula2("GAUSS", 1, 1); } ); test( "Test: \"CHISQ.DIST.RT\"", function () { ws.getRange2( "A2" ).setValue( "18.307" ); ws.getRange2( "A3" ).setValue( "10" ); oParser = new parserFormula( "CHISQ.DIST.RT(A2,A3)", "A1", ws ); ok( oParser.parse(), "CHISQ.DIST.RT(A2,A3)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0500006, "CHISQ.DIST.RT(A2,A3)" ); testArrayFormula2("CHISQ.INV.RT", 2, 2); } ); test( "Test: \"CHISQ.INV\"", function () { oParser = new parserFormula( "CHISQ.INV(0.93,1)", "A1", ws ); ok( oParser.parse(), "CHISQ.INV(0.93,1)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 3.283020287, "CHISQ.INV(0.93,1)" ); oParser = new parserFormula( "CHISQ.INV(0.6,2)", "A1", ws ); ok( oParser.parse(), "CHISQ.INV(0.6,2)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 1.832581464, "CHISQ.INV(0.6,2)" ); testArrayFormula2("CHISQ.INV", 2, 2); } ); test( "Test: \"CHISQ.DIST\"", function () { oParser = new parserFormula( "CHISQ.DIST(0.5,1,TRUE)", "A1", ws ); ok( oParser.parse(), "CHISQ.DIST(0.5,1,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.52049988, "CHISQ.DIST(0.5,1,TRUE)" ); oParser = new parserFormula( "CHISQ.DIST(2,3,FALSE)", "A1", ws ); ok( oParser.parse(), "CHISQ.DIST(2,3,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.20755375, "CHISQ.DIST(2,3,FALSE)" ); testArrayFormula2("CHISQ.DIST", 3, 3); } ); test( "Test: \"CHIINV\"", function () { ws.getRange2( "A2" ).setValue( "0.050001" ); ws.getRange2( "A3" ).setValue( "10" ); oParser = new parserFormula( "CHIINV(A2,A3)", "A1", ws ); ok( oParser.parse(), "CHIINV(A2,A3)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 18.306973, "CHIINV(A2,A3)" ); testArrayFormula2("CHIINV", 2, 2); } ); test( "Test: \"CHISQ.INV.RT\"", function () { ws.getRange2( "A2" ).setValue( "0.050001" ); ws.getRange2( "A3" ).setValue( "10" ); oParser = new parserFormula( "CHISQ.INV.RT(A2,A3)", "A1", ws ); ok( oParser.parse(), "CHISQ.INV.RT(A2,A3)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 18.306973, "CHISQ.INV.RT(A2,A3)" ); testArrayFormula2("CHISQ.INV.RT", 2, 2); } ); test( "Test: \"CHOOSE\"", function () { ws.getRange2( "A2" ).setValue( "st" ); ws.getRange2( "A3" ).setValue( "2nd" ); ws.getRange2( "A4" ).setValue( "3rd" ); ws.getRange2( "A5" ).setValue( "Finished" ); ws.getRange2( "B2" ).setValue( "Nails" ); ws.getRange2( "B3" ).setValue( "Screws" ); ws.getRange2( "B4" ).setValue( "Nuts" ); ws.getRange2( "B5" ).setValue( "Bolts" ); oParser = new parserFormula( "CHOOSE(2,A2,A3,A4,A5)", "A1", ws ); ok( oParser.parse(), "CHOOSE(2,A2,A3,A4,A5)" ); strictEqual( oParser.calculate().getValue().getValue(), "2nd", "CHOOSE(2,A2,A3,A4,A5)" ); oParser = new parserFormula( "CHOOSE(4,B2,B3,B4,B5)", "A1", ws ); ok( oParser.parse(), "CHOOSE(4,B2,B3,B4,B5)" ); strictEqual( oParser.calculate().getValue().getValue(), "Bolts", "CHOOSE(4,B2,B3,B4,B5))" ); oParser = new parserFormula( 'CHOOSE(3,"Wide",115,"world",8)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "world" ); //функция возвращает ref //testArrayFormula2("CHOOSE", 2, 9); } ); test( "Test: \"BETA.INV\"", function () { ws.getRange2( "A2" ).setValue( "0.685470581" ); ws.getRange2( "A3" ).setValue( "8" ); ws.getRange2( "A4" ).setValue( "10" ); ws.getRange2( "A5" ).setValue( "1" ); ws.getRange2( "A6" ).setValue( "3" ); oParser = new parserFormula( "BETA.INV(A2,A3,A4,A5,A6)", "A1", ws ); ok( oParser.parse(), "BETA.INV(A2,A3,A4,A5,A6)" ); strictEqual( oParser.calculate().getValue().toFixed(1) - 0, 2, "BETA.INV(A2,A3,A4,A5,A6)" ); testArrayFormula2("BETA.INV", 3, 5); } ); test( "Test: \"BETAINV\"", function () { ws.getRange2( "A2" ).setValue( "0.685470581" ); ws.getRange2( "A3" ).setValue( "8" ); ws.getRange2( "A4" ).setValue( "10" ); ws.getRange2( "A5" ).setValue( "1" ); ws.getRange2( "A6" ).setValue( "3" ); oParser = new parserFormula( "BETAINV(A2,A3,A4,A5,A6)", "A1", ws ); ok( oParser.parse(), "BETAINV(A2,A3,A4,A5,A6)" ); strictEqual( oParser.calculate().getValue().toFixed(1) - 0, 2, "BETAINV(A2,A3,A4,A5,A6)" ); testArrayFormula2("BETAINV", 3, 5); } ); test( "Test: \"BETA.DIST\"", function () { ws.getRange2( "A2" ).setValue( "2" ); ws.getRange2( "A3" ).setValue( "8" ); ws.getRange2( "A4" ).setValue( "10" ); ws.getRange2( "A5" ).setValue( "1" ); ws.getRange2( "A6" ).setValue( "3" ); oParser = new parserFormula( "BETA.DIST(A2,A3,A4,TRUE,A5,A6)", "A1", ws ); ok( oParser.parse(), "BETA.DIST(A2,A3,A4,TRUE,A5,A6)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.6854706, "BETA.DIST(A2,A3,A4,TRUE,A5,A6)" ); oParser = new parserFormula( "BETA.DIST(A2,A3,A4,FALSE,A5,A6)", "A1", ws ); ok( oParser.parse(), "BETA.DIST(A2,A3,A4,FALSE,A5,A6)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 1.4837646, "BETA.DIST(A2,A3,A4,FALSE,A5,A6)" ); testArrayFormula2("BETA.DIST", 4, 6); } ); test( "Test: \"BETADIST\"", function () { ws.getRange2( "A2" ).setValue( "2" ); ws.getRange2( "A3" ).setValue( "8" ); ws.getRange2( "A4" ).setValue( "10" ); ws.getRange2( "A5" ).setValue( "1" ); ws.getRange2( "A6" ).setValue( "3" ); oParser = new parserFormula( "BETADIST(A2,A3,A4,A5,A6)", "A1", ws ); ok( oParser.parse(), "BETADIST(A2,A3,A4,A5,A6)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.6854706, "BETADIST(A2,A3,A4,A5,A6)" ); oParser = new parserFormula( "BETADIST(1,2,3,1,6)", "A1", ws ); ok( oParser.parse(), "BETADIST(1,2,3,1,6)" ); strictEqual( oParser.calculate().getValue(), 0, "BETADIST(1,2,3,1,6)" ); oParser = new parserFormula( "BETADIST(6,2,3,1,6)", "A1", ws ); ok( oParser.parse(), "BETADIST(6,2,3,1,6)" ); strictEqual( oParser.calculate().getValue(), 1, "BETADIST(6,2,3,1,6)" ); testArrayFormula2("BETADIST", 3, 5); } ); test( "Test: \"BESSELJ\"", function () { oParser = new parserFormula( "BESSELJ(1.9, 2)", "A1", ws ); ok( oParser.parse(), "BESSELJ(1.9, 2)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.329925728, "BESSELJ(1.9, 2)" ); oParser = new parserFormula( "BESSELJ(1.9, 2.4)", "A1", ws ); ok( oParser.parse(), "BESSELJ(1.9, 2.4)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.329925728, "BESSELJ(1.9, 2.4)" ); oParser = new parserFormula( "BESSELJ(-1.9, 2.4)", "A1", ws ); ok( oParser.parse(), "BESSELJ(-1.9, 2.4)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.329925728, "BESSELJ(-1.9, 2.4)" ); oParser = new parserFormula( "BESSELJ(-1.9, -2.4)", "A1", ws ); ok( oParser.parse(), "BESSELJ(-1.9, -2.4)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("BESSELJ", 2, 2, true); } ); test( "Test: \"BESSELK\"", function () { oParser = new parserFormula( "BESSELK(1.5, 1)", "A1", ws ); ok( oParser.parse(), "BESSELK(1.5, 1)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.277387804, "BESSELK(1.5, 1)" ); oParser = new parserFormula( "BESSELK(1, 3)", "A1", ws ); ok( oParser.parse(), "BESSELK(1, 3)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 7.10126281, "BESSELK(1, 3)" ); oParser = new parserFormula( "BESSELK(-1.123,2)", "A1", ws ); ok( oParser.parse(), "BESSELK(-1.123,2)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BESSELK(1,-2)", "A1", ws ); ok( oParser.parse(), "BESSELK(1,-2)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("BESSELK", 2, 2, true); } ); test( "Test: \"BESSELY\"", function () { oParser = new parserFormula( "BESSELY(2.5, 1)", "A1", ws ); ok( oParser.parse(), "BESSELY(2.5, 1)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.1459181, "BESSELY(2.5, 1)" ); oParser = new parserFormula( "BESSELY(1,-2)", "A1", ws ); ok( oParser.parse(), "BESSELY(1,-2)" ); strictEqual( oParser.calculate().getValue(), "#NUM!", "BESSELY(1,-2)" ); oParser = new parserFormula( "BESSELY(-1,2)", "A1", ws ); ok( oParser.parse(), "BESSELY(-1,2)" ); strictEqual( oParser.calculate().getValue(), "#NUM!", "BESSELY(-1,2)" ); testArrayFormula2("BESSELY", 2, 2, true) } ); test( "Test: \"BESSELI\"", function () { //есть различия excel в некоторых формулах(неточности в 7 цифре после точки) oParser = new parserFormula( "BESSELI(1.5, 1)", "A1", ws ); ok( oParser.parse(), "BESSELI(1.5, 1)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.981666, "BESSELI(1.5, 1)" ); oParser = new parserFormula( "BESSELI(1,2)", "A1", ws ); ok( oParser.parse(), "BESSELI(1,2)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.135748, "BESSELI(1,2)" ); oParser = new parserFormula( "BESSELI(1,-2)", "A1", ws ); ok( oParser.parse(), "BESSELI(1,-2)" ); strictEqual( oParser.calculate().getValue(), "#NUM!", "BESSELI(1,-2)" ); oParser = new parserFormula( "BESSELI(-1,2)", "A1", ws ); ok( oParser.parse(), "BESSELI(-1,2)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.135748, "BESSELI(-1,2)" ); testArrayFormula2("BESSELI", 2, 2, true) } ); test( "Test: \"GAMMA.INV\"", function () { ws.getRange2( "A2" ).setValue( "0.068094" ); ws.getRange2( "A3" ).setValue( "9" ); ws.getRange2( "A4" ).setValue( "2" ); oParser = new parserFormula( "GAMMA.INV(A2,A3,A4)", "A1", ws ); ok( oParser.parse(), "GAMMA.INV(A2,A3,A4)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 10.0000112, "GAMMA.INV(A2,A3,A4)" ); testArrayFormula2("GAMMA.INV", 3, 3); } ); test( "Test: \"GAMMAINV\"", function () { ws.getRange2( "A2" ).setValue( "0.068094" ); ws.getRange2( "A3" ).setValue( "9" ); ws.getRange2( "A4" ).setValue( "2" ); oParser = new parserFormula( "GAMMAINV(A2,A3,A4)", "A1", ws ); ok( oParser.parse(), "GAMMAINV(A2,A3,A4)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 10.0000112, "GAMMAINV(A2,A3,A4)" ); } ); test( "Test: \"SUM(1,2,3)\"", function () { oParser = new parserFormula( 'SUM(1,2,3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 + 2 + 3 ); testArrayFormula2("SUM", 1, 8, null, true); } ); test( "Test: \"\"s\"&5\"", function () { oParser = new parserFormula( "\"s\"&5", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "s5" ); } ); test( "Test: \"String+Number\"", function () { oParser = new parserFormula( "1+\"099\"", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 100 ); ws.getRange2( "A1469" ).setValue( "'099" ); ws.getRange2( "A1470" ).setValue( "\"099\"" ); oParser = new parserFormula( "1+A1469", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 100 ); oParser = new parserFormula( "1+A1470", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); } ); test( "Test: \"POWER(2,8)\"", function () { oParser = new parserFormula( "POWER(2,8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.pow( 2, 8 ) ); } ); test( "Test: \"POWER(0,-3)\"", function () { oParser = new parserFormula( "POWER(0,-3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); testArrayFormula2("POWER", 2, 2); } ); test( "Test: \"ISNA(A1)\"", function () { ws.getRange2( "A1" ).setValue( "#N/A" ); oParser = new parserFormula( "ISNA(A1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); testArrayFormula2("ISNA",1,1); } ); test( "Test: \"ISNONTEXT\"", function () { oParser = new parserFormula( 'ISNONTEXT("123")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE" ); testArrayFormula2("ISNONTEXT",1,1); } ); test( "Test: \"ISNUMBER\"", function () { ws.getRange2( "A1" ).setValue( "123" ); oParser = new parserFormula( 'ISNUMBER(4)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( 'ISNUMBER(A1)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); testArrayFormula2("ISNUMBER",1,1); } ); test( "Test: \"ISODD\"", function () { oParser = new parserFormula( 'ISODD(-1)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( 'ISODD(2.5)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( 'ISODD(5)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); testArrayFormula2("ISODD",1,1,true); } ); test( "Test: \"ROUND\"", function () { oParser = new parserFormula( "ROUND(2.15, 1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2.2 ); oParser = new parserFormula( "ROUND(2.149, 1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2.1 ); oParser = new parserFormula( "ROUND(-1.475, 2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1.48 ); oParser = new parserFormula( "ROUND(21.5, -1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 20 ); oParser = new parserFormula( "ROUND(626.3,-3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1000 ); oParser = new parserFormula( "ROUND(1.98,-1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "ROUND(-50.55,-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -100 ); testArrayFormula2("ROUND", 2, 2) } ); test( "Test: \"ROUNDUP(31415.92654,-2)\"", function () { oParser = new parserFormula( "ROUNDUP(31415.92654,-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 31500 ); } ); test( "Test: \"ROUNDUP(3.2,0)\"", function () { oParser = new parserFormula( "ROUNDUP(3.2,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); } ); test( "Test: \"ROUNDUP(-3.14159,1)\"", function () { oParser = new parserFormula( "ROUNDUP(-3.14159,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -3.2 ); } ); test( "Test: \"ROUNDUP(3.14159,3)\"", function () { oParser = new parserFormula( "ROUNDUP(3.14159,3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3.142 ); testArrayFormula2("ROUNDUP", 2, 2) } ); test( "Test: \"ROUNDUP\"", function () { oParser = new parserFormula( "ROUNDUP(2.1123,4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(4) - 0, 2.1123 ); oParser = new parserFormula( "ROUNDUP(2,4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "ROUNDUP(2,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "ROUNDUP(2.1123,-1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( "ROUNDUP(2.1123,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); } ); test( "Test: \"ROUNDDOWN(31415.92654,-2)\"", function () { oParser = new parserFormula( "ROUNDDOWN(31415.92654,-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 31400 ); } ); test( "Test: \"ROUNDDOWN(-3.14159,1)\"", function () { oParser = new parserFormula( "ROUNDDOWN(-3.14159,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -3.1 ); } ); test( "Test: \"ROUNDDOWN(3.14159,3)\"", function () { oParser = new parserFormula( "ROUNDDOWN(3.14159,3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3.141 ); } ); test( "Test: \"ROUNDDOWN(3.2,0)\"", function () { oParser = new parserFormula( "ROUNDDOWN(3.2,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); testArrayFormula2("ROUNDDOWN", 2, 2) } ); test( "Test: \"MROUND\"", function () { var multiple;//должен равняться значению второго аргумента function mroundHelper( num ) { var multiplier = Math.pow( 10, Math.floor( Math.log( Math.abs( num ) ) / Math.log( 10 ) ) - AscCommonExcel.cExcelSignificantDigits + 1 ); var nolpiat = 0.5 * (num > 0 ? 1 : num < 0 ? -1 : 0) * multiplier; var y = (num + nolpiat) / multiplier; y = y / Math.abs( y ) * Math.floor( Math.abs( y ) ) var x = y * multiplier / multiple // var x = number / multiple; var nolpiat = 5 * (x / Math.abs( x )) * Math.pow( 10, Math.floor( Math.log( Math.abs( x ) ) / Math.log( 10 ) ) - AscCommonExcel.cExcelSignificantDigits ); x = x + nolpiat; x = x | x; return x * multiple; } oParser = new parserFormula( "MROUND(10,3)", "A1", ws ); ok( oParser.parse() ); multiple = 3; strictEqual( oParser.calculate().getValue(), mroundHelper( 10 + 3 / 2 ) ); oParser = new parserFormula( "MROUND(-10,-3)", "A1", ws ); ok( oParser.parse() ); multiple = -3; strictEqual( oParser.calculate().getValue(), mroundHelper( -10 + -3 / 2 ) ); oParser = new parserFormula( "MROUND(1.3,0.2)", "A1", ws ); ok( oParser.parse() ); multiple = 0.2; strictEqual( oParser.calculate().getValue(), mroundHelper( 1.3 + 0.2 / 2 ) ); testArrayFormula2("MROUND", 2, 2, true); } ); test( "Test: \"T(\"HELLO\")\"", function () { oParser = new parserFormula( "T(\"HELLO\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "HELLO" ); } ); test( "Test: \"MMULT\"", function () { ws.getRange2( "AAA102" ).setValue( "4" ); ws.getRange2( "AAA103" ).setValue( "5" ); ws.getRange2( "AAA104" ).setValue( "6" ); ws.getRange2( "AAA105" ).setValue( "7" ); ws.getRange2( "AAB102" ).setValue( "1" ); ws.getRange2( "AAB103" ).setValue( "2" ); ws.getRange2( "AAB104" ).setValue( "3" ); ws.getRange2( "AAB105" ).setValue( "2" ); ws.getRange2( "AAC102" ).setValue( "4" ); ws.getRange2( "AAC103" ).setValue( "5" ); ws.getRange2( "AAC104" ).setValue( "6" ); ws.getRange2( "AAC105" ).setValue( "3" ); ws.getRange2( "AAD102" ).setValue( "7" ); ws.getRange2( "AAD103" ).setValue( "8" ); ws.getRange2( "AAD104" ).setValue( "9" ); ws.getRange2( "AAD105" ).setValue( "4" ); ws.getRange2( "AAF102" ).setValue( "1" ); ws.getRange2( "AAF103" ).setValue( "2" ); ws.getRange2( "AAF104" ).setValue( "3" ); ws.getRange2( "AAF105" ).setValue( "6" ); ws.getRange2( "AAG102" ).setValue( "2" ); ws.getRange2( "AAG103" ).setValue( "3" ); ws.getRange2( "AAG104" ).setValue( "4" ); ws.getRange2( "AAG105" ).setValue( "5" ); oParser = new parserFormula( "MMULT(AAC102,AAF104)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 12 ); oParser = new parserFormula( "MMULT(AAA102:AAD105,AAF104)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "MMULT(AAC102,AAF104)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 12 ); oParser = new parserFormula( "MMULT(AAA102:AAD105,AAF102:AAG105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 60 ); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue(), 62 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 72 ); strictEqual( oParser.calculate().getElementRowCol(1,1).getValue(), 76 ); oParser = new parserFormula( "MMULT(AAA102:AAD105,AAF102:AAF105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 60 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 72 ); oParser = new parserFormula( "MMULT(AAA102:AAD105,AAF102:AAF105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 60 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 72 ); oParser = new parserFormula( "MMULT(AAA102:AAD105,AAF102:AAF104)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "MMULT(AAA102:AAD105,AAK110:AAN110)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "MMULT(AAA102:AAD105,AAA102:AAD105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 94 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 116 ); strictEqual( oParser.calculate().getElementRowCol(2,0).getValue(), 138 ); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue(), 32 ); strictEqual( oParser.calculate().getElementRowCol(1,1).getValue(), 40 ); strictEqual( oParser.calculate().getElementRowCol(2,1).getValue(), 48 ); oParser = new parserFormula( "MMULT(AAF102:AAF105,AAG102:AAG105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "MMULT(AAF102:AAF105,AAA102:AAD102)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 4 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 8 ); strictEqual( oParser.calculate().getElementRowCol(2,0).getValue(), 12 ); } ); test( "Test: \"T(123)\"", function () { oParser = new parserFormula( "T(123)", "A1", ws ); ok( oParser.parse() ); ok( !oParser.calculate().getValue(), "123" ); } ); test( "Test: YEAR", function () { oParser = new parserFormula( "YEAR(2013)", "A1", ws ); ok( oParser.parse() ); if ( AscCommon.bDate1904 ) strictEqual( oParser.calculate().getValue(), 1909 ); else strictEqual( oParser.calculate().getValue(), 1905 ); testArrayFormula2("YEAR",1,1); } ); test( "Test: DAY", function () { oParser = new parserFormula( "DAY(2013)", "A1", ws ); ok( oParser.parse() ); if ( AscCommon.bDate1904 ) strictEqual( oParser.calculate().getValue(), 6 ); else strictEqual( oParser.calculate().getValue(), 5 ); testArrayFormula2("DAY", 1, 1); } ); test( "Test: DAYS", function () { ws.getRange2( "A2" ).setValue( "12/31/2011" ); ws.getRange2( "A3" ).setValue( "1/1/2011" ); oParser = new parserFormula( 'DAYS("3/15/11","2/1/11")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 42 ); oParser = new parserFormula( "DAYS(A2,A3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 364 ); oParser = new parserFormula( "DAYS(A2,A3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 364 ); oParser = new parserFormula( 'DAYS("2008-03-03","2008-03-01")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( 'DAYS("2008-03-01","2008-03-03")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -2 ); testArrayFormula2("DAYS", 2, 2); } ); test( "Test: DAY 2", function () { oParser = new parserFormula( "DAY(\"20 may 2045\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 20 ); } ); test( "Test: MONTH #1", function () { oParser = new parserFormula( "MONTH(2013)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); } ); test( "Test: MONTH #2", function () { oParser = new parserFormula( "MONTH(DATE(2013,2,2))", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); } ); test( "Test: MONTH #3", function () { oParser = new parserFormula( "MONTH(NOW())", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), new cDate().getUTCMonth() + 1 ); testArrayFormula2("MONTH",1,1); } ); test( "Test: \"10-3\"", function () { oParser = new parserFormula( "10-3", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); } ); test( "Test: \"SUM\"", function () { ws.getRange2( "S5" ).setValue( "1" ); ws.getRange2( "S6" ).setValue( numDivFact(-1, 2) ); ws.getRange2( "S7" ).setValue( numDivFact(1, 4) ); ws.getRange2( "S8" ).setValue( numDivFact(-1, 6) ); oParser = new parserFormula( "SUM(S5:S8)", "A1", ws ); ok( oParser.parse() ); // strictEqual( oParser.calculate().getValue(), 1-1/Math.fact(2)+1/Math.fact(4)-1/Math.fact(6) ); ok( Math.abs( oParser.calculate().getValue() - (1 - 1 / Math.fact( 2 ) + 1 / Math.fact( 4 ) - 1 / Math.fact( 6 )) ) < dif ); } ); test( "Test: \"MAX\"", function () { ws.getRange2( "S5" ).setValue( "1" ); ws.getRange2( "S6" ).setValue( numDivFact(-1, 2) ); ws.getRange2( "S7" ).setValue( numDivFact(1, 4) ); ws.getRange2( "S8" ).setValue( numDivFact(-1, 6) ); oParser = new parserFormula( "MAX(S5:S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); ws.getRange2( "S5" ).setValue( "#DIV/0!" ); ws.getRange2( "S6" ).setValue( "TRUE" ); ws.getRange2( "S7" ).setValue( "qwe" ); ws.getRange2( "S8" ).setValue( "" ); ws.getRange2( "S9" ).setValue( "-1" ); oParser = new parserFormula( "MAX(S5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MAX(S6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MAX(S7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MAX(S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MAX(S5:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MAX(S6:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1 ); oParser = new parserFormula( "MAX(-1, TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); testArrayFormula2("MAX", 1, 8, null, true); } ); test( "Test: \"MAXA\"", function () { ws.getRange2( "S5" ).setValue( "1" ); ws.getRange2( "S6" ).setValue( numDivFact(-1, 2) ); ws.getRange2( "S7" ).setValue( numDivFact(1, 4) ); ws.getRange2( "S8" ).setValue( numDivFact(-1, 6) ); oParser = new parserFormula( "MAXA(S5:S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); ws.getRange2( "S5" ).setValue( "#DIV/0!" ); ws.getRange2( "S6" ).setValue( "TRUE" ); ws.getRange2( "S7" ).setValue( "qwe" ); ws.getRange2( "S8" ).setValue( "" ); ws.getRange2( "S9" ).setValue( "-1" ); oParser = new parserFormula( "MAXA(S5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MAXA(S6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "MAXA(S7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MAXA(S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MAXA(S5:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MAXA(S6:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "MAXA(-1, TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); testArrayFormula2("MAXA", 1, 8, null, true); } ); test( "Test: \"MIN\"", function () { ws.getRange2( "S5" ).setValue( "1" ); ws.getRange2( "S6" ).setValue( numDivFact(-1, 2) ); ws.getRange2( "S7" ).setValue( numDivFact(1, 4) ); ws.getRange2( "S8" ).setValue( numDivFact(-1, 6) ); oParser = new parserFormula( "MIN(S5:S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1 / Math.fact( 2 ) ); ws.getRange2( "S5" ).setValue( "#DIV/0!" ); ws.getRange2( "S6" ).setValue( "TRUE" ); ws.getRange2( "S7" ).setValue( "qwe" ); ws.getRange2( "S8" ).setValue( "" ); ws.getRange2( "S9" ).setValue( "2" ); oParser = new parserFormula( "MIN(S5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MIN(S6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MIN(S7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MIN(S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MIN(S5:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MIN(S6:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "MIN(2, TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); testArrayFormula2("min", 1, 8, null, true); } ); test( "Test: \"MINA\"", function () { ws.getRange2( "S5" ).setValue( "1" ); ws.getRange2( "S6" ).setValue( numDivFact(-1, 2) ); ws.getRange2( "S7" ).setValue( numDivFact(1, 4) ); ws.getRange2( "S8" ).setValue( numDivFact(-1, 6) ); oParser = new parserFormula( "MINA(S5:S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1 / Math.fact( 2 ) ); ws.getRange2( "S5" ).setValue( "#DIV/0!" ); ws.getRange2( "S6" ).setValue( "TRUE" ); ws.getRange2( "S7" ).setValue( "qwe" ); ws.getRange2( "S8" ).setValue( "" ); ws.getRange2( "S9" ).setValue( "2" ); oParser = new parserFormula( "MINA(S5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MINA(S6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "MINA(S7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MINA(S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MINA(S5:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MINA(S6:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MINA(2, TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); testArrayFormula2("mina", 1, 8, null, true); } ); test( "Test: SUM(S7:S9,{1,2,3})", function () { ws.getRange2( "S7" ).setValue( "1" ); ws.getRange2( "S8" ).setValue( "2" ); ws.getRange2( "S9" ).setValue( "3" ); oParser = new parserFormula( "SUM(S7:S9,{1,2,3})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 12 ); } ); test( "Test: ISREF", function () { oParser = new parserFormula( "ISREF(G0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE" ); testArrayFormula2("ISREF",1,1,null,true); } ); test( "Test: ISTEXT", function () { ws.getRange2( "S7" ).setValue( "test" ); oParser = new parserFormula( "ISTEXT(S7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); testArrayFormula2("ISTEXT",1,1); } ); test( "Test: MOD", function () { oParser = new parserFormula( "MOD(7,3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "MOD(-10,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MOD(-9,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "MOD(-8,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "MOD(-7,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "MOD(-6,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "MOD(-5,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MOD(10,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MOD(9,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "MOD(8,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "MOD(15,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MOD(15,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); testArrayFormula2("MOD", 2, 2); } ); test( "Test: rename sheet #1", function () { wb.dependencyFormulas.unlockRecal(); ws.getRange2( "S95" ).setValue( "2" ); ws.getRange2( "S100" ).setValue( "=" + wb.getWorksheet( 0 ).getName() + "!S95" ); ws.setName( "SheetTmp" ); strictEqual( ws.getCell2( "S100" ).getFormula(), ws.getName() + "!S95" ); wb.dependencyFormulas.lockRecal(); } ); test( "Test: wrong ref", function () { oParser = new parserFormula( "1+XXX1", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NAME?" ); } ); test( "Test: \"CODE\"", function () { oParser = new parserFormula( "CODE(\"abc\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 97 ); oParser = new parserFormula( "CODE(TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 84 ); testArrayFormula2("CODE", 1, 1); } ); test( "Test: \"CHAR\"", function () { oParser = new parserFormula( "CHAR(97)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "a" ); testArrayFormula2("CHAR", 1, 1); } ); test( "Test: \"CHAR(CODE())\"", function () { oParser = new parserFormula( "CHAR(CODE(\"A\"))", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "A" ); } ); test( "Test: \"PROPER\"", function () { oParser = new parserFormula( "PROPER(\"2-cent's worth\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "2-Cent'S Worth" ); oParser = new parserFormula( "PROPER(\"76BudGet\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "76Budget" ); oParser = new parserFormula( "PROPER(\"this is a TITLE\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "This Is A Title" ); oParser = new parserFormula( 'PROPER(TRUE)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "True" ); testArrayFormula2("PROPER", 1, 1); } ); test( "Test: \"GCD\"", function () { oParser = new parserFormula( "GCD(10,100,50)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( "GCD(24.6,36.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 12 ); oParser = new parserFormula( "GCD(-1,39,52)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("GCD", 1, 8, null, true); } ); test( "Test: \"FIXED\"", function () { oParser = new parserFormula( "FIXED(1234567,-3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "1,235,000" ); oParser = new parserFormula( "FIXED(.555555,10)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "0.5555550000" ); oParser = new parserFormula( "FIXED(1234567.555555,4,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "1234567.5556" ); oParser = new parserFormula( "FIXED(1234567)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "1,234,567.00" ); testArrayFormula2("FIXED", 2, 3); } ); test( "Test: \"REPLACE\"", function () { oParser = new parserFormula( "REPLACE(\"abcdefghijk\",3,4,\"XY\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "abXYghijk" ); oParser = new parserFormula( "REPLACE(\"abcdefghijk\",3,1,\"12345\")", "B2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "ab12345defghijk" ); oParser = new parserFormula( "REPLACE(\"abcdefghijk\",15,4,\"XY\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "abcdefghijkXY" ); testArrayFormula2("REPLACE", 4, 4); } ); test( "Test: \"SEARCH\"", function () { oParser = new parserFormula( "SEARCH(\"~*\",\"abc*dEF\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "SEARCH(\"~\",\"abc~dEF\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "SEARCH(\"de\",\"abcdEF\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "SEARCH(\"?c*e\",\"abcdEF\")", "B2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "SEARCH(\"de\",\"dEFabcdEF\",3)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( "SEARCH(\"de\",\"dEFabcdEF\",30)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("SEARCH", 2, 3); } ); test( "Test: \"SUBSTITUTE\"", function () { oParser = new parserFormula( "SUBSTITUTE(\"abcaAabca\",\"a\",\"xx\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "xxbcxxAxxbcxx" ); oParser = new parserFormula( "SUBSTITUTE(\"abcaaabca\",\"a\",\"xx\")", "B2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "xxbcxxxxxxbcxx" ); oParser = new parserFormula( "SUBSTITUTE(\"abcaaabca\",\"a\",\"\",10)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "bcbc" ); oParser = new parserFormula( "SUBSTITUTE(\"abcaaabca\",\"a\",\"xx\",3)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "abcaxxabca" ); testArrayFormula2("SUBSTITUTE", 3, 4); } ); test( "Test: \"SHEET\"", function () { oParser = new parserFormula( "SHEET(Hi_Temps)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NAME?" ); testArrayFormula2("SHEET", 1, 1, null, true); } ); test( "Test: \"SHEETS\"", function () { oParser = new parserFormula( "SHEETS(Hi_Temps)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NAME?" ); oParser = new parserFormula( "SHEETS()", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); testArrayFormula2("SHEETS", 1, 1, null, true); } ); test( "Test: \"TRIM\"", function () { oParser = new parserFormula( "TRIM(\" abc def \")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "abc def" ); oParser = new parserFormula( "TRIM(\" First Quarter Earnings \")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "First Quarter Earnings" ); testArrayFormula2("TRIM", 1, 1); } ); test( "Test: \"TRIMMEAN\"", function () { ws.getRange2( "A2" ).setValue( "4" ); ws.getRange2( "A3" ).setValue( "5" ); ws.getRange2( "A4" ).setValue( "6" ); ws.getRange2( "A5" ).setValue( "7" ); ws.getRange2( "A6" ).setValue( "2" ); ws.getRange2( "A7" ).setValue( "3" ); ws.getRange2( "A8" ).setValue( "4" ); ws.getRange2( "A9" ).setValue( "5" ); ws.getRange2( "A10" ).setValue( "1" ); ws.getRange2( "A11" ).setValue( "2" ); ws.getRange2( "A12" ).setValue( "3" ); oParser = new parserFormula( "TRIMMEAN(A2:A12,0.2)", "A1", ws ); ok( oParser.parse(), "TRIMMEAN(A2:A12,0.2)" ); strictEqual( oParser.calculate().getValue().toFixed(3) - 0, 3.778, "TRIMMEAN(A2:A12,0.2)" ); //TODO нужна другая функция для тестирования //testArrayFormula2("TRIMMEAN", 2, 2) } ); test( "Test: \"DOLLAR\"", function () { oParser = new parserFormula( "DOLLAR(1234.567)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "$1,234.57" ); oParser = new parserFormula( "DOLLAR(1234.567,-2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "$1,200" ); oParser = new parserFormula( "DOLLAR(-1234.567,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "($1,234.5670)" ); testArrayFormula2("DOLLAR", 2, 2); } ); test( "Test: \"EXACT\"", function () { ws.getRange2( "A2" ).setValue( "word" ); ws.getRange2( "A3" ).setValue( "Word" ); ws.getRange2( "A4" ).setValue( "w ord" ); ws.getRange2( "B2" ).setValue( "word" ); ws.getRange2( "B3" ).setValue( "word" ); ws.getRange2( "B4" ).setValue( "word" ); oParser = new parserFormula( "EXACT(A2,B2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( "EXACT(A3,B3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( "EXACT(A4,B4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( "EXACT(TRUE,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( 'EXACT("TRUE",TRUE)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( 'EXACT("TRUE","TRUE")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( 'EXACT("true",TRUE)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE" ); testArrayFormula2("EXACT", 2, 2); } ); test( "Test: \"LEFT\"", function () { ws.getRange2( "A2" ).setValue( "Sale Price" ); ws.getRange2( "A3" ).setValue( "Sweden" ); oParser = new parserFormula( "LEFT(A2,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Sale" ); oParser = new parserFormula( "LEFT(A3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "S" ); testArrayFormula2("LEFT", 1, 2); } ); test( "Test: \"LEN\"", function () { ws.getRange2( "A201" ).setValue( "Phoenix, AZ" ); ws.getRange2( "A202" ).setValue( "" ); ws.getRange2( "A203" ).setValue( " One " ); oParser = new parserFormula( "LEN(A201)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 11 ); oParser = new parserFormula( "LEN(A202)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "LEN(A203)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 11 ); oParser = new parserFormula( 'LEN(TRUE)', "A2", ws ); ok( oParser.parse(), 'LEN(TRUE)' ); strictEqual( oParser.calculate().getValue(), 4, 'LEN(TRUE)'); testArrayFormula2("LEN", 1, 1); } ); test( "Test: \"REPT\"", function () { oParser = new parserFormula( 'REPT("*-", 3)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "*-*-*-" ); oParser = new parserFormula( 'REPT("-",10)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "----------" ); testArrayFormula2("REPT", 2, 2); } ); test( "Test: \"RIGHT\"", function () { ws.getRange2( "A2" ).setValue( "Sale Price" ); ws.getRange2( "A3" ).setValue( "Stock Number" ); oParser = new parserFormula( "RIGHT(A2,5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Price" ); oParser = new parserFormula( "RIGHT(A3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "r" ); testArrayFormula2("RIGHT", 1, 2); } ); test( "Test: \"VALUE\"", function () { oParser = new parserFormula( "VALUE(\"123.456\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 123.456 ); oParser = new parserFormula( "VALUE(\"$1,000\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1000 ); oParser = new parserFormula( "VALUE(\"23-Mar-2002\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 37338 ); oParser = new parserFormula( "VALUE(\"03-26-2006\")", "A2", ws ); ok( oParser.parse() ); if ( AscCommon.bDate1904 ) strictEqual( oParser.calculate().getValue(), 37340 ); else strictEqual( oParser.calculate().getValue(), 38802 ); oParser = new parserFormula( "VALUE(\"16:48:00\")-VALUE(\"12:17:12\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), AscCommon.g_oFormatParser.parse( "16:48:00" ).value - AscCommon.g_oFormatParser.parse( "12:17:12" ).value ); testArrayFormula2("value", 1, 1); } ); test( "Test: \"DATE\"", function () { testArrayFormula2("DATE", 3, 3); } ); test( "Test: \"DATEVALUE\"", function () { oParser = new parserFormula( "DATEVALUE(\"10-10-2010 10:26\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 40461 ); oParser = new parserFormula( "DATEVALUE(\"10-10-2010 10:26\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 40461 ); tmp = ws.getRange2( "A7" ); tmp.setNumFormat('@'); tmp.setValue( "3-Mar" ); oParser = new parserFormula( "DATEVALUE(A7)", "A2", ws ); ok( oParser.parse() ); var d = new cDate(); d.setUTCMonth(2); d.setUTCDate(3); strictEqual( oParser.calculate().getValue(), d.getExcelDate() ); oParser = new parserFormula( "DATEVALUE(\"$1,000\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "DATEVALUE(\"23-Mar-2002\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 37338 ); oParser = new parserFormula( "DATEVALUE(\"03-26-2006\")", "A2", ws ); ok( oParser.parse() ); if ( AscCommon.bDate1904 ) strictEqual( oParser.calculate().getValue(), 37340 ); else strictEqual( oParser.calculate().getValue(), 38802 ); testArrayFormula("DATEVALUE"); } ); test( "Test: \"EDATE\"", function () { if ( !AscCommon.bDate1904 ) { oParser = new parserFormula( "EDATE(DATE(2006,1,31),5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38898 ); oParser = new parserFormula( "EDATE(DATE(2004,2,29),12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38411 ); ws.getRange2( "A7" ).setValue( "02-28-2004" ); oParser = new parserFormula( "EDATE(A7,12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38411 ); oParser = new parserFormula( "EDATE(DATE(2004,1,15),-23)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 37302 ); } else { oParser = new parserFormula( "EDATE(DATE(2006,1,31),5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 37436 ); oParser = new parserFormula( "EDATE(DATE(2004,2,29),12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 36949 ); ws.getRange2( "A7" ).setValue( "02-28-2004" ); oParser = new parserFormula( "EDATE(A7,12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 36949 ); oParser = new parserFormula( "EDATE(DATE(2004,1,15),-23)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 35840 ); } testArrayFormula2("EDATE", 2, 2, true); } ); test( "Test: \"EOMONTH\"", function () { if ( !AscCommon.bDate1904 ) { oParser = new parserFormula( "EOMONTH(DATE(2006,1,31),5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38898 ); oParser = new parserFormula( "EOMONTH(DATE(2004,2,29),12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38411 ); ws.getRange2( "A7" ).setValue( "02-28-2004" ); oParser = new parserFormula( "EOMONTH(A7,12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38411 ); oParser = new parserFormula( "EOMONTH(DATE(2004,1,15),-23)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 37315 ); } else { oParser = new parserFormula( "EOMONTH(DATE(2006,1,31),5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 37436 ); oParser = new parserFormula( "EOMONTH(DATE(2004,2,29),12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 36949 ); ws.getRange2( "A7" ).setValue( "02-28-2004" ); oParser = new parserFormula( "EOMONTH(A7,12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 36949 ); oParser = new parserFormula( "EOMONTH(DATE(2004,1,15),-23)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 35853 ); } testArrayFormula2("EOMONTH", 2, 2, true); } ); test( "Test: \"EVEN\"", function () { oParser = new parserFormula( "EVEN(1.5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "EVEN(3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "EVEN(2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "EVEN(-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -2 ); testArrayFormula("EVEN"); } ); test( "Test: \"NETWORKDAYS\"", function () { oParser = new parserFormula( "NETWORKDAYS(DATE(2006,1,1),DATE(2006,1,31))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 22 ); oParser = new parserFormula( "NETWORKDAYS(DATE(2006,1,31),DATE(2006,1,1))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -22 ); oParser = new parserFormula( "NETWORKDAYS(DATE(2006,1,1),DATE(2006,2,1),{\"01-02-2006\",\"01-16-2006\"})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 21 ); testArrayFormula2("NETWORKDAYS", 2, 3, true); } ); test( "Test: \"NETWORKDAYS.INTL\"", function () { var formulaStr = "NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,1,31))"; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), 22, formulaStr ); formulaStr = "NETWORKDAYS.INTL(DATE(2006,2,28),DATE(2006,1,31))"; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), -21, formulaStr ); formulaStr = 'NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,2,1),7,{"1/2/2006","1/16/2006"})'; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), 22, formulaStr ); formulaStr = 'NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,2,1),17,{"1/2/2006","1/16/2006"})'; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), 26, formulaStr ); formulaStr = 'NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,2,1),"1111111",{"1/2/2006","1/16/2006"})'; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), 0, formulaStr ); formulaStr = 'NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,2,1),"0010001",{"1/2/2006","1/16/2006"})'; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), 20, formulaStr ); formulaStr = 'NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,2,1),"0000000",{"1/2/2006","1/16/2006"})'; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), 30, formulaStr ); formulaStr = 'NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,2,1),"19",{"1/2/2006","1/16/2006"})'; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), "#VALUE!", formulaStr ); formulaStr = 'NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,2,1),19,{"1/2/2006","1/16/2006"})'; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), "#NUM!", formulaStr ); } ); test( "Test: \"N\"", function () { ws.getRange2( "A2" ).setValue( "7" ); ws.getRange2( "A3" ).setValue( "Even" ); ws.getRange2( "A4" ).setValue( "TRUE" ); ws.getRange2( "A5" ).setValue( "4/17/2011" ); oParser = new parserFormula( "N(A2)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( "N(A3)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "N(A4)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "N(A5)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 40650 ); oParser = new parserFormula( 'N("7")', "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); //TODO нужна другая функция для тестирования //testArrayFormula2("N", 1, 1); } ); test( "Test: \"SUMIF\"", function () { ws.getRange2( "A2" ).setValue( "100000" ); ws.getRange2( "A3" ).setValue( "200000" ); ws.getRange2( "A4" ).setValue( "300000" ); ws.getRange2( "A5" ).setValue( "400000" ); ws.getRange2( "B2" ).setValue( "7000" ); ws.getRange2( "B3" ).setValue( "14000" ); ws.getRange2( "B4" ).setValue( "21000" ); ws.getRange2( "B5" ).setValue( "28000" ); ws.getRange2( "C2" ).setValue( "250000" ); oParser = new parserFormula( "SUMIF(A2:A5,\">160000\",B2:B5)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 63000 ); oParser = new parserFormula( "SUMIF(A2:A5,\">160000\")", "A8", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 900000 ); oParser = new parserFormula( "SUMIF(A2:A5,300000,B2:B5)", "A9", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 21000 ); oParser = new parserFormula( "SUMIF(A2:A5,\">\" & C2,B2:B5)", "A10", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 49000 ); oParser = new parserFormula( "SUMIF(A2,\">160000\",B2:B5)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "SUMIF(A3,\">160000\",B2:B5)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7000 ); oParser = new parserFormula( "SUMIF(A4,\">160000\",B4:B5)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 21000 ); oParser = new parserFormula( "SUMIF(A4,\">160000\")", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 300000); ws.getRange2( "A12" ).setValue( "Vegetables" ); ws.getRange2( "A13" ).setValue( "Vegetables" ); ws.getRange2( "A14" ).setValue( "Fruits" ); ws.getRange2( "A15" ).setValue( "" ); ws.getRange2( "A16" ).setValue( "Vegetables" ); ws.getRange2( "A17" ).setValue( "Fruits" ); ws.getRange2( "B12" ).setValue( "Tomatoes" ); ws.getRange2( "B13" ).setValue( "Celery" ); ws.getRange2( "B14" ).setValue( "Oranges" ); ws.getRange2( "B15" ).setValue( "Butter" ); ws.getRange2( "B16" ).setValue( "Carrots" ); ws.getRange2( "B17" ).setValue( "Apples" ); ws.getRange2( "C12" ).setValue( "2300" ); ws.getRange2( "C13" ).setValue( "5500" ); ws.getRange2( "C14" ).setValue( "800" ); ws.getRange2( "C15" ).setValue( "400" ); ws.getRange2( "C16" ).setValue( "4200" ); ws.getRange2( "C17" ).setValue( "1200" ); oParser = new parserFormula( "SUMIF(A12:A17,\"Fruits\",C12:C17)", "A19", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2000 ); oParser = new parserFormula( "SUMIF(A12:A17,\"Vegetables\",C12:C17)", "A20", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 12000 ); oParser = new parserFormula( "SUMIF(B12:B17,\"*es\",C12:C17)", "A21", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4300 ); oParser = new parserFormula( "SUMIF(A12:A17,\"\",C12:C17)", "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 400 ); } ); test( "Test: \"SUMIFS\"", function () { ws.getRange2( "A2" ).setValue( "5" ); ws.getRange2( "A3" ).setValue( "4" ); ws.getRange2( "A4" ).setValue( "15" ); ws.getRange2( "A5" ).setValue( "3" ); ws.getRange2( "A6" ).setValue( "22" ); ws.getRange2( "A7" ).setValue( "12" ); ws.getRange2( "A8" ).setValue( "10" ); ws.getRange2( "A9" ).setValue( "33" ); ws.getRange2( "B2" ).setValue( "Apples" ); ws.getRange2( "B3" ).setValue( "Apples" ); ws.getRange2( "B4" ).setValue( "Artichokes" ); ws.getRange2( "B5" ).setValue( "Artichokes" ); ws.getRange2( "B6" ).setValue( "Bananas" ); ws.getRange2( "B7" ).setValue( "Bananas" ); ws.getRange2( "B8" ).setValue( "Carrots" ); ws.getRange2( "B9" ).setValue( "Carrots" ); ws.getRange2( "C2" ).setValue( "Tom" ); ws.getRange2( "C3" ).setValue( "Sarah" ); ws.getRange2( "C4" ).setValue( "Tom" ); ws.getRange2( "C5" ).setValue( "Sarah" ); ws.getRange2( "C6" ).setValue( "Tom" ); ws.getRange2( "C7" ).setValue( "Sarah" ); ws.getRange2( "C8" ).setValue( "Tom" ); ws.getRange2( "C9" ).setValue( "Sarah" ); oParser = new parserFormula( "SUMIFS(A2:A9, B2:B9, \"=A*\", C2:C9, \"Tom\")", "A10", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 20 ); oParser = new parserFormula( "SUMIFS(A2:A9, B2:B9, \"<>Bananas\", C2:C9, \"Tom\")", "A11", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30 ); oParser = new parserFormula( "SUMIFS(D:D,E:E,$H2)", "A11", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "SUMIFS(C:D,E:E,$H2)", "A11", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); } ); test( "Test: \"MAXIFS\"", function () { ws.getRange2( "AAA2" ).setValue( "10" ); ws.getRange2( "AAA3" ).setValue( "1" ); ws.getRange2( "AAA4" ).setValue( "100" ); ws.getRange2( "AAA5" ).setValue( "1" ); ws.getRange2( "AAA6" ).setValue( "1" ); ws.getRange2( "AAA7" ).setValue( "50" ); ws.getRange2( "BBB2" ).setValue( "b" ); ws.getRange2( "BBB3" ).setValue( "a" ); ws.getRange2( "BBB4" ).setValue( "a" ); ws.getRange2( "BBB5" ).setValue( "b" ); ws.getRange2( "BBB6" ).setValue( "a" ); ws.getRange2( "BBB7" ).setValue( "b" ); ws.getRange2( "DDD2" ).setValue( "100" ); ws.getRange2( "DDD3" ).setValue( "100" ); ws.getRange2( "DDD4" ).setValue( "200" ); ws.getRange2( "DDD5" ).setValue( "300" ); ws.getRange2( "DDD6" ).setValue( "100" ); ws.getRange2( "DDD7" ).setValue( "400" ); oParser = new parserFormula( 'MAXIFS(AAA2:AAA7,BBB2:BBB7,"b",DDD2:DDD7,">100")', "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 50 ); oParser = new parserFormula( 'MAXIFS(AAA2:AAA6,BBB2:BBB6,"a",DDD2:DDD6,">200")', "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); testArrayFormulaEqualsValues("1,3.123,-4,#N/A;2,4,5,#N/A;#N/A,#N/A,#N/A,#N/A","MAXIFS(A1:C2,A1:C2,A1:C2,A1:C2, A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,0,0,#N/A;0,0,0,#N/A;#N/A,#N/A,#N/A,#N/A","MAXIFS(A1:C2,A1:C2,A1:A1,A1:C2,A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,0,0,#N/A;2,0,0,#N/A;#N/A,#N/A,#N/A,#N/A","MAXIFS(A1:C2,A1:C2,A1:A2,A1:C2,A1:C2,A1:C2,A1:C2)"); } ); test( "Test: \"MINIFS\"", function () { ws.getRange2( "AAA2" ).setValue( "10" ); ws.getRange2( "AAA3" ).setValue( "1" ); ws.getRange2( "AAA4" ).setValue( "100" ); ws.getRange2( "AAA5" ).setValue( "1" ); ws.getRange2( "AAA6" ).setValue( "1" ); ws.getRange2( "AAA7" ).setValue( "50" ); ws.getRange2( "BBB2" ).setValue( "b" ); ws.getRange2( "BBB3" ).setValue( "a" ); ws.getRange2( "BBB4" ).setValue( "a" ); ws.getRange2( "BBB5" ).setValue( "b" ); ws.getRange2( "BBB6" ).setValue( "a" ); ws.getRange2( "BBB7" ).setValue( "b" ); ws.getRange2( "DDD2" ).setValue( "100" ); ws.getRange2( "DDD3" ).setValue( "100" ); ws.getRange2( "DDD4" ).setValue( "200" ); ws.getRange2( "DDD5" ).setValue( "300" ); ws.getRange2( "DDD6" ).setValue( "100" ); ws.getRange2( "DDD7" ).setValue( "400" ); oParser = new parserFormula( 'MINIFS(AAA2:AAA7,BBB2:BBB7,"b",DDD2:DDD7,">100")', "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( 'MINIFS(AAA2:AAA6,BBB2:BBB6,"a",DDD2:DDD6,">200")', "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); testArrayFormulaEqualsValues("1,3.123,-4,#N/A;2,4,5,#N/A;#N/A,#N/A,#N/A,#N/A","MINIFS(A1:C2,A1:C2,A1:C2,A1:C2, A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,0,0,#N/A;0,0,0,#N/A;#N/A,#N/A,#N/A,#N/A","MINIFS(A1:C2,A1:C2,A1:A1,A1:C2,A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,0,0,#N/A;2,0,0,#N/A;#N/A,#N/A,#N/A,#N/A","MINIFS(A1:C2,A1:C2,A1:A2,A1:C2,A1:C2,A1:C2,A1:C2)"); } ); test( "Test: \"TEXT\"", function () { var culturelciddefault = AscCommon.g_oDefaultCultureInfo.LCID; oParser = new parserFormula( "TEXT(1234.567,\"$0.00\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "$1234.57" ); oParser = new parserFormula( "TEXT(0.125,\"0.0%\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "12.5%" ); testArrayFormula2("TEXT", 2, 2); //___________________________________ru______________________________________________ AscCommon.setCurrentCultureInfo(1049); oParser = new parserFormula( "TEXT(123,\"гг-мм-дд\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"чч:мм:сс\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); oParser = new parserFormula( "TEXT(123,\"основной\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "123" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //____________________________________en_____________________________________________ AscCommon.setCurrentCultureInfo(1025); oParser = new parserFormula( "TEXT(123,\"yy-mm-dd\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"hh:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); oParser = new parserFormula( "TEXT(123,\"general\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "123" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //__________________________________es________________________________________________ AscCommon.setCurrentCultureInfo(3082); oParser = new parserFormula( "TEXT(123,\"aa-mm-dd\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"hh:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); oParser = new parserFormula( "TEXT(127,\"Estándar\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "127" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //__________________________________fi________________________________________________ AscCommon.setCurrentCultureInfo(1035); oParser = new parserFormula( "TEXT(123,\"vv-mm-pp\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"tt:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); oParser = new parserFormula( "TEXT(123,\"yleinen\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "123" ); oParser = new parserFormula( "TEXT(123,\"\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //__________________________________fy________________________________________________ AscCommon.setCurrentCultureInfo(1043); oParser = new parserFormula( "TEXT(123,\"jj-mm-dd\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"uu:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //__________________________________fr________________________________________________ AscCommon.setCurrentCultureInfo(1036); oParser = new parserFormula( "TEXT(123,\"jj-mm-aa\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"hh:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //_______________________________de___________________________________________________ AscCommon.setCurrentCultureInfo(1031); oParser = new parserFormula( "TEXT(123,\"jj-mm-tt\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"hh:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //_______________________________da____________________________________________________ AscCommon.setCurrentCultureInfo(1053); oParser = new parserFormula( "TEXT(123,\"åå-mm-dd\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"tt:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //_____________________________special________________________________________________ AscCommon.setCurrentCultureInfo(1032); oParser = new parserFormula( "TEXT(123,\"εε-μμ-ηη\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"ωω:λλ:δδ\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); AscCommon.setCurrentCultureInfo(culturelciddefault); AscCommon.setCurrentCultureInfo(1029); oParser = new parserFormula( "TEXT(123,\"rr-mm-dd\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"hh:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); AscCommon.setCurrentCultureInfo(culturelciddefault); AscCommon.setCurrentCultureInfo(1041); oParser = new parserFormula( "TEXT(124,\"G/標準\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "124" ); AscCommon.setCurrentCultureInfo(culturelciddefault); } ); test( "Test: \"TEXTJOIN\"", function () { ws.getRange2( "A2" ).setValue( "Tulsa" ); ws.getRange2( "A3" ).setValue( "Seattle" ); ws.getRange2( "A4" ).setValue( "Iselin" ); ws.getRange2( "A5" ).setValue( "Fort Lauderdale" ); ws.getRange2( "A6" ).setValue( "Tempe" ); ws.getRange2( "A7" ).setValue( "end" ); ws.getRange2( "B2" ).setValue( "OK" ); ws.getRange2( "B3" ).setValue( "WA" ); ws.getRange2( "B4" ).setValue( "NJ" ); ws.getRange2( "B5" ).setValue( "FL" ); ws.getRange2( "B6" ).setValue( "AZ" ); ws.getRange2( "B7" ).setValue( "" ); ws.getRange2( "C2" ).setValue( "74133" ); ws.getRange2( "C3" ).setValue( "98109" ); ws.getRange2( "C4" ).setValue( "8830" ); ws.getRange2( "C5" ).setValue( "33309" ); ws.getRange2( "C6" ).setValue( "85285" ); ws.getRange2( "C7" ).setValue( "" ); ws.getRange2( "D2" ).setValue( "US" ); ws.getRange2( "D3" ).setValue( "US" ); ws.getRange2( "D4" ).setValue( "US" ); ws.getRange2( "D5" ).setValue( "US" ); ws.getRange2( "D6" ).setValue( "US" ); ws.getRange2( "D7" ).setValue( "" ); ws.getRange2( "A9" ).setValue( "," ); ws.getRange2( "B9" ).setValue( "," ); ws.getRange2( "C9" ).setValue( "," ); ws.getRange2( "D9" ).setValue( ";" ); oParser = new parserFormula( "TEXTJOIN(A9:D9, TRUE, A2:D7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Tulsa,OK,74133,US;Seattle,WA,98109,US;Iselin,NJ,8830,US;Fort Lauderdale,FL,33309,US;Tempe,AZ,85285,US;end" ); oParser = new parserFormula( "TEXTJOIN(A9:D9, FALSE, A2:D7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Tulsa,OK,74133,US;Seattle,WA,98109,US;Iselin,NJ,8830,US;Fort Lauderdale,FL,33309,US;Tempe,AZ,85285,US;end,,," ); oParser = new parserFormula( "TEXTJOIN(A2:D5, 1, B6:D6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "AZTulsa85285OKUS" ); testArrayFormulaEqualsValues("113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,#N/A;113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,#N/A;#N/A,#N/A,#N/A,#N/A", "TEXTJOIN(A1:C2,A1:C2,A1:C2,A1:C2, A1:C2)"); testArrayFormulaEqualsValues("113.1232-41224152113.1232-4122415,113.1232-41224152113.1232-4122415,113.1232-41224152113.1232-4122415,#N/A;113.1232-41224152113.1232-4122415,113.1232-41224152113.1232-4122415,113.1232-41224152113.1232-4122415,#N/A;#N/A,#N/A,#N/A,#N/A", "TEXTJOIN(A1:A2,A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445;113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445;#N/A,#N/A,#N/A,#N/A", "TEXTJOIN(A1:C2,A1:A2,A1:C2,A1:C2,A1:C2,A1:C2)"); } ); test("Test: \"WORKDAY\"", function () { oParser = new parserFormula("WORKDAY(DATE(2006,1,1),0)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 38718); oParser = new parserFormula("WORKDAY(DATE(2006,1,1),10)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 38730); oParser = new parserFormula("WORKDAY(DATE(2006,1,1),-10)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 38705); oParser = new parserFormula("WORKDAY(DATE(2006,1,1),20,{\"1-2-2006\",\"1-16-2006\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 38748); oParser = new parserFormula("WORKDAY(DATE(2017,10,6),1,DATE(2017,10,9))", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43018); oParser = new parserFormula("WORKDAY(DATE(2017,10,7),1,DATE(2017,10,9))", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43018); oParser = new parserFormula("WORKDAY(DATE(2017,9,25),-1,DATE(2017,9,10))", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43000); oParser = new parserFormula("WORKDAY(DATE(2017,9,25),-1,DATE(2017,9,10))", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43000); oParser = new parserFormula("WORKDAY(DATE(2017,9,20),-1,DATE(2017,9,10))", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 42997); oParser = new parserFormula("WORKDAY(DATE(2017,10,2),-1)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43007); oParser = new parserFormula("WORKDAY(DATE(2017,10,2),-1)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43007); oParser = new parserFormula("WORKDAY(DATE(2017,10,3),-3)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43006); oParser = new parserFormula("WORKDAY(DATE(2017,10,4),-2)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43010); oParser = new parserFormula("WORKDAY(DATE(2018,4,30),1,{\"5-1-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43222); oParser = new parserFormula("WORKDAY(DATE(2018,4,30),2,{\"5-1-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43224); oParser = new parserFormula("WORKDAY(DATE(2018,4,30),3,{\"5-1-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43227); oParser = new parserFormula("WORKDAY(DATE(2018,4,30),1,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43224); oParser = new parserFormula("WORKDAY(DATE(2018,4,30),3,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43228); oParser = new parserFormula("WORKDAY(DATE(2018,4,29),1,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43220); oParser = new parserFormula("WORKDAY(DATE(2018,4,29),2,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43224); oParser = new parserFormula("WORKDAY(DATE(2018,4,29),3,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43227); oParser = new parserFormula("WORKDAY(DATE(2018,4,29),-1,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43217); oParser = new parserFormula("WORKDAY(DATE(2018,4,29),-2,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43216); oParser = new parserFormula("WORKDAY(DATE(2018,4,29),0,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43219); oParser = new parserFormula("WORKDAY({1,2,3},{1,2})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); oParser = new parserFormula("WORKDAY({1,2,3},1)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); oParser = new parserFormula("WORKDAY(1,{1,2})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); oParser = new parserFormula("WORKDAY({1,2,3},1.123)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); oParser = new parserFormula("WORKDAY({1,2,3},-1.123)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula("WORKDAY({1,2,3},5)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 6); oParser = new parserFormula("WORKDAY(1,15)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 20); /*oParser = new parserFormula("WORKDAY(1,50)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 69); oParser = new parserFormula("WORKDAY(1,60)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 83); oParser = new parserFormula("WORKDAY(1,61)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 86);*/ //todo ms выдаёт ошибки /*ws.getRange2( "A101" ).setValue( "1" ); ws.getRange2( "B101" ).setValue( "3.123" ); ws.getRange2( "C101" ).setValue( "-4" ); oParser = new parserFormula("WORKDAY(A101:B101,A101:B101)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "#VALUE!"); oParser = new parserFormula("WORKDAY(A101,A101:B101)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "#VALUE!"); oParser = new parserFormula("WORKDAY(A101:B101,A101)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "#VALUE!"); oParser = new parserFormula("WORKDAY(A101,A101)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2);*/ }); test( "Test: \"WORKDAY.INTL\"", function () { oParser = new parserFormula( "WORKDAY.INTL(DATE(2012,1,1),30,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "WORKDAY.INTL(DATE(2012,1,1),90,11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 41013 ); oParser = new parserFormula( 'TEXT(WORKDAY.INTL(DATE(2012,1,1),30,17),"m/dd/yyyy")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "2/05/2012" ); oParser = new parserFormula( 'WORKDAY.INTL(151,8,"0000000")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 159 ); oParser = new parserFormula( 'WORKDAY.INTL(151,8,"0000000")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 159 ); oParser = new parserFormula( 'WORKDAY.INTL(159,8,"0011100")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 171 ); oParser = new parserFormula( 'WORKDAY.INTL(151,-18,"0000000")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 133 ); oParser = new parserFormula( 'WORKDAY.INTL(151,8,"1111111")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( 'WORKDAY.INTL(DATE(2006,1,1),20,1,{"1/2/2006","1/16/2006"})', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38748 ); oParser = new parserFormula( 'WORKDAY.INTL(DATE(2006,1,1),20,{"1/2/2006","1/16/2006"})', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( 'WORKDAY.INTL(DATE(2006,1,1),-20,1,{"1/2/2006",,"1/16/2006"})', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38691 ); } ); test( "Test: \"TIME\"", function () { ws.getRange2( "A2" ).setValue( "12" ); ws.getRange2( "A3" ).setValue( "16" ); ws.getRange2( "B2" ).setValue( "0" ); ws.getRange2( "B3" ).setValue( "48" ); ws.getRange2( "C2" ).setValue( "0" ); ws.getRange2( "C3" ).setValue( "10" ); oParser = new parserFormula( "TIME(A2,B2,C2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0.5 ); oParser = new parserFormula( "TIME(A3,B3,C3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.7001157 ); oParser = new parserFormula( "TIME(1,1,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0423727 ); oParser = new parserFormula( "TIME(1.34,1,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0423727 ); oParser = new parserFormula( "TIME(1.34,1.456,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0423727 ); oParser = new parserFormula( "TIME(1.34,1.456,1.9)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0423727 ); oParser = new parserFormula( "TIME(-1.34,1.456,1.9)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("TIME", 3, 3); } ); test( "Test: \"TIMEVALUE\"", function () { oParser = new parserFormula( "timevalue(\"10:02:34\")", "A2", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - 0.4184490740740740 ) < dif ); oParser = new parserFormula( "timevalue(\"02-01-2006 10:15:29 AM\")", "A2", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - 0.4274189814823330 ) < dif ); oParser = new parserFormula( "timevalue(\"22:02\")", "A2", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - 0.9180555555555560 ) < dif ); testArrayFormula("TIMEVALUE"); } ); test( "Test: \"TYPE\"", function () { ws.getRange2( "A2" ).setValue( "Smith" ); oParser = new parserFormula( "TYPE(A2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( 'TYPE("Mr. "&A2)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( 'TYPE(2+A2)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 16 ); oParser = new parserFormula( '(2+A2)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( 'TYPE({1,2;3,4})', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 64 ); //TODO нужна другая функция для тестирования //testArrayFormula2("TYPE", 1, 1); } ); test( "Test: \"DAYS360\"", function () { oParser = new parserFormula( "DAYS360(DATE(2002,2,3),DATE(2005,5,31))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1198 ); oParser = new parserFormula( "DAYS360(DATE(2005,5,31),DATE(2002,2,3))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1197 ); oParser = new parserFormula( "DAYS360(DATE(2002,2,3),DATE(2005,5,31),FALSE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1198 ); oParser = new parserFormula( "DAYS360(DATE(2002,2,3),DATE(2005,5,31),TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1197 ); testArrayFormula2("DAYS360", 2, 3); } ); test( "Test: \"WEEKNUM\"", function () { oParser = new parserFormula( "WEEKNUM(DATE(2006,1,1))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2006,1,1),17)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2006,1,1),1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2006,1,1),21)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 52 ); oParser = new parserFormula( "WEEKNUM(DATE(2006,2,1),1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "WEEKNUM(DATE(2006,2,1),2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( "WEEKNUM(DATE(2006,2,1),11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( "WEEKNUM(DATE(2007,1,1),15)", "A2", ws );//понед ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2008,1,1),15)", "A2", ws );//втор ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2003,1,1),15)", "A2", ws );//сред ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2009,1,1),15)", "A2", ws );//чет ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2010,1,1),15)", "A2", ws );//пят ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2011,1,1),15)", "A2", ws );//суб ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2012,1,1),11)", "A2", ws );//вск ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2008,1,4),11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2008,1,10),11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "WEEKNUM(DATE(2008,1,11),11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "WEEKNUM(DATE(2008,1,17),11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "WEEKNUM(DATE(2008,1,18),11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "WEEKNUM(DATE(2008,1,24),11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "WEEKNUM(DATE(2013,1,1),21)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2013,1,7))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); testArrayFormula2("WEEKNUM", 1, 2, true); } ); test( "Test: \"ISOWEEKNUM\"", function () { ws.getRange2( "A2" ).setValue( "3/9/2012" ); oParser = new parserFormula( "ISOWEEKNUM(A2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( "ISOWEEKNUM(123)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 18 ); oParser = new parserFormula( "ISOWEEKNUM(120003)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30 ); oParser = new parserFormula( "ISOWEEKNUM(120003)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30 ); oParser = new parserFormula( "ISOWEEKNUM(-100)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "ISOWEEKNUM(1203)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 16 ); testArrayFormula2("ISOWEEKNUM",1,1); } ); test( "Test: \"WEEKDAY\"", function () { ws.getRange2( "A2" ).setValue( "2/14/2008" ); oParser = new parserFormula( "WEEKDAY(A2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "WEEKDAY(A2, 2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "WEEKDAY(A2, 3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); testArrayFormula2("WEEKDAY", 1, 2); } ); test( "Test: \"WEIBULL\"", function () { ws.getRange2( "A2" ).setValue( "105" ); ws.getRange2( "A3" ).setValue( "20" ); ws.getRange2( "A4" ).setValue( "100" ); oParser = new parserFormula( "WEIBULL(A2,A3,A4,TRUE)", "A20", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.929581 ); oParser = new parserFormula( "WEIBULL(A2,A3,A4,FALSE)", "A20", ws ); ok( oParser.parse(), "WEIBULL(A2,A3,A4,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.035589 ); testArrayFormula2("WEIBULL", 4, 4); } ); test( "Test: \"WEIBULL.DIST\"", function () { ws.getRange2( "A2" ).setValue( "105" ); ws.getRange2( "A3" ).setValue( "20" ); ws.getRange2( "A4" ).setValue( "100" ); oParser = new parserFormula( "WEIBULL.DIST(A2,A3,A4,TRUE)", "A20", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.929581 ); oParser = new parserFormula( "WEIBULL.DIST(A2,A3,A4,FALSE)", "A20", ws ); ok( oParser.parse(), "WEIBULL.DIST(A2,A3,A4,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.035589 ); testArrayFormula2("WEIBULL.DIST", 4, 4); } ); test( "Test: \"YEARFRAC\"", function () { function okWrapper( a, b ) { ok( Math.abs( a - b ) < dif ); } oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2006,3,26))", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.236111111 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,3,26),DATE(2006,1,1))", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.236111111 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2006,7,1))", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.5 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2007,9,1))", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 1.666666667 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2006,7,1),0)", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.5 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2006,7,1),1)", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.495890411 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2006,7,1),2)", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.502777778 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2006,7,1),3)", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.495890411 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2006,7,1),4)", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.5 ); oParser = new parserFormula( "YEARFRAC(DATE(2004,3,1),DATE(2006,3,1),1)", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 1.998175182481752 ); testArrayFormula2("YEARFRAC", 2, 3, true); } ); test( "Test: \"DATEDIF\"", function () { oParser = new parserFormula( "DATEDIF(DATE(2001,1,1),DATE(2003,1,1),\"Y\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "DATEDIF(DATE(2001,6,1),DATE(2002,8,15),\"D\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 440 ); oParser = new parserFormula( "DATEDIF(DATE(2001,6,1),DATE(2002,8,15),\"YD\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 75 ); oParser = new parserFormula( "DATEDIF(DATE(2001,6,1),DATE(2002,8,15),\"MD\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 14 ); testArrayFormula2("DATEDIF", 3, 3); } ); test( "Test: \"PRODUCT\"", function () { ws.getRange2( "A2" ).setValue( "5" ); ws.getRange2( "A3" ).setValue( "15" ); ws.getRange2( "A4" ).setValue( "30" ); oParser = new parserFormula( "PRODUCT(A2:A4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2250 ); oParser = new parserFormula( "PRODUCT(A2:A4, 2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4500 ); testArrayFormula2("PRODUCT", 1, 8, null, true); } ); test( "Test: \"SUMPRODUCT\"", function () { oParser = new parserFormula( "SUMPRODUCT({2,3})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "SUMPRODUCT({2,3},{4,5})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 23 ); oParser = new parserFormula( "SUMPRODUCT({2,3},{4,5},{2,2})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 46 ); oParser = new parserFormula( "SUMPRODUCT({2,3;4,5},{2,2;3,4})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 42 ); ws.getRange2( "N44" ).setValue( "1" ); ws.getRange2( "N45" ).setValue( "2" ); ws.getRange2( "N46" ).setValue( "3" ); ws.getRange2( "N47" ).setValue( "4" ); ws.getRange2( "O44" ).setValue( "5" ); ws.getRange2( "O45" ).setValue( "6" ); ws.getRange2( "O46" ).setValue( "7" ); ws.getRange2( "O47" ).setValue( "8" ); ws.getRange2( "P44" ).setValue( "9" ); ws.getRange2( "P45" ).setValue( "10" ); ws.getRange2( "P46" ).setValue( "11" ); ws.getRange2( "P47" ).setValue( "12" ); ws.getRange2( "P48" ).setValue( "" ); ws.getRange2( "P49" ).setValue( "" ); ws.getRange2( "N48" ).setValue( "0.456" ); ws.getRange2( "O48" ).setValue( "0.123212" ); oParser = new parserFormula( "SUMPRODUCT(N44:N47,O44:O47,P44:P47)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 780 ); oParser = new parserFormula( "SUMPRODUCT(N44:N47*O44:O47)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 70 ); oParser = new parserFormula( "SUMPRODUCT(SUM(N44:N47*O44:O47))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 70 ); oParser = new parserFormula( "SUMPRODUCT({1,2,TRUE,3})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( "SUMPRODUCT({1,2,FALSE,3})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( "SUMPRODUCT({TRUE,TRUE,FALSE,3})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "SUMPRODUCT(P48)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "SUMPRODUCT(P48, P44:P47)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "SUMPRODUCT(P48:P49)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "SUM(SUMPRODUCT(N44:N47*O44:O47))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 70 ); oParser = new parserFormula( "SUMPRODUCT(N44:O47*P44:P47)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 388 ); oParser = new parserFormula( "SUM(SUMPRODUCT(N44:O47*P44:P47))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 388 ); oParser = new parserFormula( "SUM(SUMPRODUCT(N44:O47))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUM(SUMPRODUCT(N44:O47))" ); strictEqual( oParser.calculate().getValue(), 36 ); oParser = new parserFormula( "SUMPRODUCT(YEAR(N45:O47))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 11400 ); oParser = new parserFormula( "SUMPRODUCT(MONTH(N45:O47))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( "SUMPRODUCT(DAY(N45:O47))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30 ); oParser = new parserFormula( "SUMPRODUCT(HOUR(N45:P48))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 12 ); oParser = new parserFormula( "SUMPRODUCT(MINUTE(N45:P48))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 113 ); oParser = new parserFormula( "SUMPRODUCT(SECOND(N45:P48))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 64 ); oParser = new parserFormula( "SUMPRODUCT(DAY(N44:P49))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 78 ); oParser = new parserFormula( "SUMPRODUCT(MONTH(N44:P49))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 18 ); oParser = new parserFormula( "SUMPRODUCT(YEAR(N44:P49))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 34200 ); oParser = new parserFormula( "SUMPRODUCT(({1,2,3})*({TRUE,TRUE,TRUE}))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); /*oParser = new parserFormula( "SUMPRODUCT(({1,2,3})*({TRUE;TRUE;TRUE;TRUE}))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 24 );*/ oParser = new parserFormula( "SUMPRODUCT({TRUE,TRUE,FALSE})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "SUMPRODUCT({1,2,3,3,TRUE})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 9 ); oParser = new parserFormula( "SUMPRODUCT({1,2,3,3,TRUE})+SUMPRODUCT({1,2,3,3,TRUE})", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT({1,2,3,3,TRUE})+SUMPRODUCT({1,2,3,3,TRUE})" ); strictEqual( oParser.calculate().getValue(), 18 ); oParser = new parserFormula( "SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE})", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE})" ); strictEqual( oParser.calculate().getValue(), 81 ); oParser = new parserFormula( "SUMPRODUCT(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}))" ); strictEqual( oParser.calculate().getValue(), 81 ); oParser = new parserFormula( "SUM(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUM(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}))" ); strictEqual( oParser.calculate().getValue(), 81 ); oParser = new parserFormula( "SUM(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}),1,2,3)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUM(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}),1,2,3)" ); strictEqual( oParser.calculate().getValue(), 87 ); oParser = new parserFormula( "SUM(SUMPRODUCT(N44:O47))+SUM(SUMPRODUCT(N44:O47))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUM(SUMPRODUCT(N44:O47))+SUM(SUMPRODUCT(N44:O47))" ); strictEqual( oParser.calculate().getValue(), 72 ); oParser = new parserFormula( "SUM(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}),SUMPRODUCT({1,2,3,3,TRUE}),2,SUMPRODUCT({1,2,3,3}))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUM(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}),SUMPRODUCT({1,2,3,3,TRUE}),2,SUMPRODUCT({1,2,3,3}))" ); strictEqual( oParser.calculate().getValue(), 101 ); ws.getRange2( "A101" ).setValue( "5" ); ws.getRange2( "A102" ).setValue( "6" ); ws.getRange2( "A103" ).setValue( "7" ); ws.getRange2( "A104" ).setValue( "8" ); ws.getRange2( "A105" ).setValue( "9" ); ws.getRange2( "B101" ).setValue( "1" ); ws.getRange2( "B102" ).setValue( "1" ); ws.getRange2( "B103" ).setValue( "0" ); ws.getRange2( "B104" ).setValue( "1" ); ws.getRange2( "B105" ).setValue( "1" ); oParser = new parserFormula( "SUMPRODUCT((A101:A105)*((B101:B105)=1))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT((A101:A105)*((B101:B105)=1))" ); strictEqual( oParser.calculate().getValue(), 28 ); oParser = new parserFormula( "SUMPRODUCT((A101:A105)*((B101:B105)=1))+SUMPRODUCT((A101:A104)*((B101:B104)=1))+SUMPRODUCT((A101:A103)*((B101:B103)=1))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT((A101:A105)*((B101:B105)=1))+SUMPRODUCT((A101:A104)*((B101:B104)=1))+SUMPRODUCT((A101:A103)*((B101:B103)=1))" ); strictEqual( oParser.calculate().getValue(), 58 ); oParser = new parserFormula( "SUMPRODUCT(({3})*({TRUE,TRUE,TRUE,TRUE}))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT(({3})*({TRUE,TRUE,TRUE,TRUE}))" ); strictEqual( oParser.calculate().getValue(), 12 ); oParser = new parserFormula( "SUMPRODUCT(({3;2;2;2})*({TRUE;TRUE;TRUE;TRUE}))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT(({3;2;2;2})*({TRUE;TRUE;TRUE;TRUE}))" ); strictEqual( oParser.calculate().getValue(), 9 ); oParser = new parserFormula( "SUMPRODUCT(--ISNUMBER({5;6;7;1;2;3;4}))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT(--ISNUMBER({5;6;7;1;2;3;4}))" ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( "SUMPRODUCT(--ISNUMBER(SEARCH({5;6;7;1;2;3;4},123)))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT(--ISNUMBER(SEARCH({5;6;7;1;2;3;4},123)))" ); strictEqual( oParser.calculate().getValue(), 3 ); testArrayFormula2("SUMPRODUCT", 1, 8, null, true); } ); test( "Test: \"SINH\"", function () { oParser = new parserFormula( "SINH(0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "SINH(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ((Math.E - 1 / Math.E) / 2) ); testArrayFormula("SINH"); } ); test( "Test: \"SIGN\"", function () { oParser = new parserFormula( "SIGN(10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "SIGN(4-4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "SIGN(-0.00001)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1 ); testArrayFormula("SIGN"); } ); test( "Test: \"COSH\"", function () { oParser = new parserFormula( "COSH(0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COSH(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ((Math.E + 1 / Math.E) / 2) ); } ); test( "Test: \"IMCOSH\"", function () { oParser = new parserFormula( 'IMCOSH("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMCOSH("4+3i")' ); strictEqual( oParser.calculate().getValue(), "-27.03494560307422+3.8511533348117766i", 'IMCOSH("4+3i")' ); testArrayFormula("IMCOSH", true); } ); test( "Test: \"IMCOS\"", function () { oParser = new parserFormula( 'IMCOS("1+i")', "A2", ws ); ok( oParser.parse(), 'IMCOS("1+i")' ); strictEqual( oParser.calculate().getValue(), "0.8337300251311491-0.9888977057628651i", 'IMCOS("1+i")' ); testArrayFormula("IMCOS", true); } ); test( "Test: \"IMCOT\"", function () { oParser = new parserFormula( 'IMCOT("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMCOT("4+3i")' ); strictEqual( oParser.calculate().getValue(), "0.004901182394304475-0.9992669278059015i", 'IMCOT("4+3i")' ); testArrayFormula("IMCOT", true); } ); test( "Test: \"IMCSC\"", function () { oParser = new parserFormula( 'IMCSC("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMCSC("4+3i")' ); strictEqual( oParser.calculate().getValue(), "-0.0754898329158637+0.06487747137063551i", 'IMCSC("4+3i")' ); testArrayFormula("IMCSC", true); } ); test( "Test: \"IMCSCH\"", function () { oParser = new parserFormula( 'IMCSCH("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMCSCH("4+3i")' ); strictEqual( oParser.calculate().getValue(), "-0.03627588962862601-0.0051744731840193976i", 'IMCSCH("4+3i")' ); testArrayFormula("IMCSCH", true); } ); test( "Test: \"IMSIN\"", function () { oParser = new parserFormula( 'IMSIN("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMSIN("4+3i")' ); strictEqual( oParser.calculate().getValue(), "-7.619231720321408-6.548120040911002i", 'IMSIN("4+3i")' ); testArrayFormula("IMSIN", true); } ); test( "Test: \"IMSINH\"", function () { oParser = new parserFormula( 'IMSINH("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMSINH("4+3i")' ); strictEqual( oParser.calculate().getValue(), "-27.01681325800393+3.8537380379193764i", 'IMSINH("4+3i")' ); testArrayFormula("IMSINH", true); } ); test( "Test: \"IMSEC\"", function () { oParser = new parserFormula( 'IMSEC("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMSEC("4+3i")' ); strictEqual( oParser.calculate().getValue(), "-0.06529402785794705-0.07522496030277323i", 'IMSEC("4+3i")' ); testArrayFormula("IMSEC", true); } ); test( "Test: \"IMSECH\"", function () { oParser = new parserFormula( 'IMSECH("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMSECH("4+3i")' ); strictEqual( oParser.calculate().getValue(), "-0.03625349691586888-0.00516434460775318i", 'IMSECH("4+3i")' ); testArrayFormula("IMSECH", true); } ); test( "Test: \"IMTAN\"", function () { oParser = new parserFormula( 'IMTAN("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMTAN("4+3i")' ); strictEqual( oParser.calculate().getValue(), "0.004908258067496062+1.000709536067233i", 'IMTAN("4+3i")' ); testArrayFormula("IMTAN", true); } ); test( "Test: \"IMSQRT\"", function () { oParser = new parserFormula( 'IMSQRT("1+i")', "A2", ws ); ok( oParser.parse(), 'IMSQRT("1+i")' ); //strictEqual( oParser.calculate().getValue(), "1.0986841134678098+0.4550898605622274i", 'IMSQRT("1+i")' ); testArrayFormula("IMSQRT", true); } ); test( "Test: \"IMREAL\"", function () { oParser = new parserFormula( 'IMREAL("6-9i")', "A2", ws ); ok( oParser.parse(), 'IMREAL("6-9i")' ); strictEqual( oParser.calculate().getValue(), 6, 'IMREAL("6-9i")' ); testArrayFormula("IMREAL", true); } ); test( "Test: \"IMLOG2\"", function () { //TODO в excel результат данной формулы - "2.32192809488736+1.33780421245098i" oParser = new parserFormula( 'IMLOG2("3+4i")', "A2", ws ); ok( oParser.parse(), 'IMLOG2("3+4i")' ); strictEqual( oParser.calculate().getValue(), "2.321928094887362+1.3378042124509761i", 'IMLOG2("3+4i")' ); testArrayFormula("IMLOG2", true); } ); test( "Test: \"IMLOG10\"", function () { //TODO в excel результат данной формулы - "0.698970004336019+0.402719196273373i" oParser = new parserFormula( 'IMLOG10("3+4i")', "A2", ws ); ok( oParser.parse(), 'IMLOG10("3+4i")' ); strictEqual( oParser.calculate().getValue(), "0.6989700043360186+0.40271919627337305i", 'IMLOG10("3+4i")' ); testArrayFormula("IMLOG10", true); } ); test( "Test: \"IMLN\"", function () { //TODO в excel результат данной формулы - "1.6094379124341+0.927295218001612i" oParser = new parserFormula( 'IMLN("3+4i")', "A2", ws ); ok( oParser.parse(), 'IMLN("3+4i")' ); strictEqual( oParser.calculate().getValue(), "1.6094379124341003+0.9272952180016123i", 'IMLN("3+4i")' ); testArrayFormula("IMLN", true); } ); test( "Test: \"IMEXP\"", function () { //TODO в excel результат данной формулы - "1.46869393991589+2.28735528717884i" oParser = new parserFormula( 'IMEXP("1+i")', "A2", ws ); ok( oParser.parse(), 'IMEXP("1+i")' ); strictEqual( oParser.calculate().getValue(), "1.4686939399158851+2.2873552871788423i", 'IMEXP("1+i")' ); testArrayFormula("IMEXP", true); } ); test( "Test: \"IMCONJUGATE\"", function () { oParser = new parserFormula( 'IMCONJUGATE("3+4i")', "A2", ws ); ok( oParser.parse(), 'IMCONJUGATE("3+4i")' ); strictEqual( oParser.calculate().getValue(), "3-4i", 'IMCONJUGATE("3+4i")' ); testArrayFormula("IMCONJUGATE", true); } ); test( "Test: \"IMARGUMENT\"", function () { oParser = new parserFormula( 'IMARGUMENT("3+4i")', "A2", ws ); ok( oParser.parse(), 'IMARGUMENT("3+4i")' ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.92729522, 'IMARGUMENT("3+4i")' ); testArrayFormula("IMARGUMENT", true); } ); test( "Test: \"IMAGINARY\"", function () { oParser = new parserFormula( 'IMAGINARY("3+4i")', "A2", ws ); ok( oParser.parse(), 'IMAGINARY("3+4i")' ); strictEqual( oParser.calculate().getValue(), 4, 'IMAGINARY("3+4i")' ); oParser = new parserFormula( 'IMAGINARY("0-j")', "A2", ws ); ok( oParser.parse(), 'IMAGINARY("0-j")' ); strictEqual( oParser.calculate().getValue(), -1, 'IMAGINARY("0-j")' ); oParser = new parserFormula( 'IMAGINARY("4")', "A2", ws ); ok( oParser.parse(), 'IMAGINARY("4")' ); strictEqual( oParser.calculate().getValue(), 0, 'IMAGINARY("4")' ); testArrayFormula("IMAGINARY", true); } ); test( "Test: \"IMDIV\"", function () { oParser = new parserFormula( 'IMDIV("-238+240i","10+24i")', "A2", ws ); ok( oParser.parse(), 'IMDIV("-238+240i","10+24i")' ); strictEqual( oParser.calculate().getValue(), "5+12i", 'IMDIV("-238+240i","10+24i")' ); testArrayFormula2("IMDIV", 2, 2, true); } ); test( "Test: \"IMPOWER\"", function () { testArrayFormula2("IMPOWER", 2, 2, true); } ); test( "Test: \"IMABS\"", function () { oParser = new parserFormula( 'IMABS("5+12i")', "A2", ws ); ok( oParser.parse(), 'IMABS("5+12i"' ); strictEqual( oParser.calculate().getValue(), 13, 'IMABS("5+12i"' ); testArrayFormula("IMABS", true); } ); test( "Test: \"IMSUB\"", function () { oParser = new parserFormula( 'IMSUB("13+4i","5+3i")', "A2", ws ); ok( oParser.parse(), 'IMSUB("13+4i","5+3i")' ); strictEqual( oParser.calculate().getValue(), "8+i", 'IMSUB("13+4i","5+3i")' ); testArrayFormula2("IMSUB", 2, 2, true); } ); test( "Test: \"TAN\"", function () { oParser = new parserFormula( "TAN(0.785)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 0.99920 ); oParser = new parserFormula( "TAN(45*PI()/180)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(1) - 0, 1 ); testArrayFormula("TAN"); } ); test( "Test: \"TANH\"", function () { oParser = new parserFormula( "TANH(0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "TANH(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), ((Math.E * Math.E - 1) / (Math.E * Math.E + 1)) ), true ); testArrayFormula("TANH"); } ); test( "Test: \"ATAN\"", function () { oParser = new parserFormula( 'ATAN(1)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.785398163 ); testArrayFormula("ATAN"); } ); test( "Test: \"ATAN2\"", function () { oParser = new parserFormula( 'ATAN2(1, 1)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.785398163); oParser = new parserFormula( 'ATAN2(-1, -1)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, -2.35619449); oParser = new parserFormula( 'ATAN2(-1, -1)*180/PI()', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -135); oParser = new parserFormula( 'DEGREES(ATAN2(-1, -1))', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -135); testArrayFormula2("ATAN2", 2, 2); } ); test( "Test: \"ATANH\"", function () { oParser = new parserFormula( 'ATANH(0.76159416)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 1.00000001 ); oParser = new parserFormula( 'ATANH(-0.1)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, -0.100335348 ); testArrayFormula("ATANH"); } ); test( "Test: \"XOR\"", function () { oParser = new parserFormula( 'XOR(3>0,2<9)', "A2", ws ); ok( oParser.parse(), 'XOR(3>0,2<9)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'XOR(3>0,2<9)' ); oParser = new parserFormula( 'XOR(3>12,4>6)', "A2", ws ); ok( oParser.parse(), 'XOR(3>12,4>6)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'XOR(3>12,4>6)' ); oParser = new parserFormula( 'XOR(3>12,4<6)', "A2", ws ); ok( oParser.parse(), 'XOR(3>12,4<6)' ); strictEqual( oParser.calculate().getValue(), "TRUE", 'XOR(3>12,4<6)' ); //area - specific for xor function //all empty - false result ws.getRange2( "A101" ).setValue( "5" ); ws.getRange2( "A102" ).setValue( "6" ); ws.getRange2( "A103" ).setValue( "test1" ); ws.getRange2( "A104" ).setValue( "" ); ws.getRange2( "A105" ).setValue( "false" ); ws.getRange2( "B101" ).setValue( "1" ); ws.getRange2( "B102" ).setValue( "1" ); ws.getRange2( "B103" ).setValue( "test2" ); ws.getRange2( "B104" ).setValue( "" ); ws.getRange2( "B105" ).setValue( "false" ); ws.getRange2( "B106" ).setValue( "#VALUE!" ); oParser = new parserFormula( 'XOR(A101:B102)', "A2", ws ); ok( oParser.parse(), 'XOR(A101:B102)' ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( 'XOR(A101:B103)', "A2", ws ); ok( oParser.parse(), 'XOR(A101:B103)' ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( 'XOR(A101:A103)', "A2", ws ); ok( oParser.parse(), 'XOR(A101:A103)' ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( 'XOR(A101:A104)', "A2", ws ); ok( oParser.parse(), 'XOR(A101:A104)' ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( 'XOR(A104:B104)', "A2", ws ); ok( oParser.parse(), 'XOR(A104:B104)' ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( 'XOR(A101:B104)', "A2", ws ); ok( oParser.parse(), 'XOR(A101:B104)' ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( 'XOR(A101:B105)', "A2", ws ); ok( oParser.parse(), 'XOR(A101:B105)' ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( 'XOR(A101:A105)', "A2", ws ); ok( oParser.parse(), 'XOR(A101:A105)' ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( 'XOR(B101:A106)', "A2", ws ); ok( oParser.parse(), 'XOR(B101:A106)' ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("XOR", 1, 8, null, true); } ); test( "Test: \"COMBIN\"", function () { oParser = new parserFormula( "COMBIN(8,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 28 ); oParser = new parserFormula( "COMBIN(10,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 210 ); oParser = new parserFormula( "COMBIN(6,5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( "COMBIN(-6,5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "COMBIN(3,5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "COMBIN(6,-5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); } ); test( "Test: \"FACTDOUBLE\"", function () { oParser = new parserFormula( "FACTDOUBLE(8)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 * 4 * 6 * 8 ); oParser = new parserFormula( "FACTDOUBLE(9)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 9 * 7 * 5 * 3 ); oParser = new parserFormula( "FACTDOUBLE(6.5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 * 4 * 2 ); oParser = new parserFormula( "FACTDOUBLE(-6)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "FACTDOUBLE(600)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula("FACTDOUBLE", true); } ); test( "Test: \"FACT\"", function () { oParser = new parserFormula( "FACT(5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 120 ); oParser = new parserFormula( "FACT(1.9)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "FACT(0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "FACT(-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "FACT(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); testArrayFormula("FACT"); } ); test( "Test: \"GCD\"", function () { oParser = new parserFormula( "LCM(5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "LCM(24.6,36.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 72 ); oParser = new parserFormula( "LCM(-1,39,52)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "LCM(0,39,52)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "LCM(24,36,15)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 360 ); testArrayFormula2("LCM", 1, 8, null, true); } ); test( "Test: \"RANDBETWEEN\"", function () { var res; oParser = new parserFormula( "RANDBETWEEN(1,6)", "A1", ws ); ok( oParser.parse() ); res = oParser.calculate().getValue(); ok( res >= 1 && res <= 6 ); oParser = new parserFormula( "RANDBETWEEN(-10,10)", "A1", ws ); ok( oParser.parse() ); res = oParser.calculate().getValue(); ok( res >= -10 && res <= 10 ); oParser = new parserFormula( "RANDBETWEEN(-25,-3)", "A1", ws ); ok( oParser.parse() ); res = oParser.calculate().getValue(); ok( res >= -25 && res <= -3 ); testArrayFormula2("RANDBETWEEN", 2, 2, true) } ); test( "Test: \"QUOTIENT\"", function () { oParser = new parserFormula( "QUOTIENT(1,6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "QUOTIENT(-10,3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -3 ); oParser = new parserFormula( "QUOTIENT(5,3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "QUOTIENT(5,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); testArrayFormula2("QUOTIENT", 2 , 2, true) } ); test( "Test: \"TRUNC\"", function () { oParser = new parserFormula( "TRUNC(PI())", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "TRUNC(PI(),3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3.141 ); oParser = new parserFormula( "TRUNC(PI(),-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "TRUNC(-PI(),2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -3.14 ); oParser = new parserFormula( "TRUNC(8.9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 8 ); oParser = new parserFormula( "TRUNC(-8.9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -8 ); oParser = new parserFormula( "TRUNC(0.45)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "TRUNC(43214)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 43214 ); oParser = new parserFormula( "TRUNC(43214, 10)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 43214 ); oParser = new parserFormula( "TRUNC(43214, -2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 43200 ); oParser = new parserFormula( "TRUNC(43214, -10)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "TRUNC(34123.123, -2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 34100 ); oParser = new parserFormula( "TRUNC(123.23423,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 123.2 ); testArrayFormula2("TRUNC", 1, 2); } ); test( "Test: \"MULTINOMIAL\"", function () { oParser = new parserFormula( "MULTINOMIAL(2,3,4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.fact( 2 + 3 + 4 ) / (Math.fact( 2 ) * Math.fact( 3 ) * Math.fact( 4 )) ); oParser = new parserFormula( "MULTINOMIAL(2,3,\"r\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "MULTINOMIAL(150,50)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("MULTINOMIAL", 1, 8, null, true); } ); test( "Test: \"MUNIT\"", function () { ws.getRange2( "A101" ).setValue( "5" ); ws.getRange2( "B102" ).setValue( "6" ); oParser = new parserFormula( "MUNIT(1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); oParser = new parserFormula( "MUNIT(-1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "MUNIT(1.123)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); oParser = new parserFormula( "MUNIT(2.123)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(1,1).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 0 ); oParser = new parserFormula( "MUNIT(A101)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(1,1).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 0 ); oParser = new parserFormula( "MUNIT(A101:B102)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "MUNIT({0,0;1,2;123,\"sdf\"})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), "#VALUE!" ); strictEqual( oParser.calculate().getElementRowCol(1,1).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(2,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(2,1).getValue(), "#VALUE!" ); oParser = new parserFormula( "MUNIT({12,2})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue(), 1 ); } ); test( "Test: \"SUMSQ\"", function () { oParser = new parserFormula( "SUMSQ(2.5,-3.6,2.4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2.5 * 2.5 + 3.6 * 3.6 + 2.4 * 2.4 ); oParser = new parserFormula( "SUMSQ(2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "SUMSQ(150,50)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 150 * 150 + 50 * 50 ); oParser = new parserFormula( "SUMSQ(150,\"f\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("SUMSQ", 1, 8, null, true); } ); test( "Test: \"ROMAN\"", function () { oParser = new parserFormula( "ROMAN(499,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "CDXCIX" ); oParser = new parserFormula( "ROMAN(499,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "LDVLIV" ); oParser = new parserFormula( "ROMAN(499,2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "XDIX" ); oParser = new parserFormula( "ROMAN(499,3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "VDIV" ); oParser = new parserFormula( "ROMAN(499,4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "ID" ); oParser = new parserFormula( "ROMAN(2013,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "MMXIII" ); oParser = new parserFormula( "ROMAN(2013,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "ROMAN(-2013,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "ROMAN(2499,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "MMLDVLIV" ); oParser = new parserFormula( "ROMAN(499)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "CDXCIX" ); testArrayFormula2("ROMAN", 2, 2); } ); test( "Test: \"SUMXMY2\"", function () { ws.getRange2( "A101" ).setValue( "5" ); ws.getRange2( "A102" ).setValue( "6" ); ws.getRange2( "A103" ).setValue( "test1" ); ws.getRange2( "A104" ).setValue( "" ); ws.getRange2( "A105" ).setValue( "false" ); ws.getRange2( "B101" ).setValue( "1" ); ws.getRange2( "B102" ).setValue( "1" ); ws.getRange2( "B103" ).setValue( "test2" ); ws.getRange2( "B104" ).setValue( "" ); ws.getRange2( "B105" ).setValue( "false" ); oParser = new parserFormula( "SUMXMY2(A101,B101)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 16 ); oParser = new parserFormula( "SUMXMY2(A103,B103)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "SUMXMY2(A101:A102,B101:B102)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 41 ); oParser = new parserFormula( "SUMXMY2(A105,B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "SUMXMY2({2,3,9,1,8,7,5},{6,5,11,7,5,4,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 79 ); oParser = new parserFormula( "SUMXMY2({2,3,9;1,8,7},{6,5,11;7,5,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 78 ); oParser = new parserFormula( "SUMXMY2(7,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); testArrayFormula2("SUMXMY2", 2, 2, null, true) } ); test( "Test: \"SUMX2MY2\"", function () { ws.getRange2( "A101" ).setValue( "5" ); ws.getRange2( "A102" ).setValue( "6" ); ws.getRange2( "A103" ).setValue( "test1" ); ws.getRange2( "A104" ).setValue( "" ); ws.getRange2( "A105" ).setValue( "false" ); ws.getRange2( "B101" ).setValue( "1" ); ws.getRange2( "B102" ).setValue( "1" ); ws.getRange2( "B103" ).setValue( "test2" ); ws.getRange2( "B104" ).setValue( "" ); ws.getRange2( "B105" ).setValue( "false" ); oParser = new parserFormula( "SUMX2MY2({2,3,9,1,8,7,5},{6,5,11,7,5,4,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -55 ); oParser = new parserFormula( "SUMX2MY2({2,3,9;1,8,7},{6,5,11;7,5,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -64 ); oParser = new parserFormula( "SUMX2MY2(7,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 24 ); oParser = new parserFormula( "SUMX2MY2(A101,B101)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 24 ); oParser = new parserFormula( "SUMX2MY2(A103,B103)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "SUMX2MY2(A101:A102,B101:B102)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 59 ); /*oParser = new parserFormula( "SUMX2MY2(A101:A105,B101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 59 );*/ oParser = new parserFormula( "SUMX2MY2(A105,B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("SUMX2MY2", 2, 2, null, true); } ); test( "Test: \"SUMX2PY2\"", function () { ws.getRange2( "A101" ).setValue( "5" ); ws.getRange2( "A102" ).setValue( "6" ); ws.getRange2( "A103" ).setValue( "test1" ); ws.getRange2( "A104" ).setValue( "" ); ws.getRange2( "A105" ).setValue( "false" ); ws.getRange2( "B101" ).setValue( "1" ); ws.getRange2( "B102" ).setValue( "1" ); ws.getRange2( "B103" ).setValue( "test2" ); ws.getRange2( "B104" ).setValue( "" ); ws.getRange2( "B105" ).setValue( "false" ); oParser = new parserFormula( "SUMX2PY2({2,3,9,1,8,7,5},{6,5,11,7,5,4,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 521 ); oParser = new parserFormula( "SUMX2PY2({2,3,9;1,8,7},{6,5,11;7,5,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 480 ); oParser = new parserFormula( "SUMX2PY2(7,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 74 ); oParser = new parserFormula( "SUMX2PY2(A101,B101)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 26 ); oParser = new parserFormula( "SUMX2PY2(A103,B103)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "SUMX2PY2(A101:A102,B101:B102)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 63 ); oParser = new parserFormula( "SUMX2PY2(A105,B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("SUMX2PY2", 2, 2, null, true); } ); test( "Test: \"SERIESSUM\"", function () { ws.getRange2( "A2" ).setValue( "1" ); ws.getRange2( "A3" ).setValue( numDivFact(-1, 2) ); ws.getRange2( "A4" ).setValue( numDivFact(1, 4) ); ws.getRange2( "A5" ).setValue( numDivFact(-1, 6) ); oParser = new parserFormula( "SERIESSUM(PI()/4,0,2,A2:A5)", "A7", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - (1 - 1 / 2 * Math.pow( Math.PI / 4, 2 ) + 1 / Math.fact( 4 ) * Math.pow( Math.PI / 4, 4 ) - 1 / Math.fact( 6 ) * Math.pow( Math.PI / 4, 6 )) ) < dif ); ws.getRange2( "B2" ).setValue( "1" ); ws.getRange2( "B3" ).setValue( numDivFact(-1, 3) ); ws.getRange2( "B4" ).setValue( numDivFact(1, 5) ); ws.getRange2( "B5" ).setValue( numDivFact(-1, 7) ); oParser = new parserFormula( "SERIESSUM(PI()/4,1,2,B2:B5)", "B7", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - (Math.PI / 4 - 1 / Math.fact( 3 ) * Math.pow( Math.PI / 4, 3 ) + 1 / Math.fact( 5 ) * Math.pow( Math.PI / 4, 5 ) - 1 / Math.fact( 7 ) * Math.pow( Math.PI / 4, 7 )) ) < dif ); //TODO нужна другая функция для тестирования //testArrayFormula2("SERIESSUM", 4, 4); } ); /* * Mathematical Function * */ test( "Test: \"CEILING\"", function () { oParser = new parserFormula( "CEILING(2.5,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "CEILING(-2.5,-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -4 ); oParser = new parserFormula( "CEILING(-2.5,2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -2 ); oParser = new parserFormula( "CEILING(1.5,0.1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1.5 ); oParser = new parserFormula( "CEILING(0.234,0.01)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0.24 ); testArrayFormula2("CEILING", 2, 2); } ); test( "Test: \"CELL\"", function () { ws.getRange2( "J2" ).setValue( "1" ); ws.getRange2( "J3" ).setValue( "test" ); ws.getRange2( "J4" ).setValue( "test2" ); oParser = new parserFormula( 'CELL("address",J3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "$J$3" ); oParser = new parserFormula( 'CELL("address",J3:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "$J$3" ); oParser = new parserFormula( 'CELL("col",J3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( 'CELL("col",J3:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( 'CELL("row",J3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( 'CELL("row",J3:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( 'CELL("color",J3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( 'CELL("color",J3:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( 'CELL("contents",J3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "test" ); oParser = new parserFormula( 'CELL("contents",J3:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "test" ); oParser = new parserFormula( 'CELL("contents",J4:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "test2" ); oParser = new parserFormula( 'CELL("contents",J5:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( 'CELL("prefix",J3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "'" ); /*oParser = new parserFormula( 'CELL("prefix",J2)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "" );*/ oParser = new parserFormula( 'CELL("prefix",J6:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "" ); } ); /* * Statistical Function * */ test( "Test: \"AVEDEV\"", function () { oParser = new parserFormula( "AVEDEV(-3.5,1.4,6.9,-4.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4.075 ); oParser = new parserFormula( "AVEDEV({-3.5,1.4,6.9,-4.5})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4.075 ); oParser = new parserFormula( "AVEDEV(-3.5,1.4,6.9,-4.5,-0.3)", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 3.32 ), true ); testArrayFormula2("AVEDEV", 1, 8, null, true); } ); test( "Test: \"AVERAGE\"", function () { oParser = new parserFormula( "AVERAGE(1,2,3,4,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "AVERAGE({1,2;3,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2.5 ); oParser = new parserFormula( "AVERAGE({1,2,3,4,5},6,\"7\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "AVERAGE({1,\"2\",TRUE,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2.5 ); testArrayFormula2("AVERAGE", 1, 8, null, true); } ); test( "Test: \"AVERAGEA\"", function () { ws.getRange2( "E2" ).setValue( "TRUE" ); ws.getRange2( "E3" ).setValue( "FALSE" ); ws.getRange2( "F2" ).setValue( "10" ); ws.getRange2( "F3" ).setValue( "7" ); ws.getRange2( "F4" ).setValue( "9" ); ws.getRange2( "F5" ).setValue( "2" ); ws.getRange2( "F6" ).setValue( "Not available" ); ws.getRange2( "F7" ).setValue( "" ); oParser = new parserFormula( "AVERAGEA(10,E1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( "AVERAGEA(10,E2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5.5 ); oParser = new parserFormula( "AVERAGEA(10,E3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "AVERAGEA(F2:F6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5.6 ); oParser = new parserFormula( "AVERAGEA(F2:F5,F7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); testArrayFormula2("AVERAGEA", 1, 8, null, true); } ); test( "Test: \"AVERAGEIF\"", function () { ws.getRange2( "E2" ).setValue( "10" ); ws.getRange2( "E3" ).setValue( "20" ); ws.getRange2( "E4" ).setValue( "28" ); ws.getRange2( "E5" ).setValue( "30" ); oParser = new parserFormula( "AVERAGEIF(E2:E5,\">15\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 26 ); testArrayFormula2("AVERAGEIF", 2, 3, null, true); } ); test( "Test: \"AVERAGEIFS\"", function () { ws.getRange2( "E2" ).setValue( "Quiz" ); ws.getRange2( "E3" ).setValue( "Grade" ); ws.getRange2( "E4" ).setValue( "75" ); ws.getRange2( "E5" ).setValue( "94" ); ws.getRange2( "F2" ).setValue( "Quiz" ); ws.getRange2( "F3" ).setValue( "Grade" ); ws.getRange2( "F4" ).setValue( "85" ); ws.getRange2( "F5" ).setValue( "80" ); ws.getRange2( "G2" ).setValue( "Exam" ); ws.getRange2( "G3" ).setValue( "Grade" ); ws.getRange2( "G4" ).setValue( "87" ); ws.getRange2( "G5" ).setValue( "88" ); oParser = new parserFormula( "AVERAGEIFS(E2:E5,E2:E5,\">70\",E2:E5,\"<90\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 75 ); oParser = new parserFormula( "AVERAGEIFS(F2:F5,F2:F5,\">95\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "AVERAGEIFS(G2:G5,G2:G5,\"<>Incomplete\",G2:G5,\">80\")", "A3", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 87.5 ); testArrayFormulaEqualsValues("1,3.123,-4,#N/A;2,4,5,#N/A;#N/A,#N/A,#N/A,#N/A", "AVERAGEIFS(A1:C2,A1:C2,A1:C2,A1:C2, A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,#DIV/0!,#DIV/0!,#N/A;#DIV/0!,#DIV/0!,#DIV/0!,#N/A;#N/A,#N/A,#N/A,#N/A", "AVERAGEIFS(A1:C2,A1:C2,A1:A1,A1:C2,A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,#DIV/0!,#DIV/0!,#N/A;2,#DIV/0!,#DIV/0!,#N/A;#N/A,#N/A,#N/A,#N/A", "AVERAGEIFS(A1:C2,A1:C2,A1:A2,A1:C2,A1:C2,A1:C2,A1:C2)"); } ); test( "Test: \"AGGREGATE\"", function () { ws.getRange2( "A101" ).setValue( "TEST" ); ws.getRange2( "A102" ).setValue( "72" ); ws.getRange2( "A103" ).setValue( "30" ); ws.getRange2( "A104" ).setValue( "TEST2" ); ws.getRange2( "A105" ).setValue( "31" ); ws.getRange2( "A106" ).setValue( "96" ); ws.getRange2( "A107" ).setValue( "32" ); ws.getRange2( "A108" ).setValue( "81" ); ws.getRange2( "A109" ).setValue( "33" ); ws.getRange2( "A110" ).setValue( "53" ); ws.getRange2( "A111" ).setValue( "34" ); ws.getRange2( "B101" ).setValue( "82" ); ws.getRange2( "B102" ).setValue( "65" ); ws.getRange2( "B103" ).setValue( "95" ); ws.getRange2( "B104" ).setValue( "63" ); ws.getRange2( "B105" ).setValue( "53" ); ws.getRange2( "B106" ).setValue( "71" ); ws.getRange2( "B107" ).setValue( "55" ); ws.getRange2( "B108" ).setValue( "83" ); ws.getRange2( "B109" ).setValue( "100" ); ws.getRange2( "B110" ).setValue( "91" ); ws.getRange2( "B111" ).setValue( "89" ); oParser = new parserFormula( "AGGREGATE(4, 6, A101:A111)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 96 ); oParser = new parserFormula( "AGGREGATE(14, 6, A101:A111, 3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 72 ); oParser = new parserFormula( "AGGREGATE(15, 6, A101:A111)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "AGGREGATE(12, 6, A101:A111, B101:B111)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 68 ); oParser = new parserFormula( "AGGREGATE(12, 6, A101:A111, B101:B111)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 68 ); oParser = new parserFormula( "AGGREGATE(1,1,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 61.375); oParser = new parserFormula( "AGGREGATE(2,1,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 8); oParser = new parserFormula( "AGGREGATE(3,1,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10); oParser = new parserFormula( "AGGREGATE(4,1,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 95); oParser = new parserFormula( "AGGREGATE(5,3,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30); oParser = new parserFormula( "AGGREGATE(6,1,100)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!"); oParser = new parserFormula( "AGGREGATE(7,3,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 22.87192602); oParser = new parserFormula( "AGGREGATE(8,3,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 21.39472774); oParser = new parserFormula( "AGGREGATE(9,3,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 491); oParser = new parserFormula( "AGGREGATE(10,3,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 523.125); oParser = new parserFormula( "AGGREGATE(11,3,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 457.734375); oParser = new parserFormula( "AGGREGATE(12,3,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 64); oParser = new parserFormula( "AGGREGATE(13,3,A101:B105,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30); oParser = new parserFormula( "AGGREGATE(14,3,A101:B105,2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 82); oParser = new parserFormula( "AGGREGATE(15,3,A101:B105,2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 31); oParser = new parserFormula( "AGGREGATE(16,3,A101:B105,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 95); oParser = new parserFormula( "AGGREGATE(17,3,A101:B105,3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 74.5); oParser = new parserFormula( "AGGREGATE(18,3,A101:B105,0.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30.8); oParser = new parserFormula( "AGGREGATE(19,3,A101:B105,2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 64); } ); test( "Test: \"AND\"", function () { ws.getRange2( "A2" ).setValue( "50" ); ws.getRange2( "A3" ).setValue( "100" ); oParser = new parserFormula( "AND(A2>1,A2<100)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE"); oParser = new parserFormula( 'AND(A2<A3,A2<100)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE"); oParser = new parserFormula( 'AND(A3>1,A3<100)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE"); testArrayFormula2("AND", 1, 8, null, true); } ); test( "Test: \"OR\"", function () { ws.getRange2( "A2" ).setValue( "50" ); ws.getRange2( "A3" ).setValue( "100" ); oParser = new parserFormula( "AND(A2>1,A2<100)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE"); oParser = new parserFormula( 'AND(A2<A3,A2<100)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE"); oParser = new parserFormula( 'AND(A3<1,A3>100)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE"); testArrayFormula2("OR", 1, 8, null, true); } ); test( "Test: \"BINOMDIST\"", function () { function binomdist( x, n, p ) { x = parseInt( x ); n = parseInt( n ); return Math.binomCoeff( n, x ) * Math.pow( p, x ) * Math.pow( 1 - p, n - x ); } oParser = new parserFormula( "BINOMDIST(6,10,0.5,FALSE)", "A1", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - binomdist( 6, 10, 0.5 ) ) < dif ); oParser = new parserFormula( "BINOMDIST(6,10,0.5,TRUE)", "A1", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - (function () { var bm = 0; for ( var y = 0; y <= 6; y++ ) { bm += binomdist( y, 10, 0.5 ) } return bm; })() ) < dif ); oParser = new parserFormula( "BINOMDIST(11,10,0.5,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("BINOMDIST", 4, 4); } ); test( "Test: \"BINOM.DIST\"", function () { ws.getRange2( "A2" ).setValue( "6" ); ws.getRange2( "A3" ).setValue( "10" ); ws.getRange2( "A4" ).setValue( "0.5" ); oParser = new parserFormula( "BINOM.DIST(A2,A3,A4,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 7 ) - 0, 0.2050781); } ); test( "Test: \"BINOM.DIST.RANGE\"", function () { oParser = new parserFormula( "BINOM.DIST.RANGE(60,0.75,48)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 3 ) - 0, 0.084); oParser = new parserFormula( "BINOM.DIST.RANGE(60,0.75,45,50)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 3 ) - 0, 0.524); testArrayFormula2("BINOM.DIST.RANGE", 3, 4); } ); test( "Test: \"CONFIDENCE\"", function () { oParser = new parserFormula( "CONFIDENCE(0.4,5,12)", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 1.214775614397568 ), true ); oParser = new parserFormula( "CONFIDENCE(0.75,9,7)", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 1.083909233527114 ), true ); testArrayFormula2("CONFIDENCE", 3, 3); } ); test( "Test: \"CONFIDENCE.NORM\"", function () { ws.getRange2( "A2" ).setValue( "0.05" ); ws.getRange2( "A3" ).setValue( "2.5" ); ws.getRange2( "A4" ).setValue( "50" ); oParser = new parserFormula( "CONFIDENCE.NORM(A2,A3,A4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 6 ) - 0, 0.692952); } ); test( "Test: \"CONFIDENCE.T\"", function () { oParser = new parserFormula( "CONFIDENCE.T(0.05,1,50)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 9 ) - 0, 0.284196855); testArrayFormula2("CONFIDENCE.T", 3, 3); } ); test( "Test: \"CORREL\"", function () { oParser = new parserFormula( "CORREL({2.532,5.621;2.1,3.4},{5.32,2.765;5.2,\"f\"})", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), -0.988112020032211 ), true ); oParser = new parserFormula( "CORREL({1;2;3},{4;5;\"E\"})", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 1 ), true ); oParser = new parserFormula( "CORREL({1,2},{1,\"e\"})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); testArrayFormula2("CORREL", 2, 2, null, true) } ); test( "Test: \"COUNT\"", function () { ws.getRange2( "E2" ).setValue( "TRUE" ); oParser = new parserFormula( "COUNT({1,2,3,4,5})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "COUNT(1,2,3,4,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "COUNT({1,2,3,4,5},6,\"7\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( "COUNT(10,E150)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNT(10,E2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); ws.getRange2( "S5" ).setValue( "#DIV/0!" ); ws.getRange2( "S6" ).setValue( "TRUE" ); ws.getRange2( "S7" ).setValue( "qwe" ); ws.getRange2( "S8" ).setValue( "" ); ws.getRange2( "S9" ).setValue( "2" ); oParser = new parserFormula( "COUNT(S5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNT(S6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNT(S7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNT(S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNT(S5:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNT(S6:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); testArrayFormula2("COUNT", 2, 2, null, true); } ); test( "Test: \"COUNTA\"", function () { ws.getRange2( "E2" ).setValue( "TRUE" ); oParser = new parserFormula( "COUNTA({1,2,3,4,5})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "COUNTA(1,2,3,4,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "COUNTA({1,2,3,4,5},6,\"7\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( "COUNTA(10,E150)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNTA(10,E2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); ws.getRange2( "S5" ).setValue( "#DIV/0!" ); ws.getRange2( "S6" ).setValue( "TRUE" ); ws.getRange2( "S7" ).setValue( "qwe" ); ws.getRange2( "S8" ).setValue( "" ); ws.getRange2( "S9" ).setValue( "2" ); oParser = new parserFormula( "COUNTA(S5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNTA(S6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNTA(S7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNTA(S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNTA(S5:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "COUNTA(S6:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); } ); test( "Test: \"COUNTIFS\"", function () { ws.getRange2( "A15" ).setValue( "Yes" ); ws.getRange2( "A16" ).setValue( "Yes" ); ws.getRange2( "A17" ).setValue( "Yes" ); ws.getRange2( "A18" ).setValue( "No" ); ws.getRange2( "B15" ).setValue( "No" ); ws.getRange2( "B16" ).setValue( "Yes" ); ws.getRange2( "B17" ).setValue( "Yes" ); ws.getRange2( "B18" ).setValue( "Yes" ); ws.getRange2( "C15" ).setValue( "No" ); ws.getRange2( "C16" ).setValue( "No" ); ws.getRange2( "C17" ).setValue( "Yes" ); ws.getRange2( "C18" ).setValue( "Yes" ); oParser = new parserFormula( "COUNTIFS(A15:C15,\"=Yes\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNTIFS(A15:A18,\"=Yes\",B15:B18,\"=Yes\")", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIFS(A18:C18,\"=Yes\",A16:C16,\"=Yes\")", "C1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); ws.getRange2( "D15" ).setValue( "1" ); ws.getRange2( "D16" ).setValue( "2" ); ws.getRange2( "D17" ).setValue( "3" ); ws.getRange2( "D18" ).setValue( "4" ); ws.getRange2( "D19" ).setValue( "5" ); ws.getRange2( "D20" ).setValue( "6" ); ws.getRange2( "E15" ).setValue( "5/1/2011" ); ws.getRange2( "E16" ).setValue( "5/2/2011" ); ws.getRange2( "E17" ).setValue( "5/3/2011" ); ws.getRange2( "E18" ).setValue( "5/4/2011" ); ws.getRange2( "E19" ).setValue( "5/5/2011" ); ws.getRange2( "E20" ).setValue( "5/6/2011" ); oParser = new parserFormula( "COUNTIFS(D15:D20,\"<6\",D15:D20,\">1\")", "D1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "COUNTIFS(D15:D20,\"<5\",E15:E20,\"<5/3/2011\")", "E1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIFS(D15:D20,\"<\" & D19,E15:E20,\"<\" & E17)", "E1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); testArrayFormulaEqualsValues("1,1,1,#N/A;1,1,1,#N/A;#N/A,#N/A,#N/A,#N/A", "COUNTIFS(A1:C2,A1:C2,A1:C2,A1:C2, A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,0,0,#N/A;1,0,0,#N/A;#N/A,#N/A,#N/A,#N/A", "COUNTIFS(A1:C2,A1:A2,A1:C2,A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("#VALUE!,#VALUE!,#VALUE!,#N/A;#VALUE!,#VALUE!,#VALUE!,#N/A;#N/A,#N/A,#N/A,#N/A", "COUNTIFS(A1:C2,A1:C2,A1:A2,A1:C2,A1:A2,A1:C2)"); } ); test( "Test: \"COUNTIF\"", function () { ws.getRange2( "A7" ).setValue( "3" ); ws.getRange2( "B7" ).setValue( "10" ); ws.getRange2( "C7" ).setValue( "7" ); ws.getRange2( "D7" ).setValue( "10" ); ws.getRange2( "A8" ).setValue( "apples" ); ws.getRange2( "B8" ).setValue( "oranges" ); ws.getRange2( "C8" ).setValue( "grapes" ); ws.getRange2( "D8" ).setValue( "melons" ); oParser = new parserFormula( "COUNTIF(A7:D7,\"=10\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(A7:D7,\">5\")", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "COUNTIF(A7:D7,\"<>10\")", "C1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(A8:D8,\"*es\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "COUNTIF(A8:D8,\"??a*\")", "B2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(A8:D8,\"*l*\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); wb.dependencyFormulas.unlockRecal(); ws.getRange2( "CC1" ).setValue( "1" ); ws.getRange2( "CC2" ).setValue( "0" ); ws.getRange2( "CC3" ).setValue( "1" ); ws.getRange2( "CC4" ).setValue( "true" ); ws.getRange2( "CC5" ).setValue( "=true" ); ws.getRange2( "CC6" ).setValue( "=true()" ); ws.getRange2( "CC7" ).setValue( "'true'" ); ws.getRange2( "CC8" ).setValue( "" ); /*oParser = new parserFormula( "COUNTIF(CC1:CC8,\"<\"&\"F007\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 );*/ oParser = new parserFormula( "COUNTIF(CC1:CC7, TRUE())", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "COUNTIF(CC1:CC7, TRUE)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "COUNTIF(CC1:CC7, 1)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(CC1:CC7, 0)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); ws.getRange2( "CC8" ).setValue( ">3" ); oParser = new parserFormula( "COUNTIF(CC8,\">3\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); ws.getRange2( "CC8" ).setValue( ">3" ); oParser = new parserFormula( "COUNTIF(CC8,\"=>3\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); ws.getRange2( "CC9" ).setValue( "=NA()" ); ws.getRange2( "CC10" ).setValue( "#N/A" ); oParser = new parserFormula( "COUNTIF(CC9:CC10,\"#N/A\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(CC9:CC10, NA())", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(CC9:CC10,\"=NA()\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNTIF(#REF!, 1)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "COUNTIF(CC1:CC8,\">=1\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(CC1:CC8,\"=1\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(CC1:CC8,\"<1\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNTIF(CC1:CC8,\">1\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNTIF(CC1:CC8,\"=\"&CC8)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); wb.dependencyFormulas.lockRecal(); ws.getRange2( "A22" ).setValue( "apples" ); ws.getRange2( "A23" ).setValue( "" ); ws.getRange2( "A24" ).setValue( "oranges" ); ws.getRange2( "A25" ).setValue( "peaches" ); ws.getRange2( "A26" ).setValue( "" ); ws.getRange2( "A27" ).setValue( "apples" ); oParser = new parserFormula( 'COUNTIF(A22:A27,"*es")', "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( 'COUNTIF(A22:A27,"?????es")', "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( 'COUNTIF(A22:A27,"*")', "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( 'COUNTIF(A22:A27,"<>"&"***")', "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( 'COUNTIF(A22:A27,"<>"&"*")', "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( 'COUNTIF(A22:A27,"<>"&"?")', "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); testArrayFormula2("COUNTIF", 2, 2) } ); test( "Test: \"COUNTBLANK\"", function () { ws.getRange2( "A22" ).setValue( "6" ); ws.getRange2( "A23" ).setValue( "" ); ws.getRange2( "A24" ).setValue( "4" ); ws.getRange2( "B22" ).setValue( "" ); ws.getRange2( "B23" ).setValue( "27" ); ws.getRange2( "B24" ).setValue( "34" ); oParser = new parserFormula( "COUNTBLANK(A22:B24)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTBLANK(A22)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNTBLANK(A23)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); } ); test( "Test: \"COVAR\"", function () { oParser = new parserFormula( "COVAR({2.532,5.621;2.1,3.4},{5.32,2.765;5.2,6.7})", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), -1.3753740625 ), true ); oParser = new parserFormula( "COVAR({1,2},{4,5})", "B1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 0.25 ), true ); testArrayFormula2("COVAR", 2, 2, null, true) } ); test( "Test: \"COVARIANCE.P\"", function () { ws.getRange2( "AA1" ).setValue( "3" ); ws.getRange2( "AA2" ).setValue( "2" ); ws.getRange2( "AA4" ).setValue( "4" ); ws.getRange2( "AA5" ).setValue( "5" ); ws.getRange2( "AA6" ).setValue( "6" ); ws.getRange2( "BB1" ).setValue( "9" ); ws.getRange2( "BB2" ).setValue( "7" ); ws.getRange2( "BB4" ).setValue( "12" ); ws.getRange2( "BB5" ).setValue( "15" ); ws.getRange2( "BB6" ).setValue( "17" ); oParser = new parserFormula( "COVARIANCE.P(AA1:AA6, BB1:BB6)", "A1", ws ); ok( oParser.parse() ); strictEqual(oParser.calculate().getValue(), 5.2 ); testArrayFormula2("COVARIANCE.P", 2, 2, null, true); } ); test( "Test: \"COVARIANCE.S\"", function () { ws.getRange2( "AAA1" ).setValue( "2" ); ws.getRange2( "AAA2" ).setValue( "4" ); ws.getRange2( "AAA3" ).setValue( "8" ); ws.getRange2( "BBB1" ).setValue( "5" ); ws.getRange2( "BBB2" ).setValue( "11" ); ws.getRange2( "BBB3" ).setValue( "12" ); oParser = new parserFormula( "COVARIANCE.S({2,4,8},{5,11,12})", "A1", ws ); ok( oParser.parse() ); strictEqual(oParser.calculate().getValue().toFixed(9) - 0, 9.666666667 ); oParser = new parserFormula( "COVARIANCE.S(AAA1:AAA3,BBB1:BBB3)", "A1", ws ); ok( oParser.parse() ); strictEqual(oParser.calculate().getValue().toFixed(9) - 0, 9.666666667 ); testArrayFormula2("COVARIANCE.S", 2, 2, null, true); } ); test( "Test: \"CRITBINOM\"", function () { oParser = new parserFormula( "CRITBINOM(6,0.5,0.75)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "CRITBINOM(12,0.3,0.95)", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( "CRITBINOM(-12,0.3,0.95)", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "CRITBINOM(-12,1.3,0.95)", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "CRITBINOM(-12,-1.3,0.95)", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "CRITBINOM(-12,0,0.95)", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "CRITBINOM(-12,0.3,1.95)", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("CRITBINOM", 3, 3); } ); test( "Test: \"CONCAT\"", function () { ws.getRange2( "AA1" ).setValue( "a1" ); ws.getRange2( "AA2" ).setValue( "a2" ); ws.getRange2( "AA4" ).setValue( "a4" ); ws.getRange2( "AA5" ).setValue( "a5" ); ws.getRange2( "AA6" ).setValue( "a6" ); ws.getRange2( "AA7" ).setValue( "a7" ); ws.getRange2( "BB1" ).setValue( "b1" ); ws.getRange2( "BB2" ).setValue( "b2" ); ws.getRange2( "BB4" ).setValue( "b4" ); ws.getRange2( "BB5" ).setValue( "b5" ); ws.getRange2( "BB6" ).setValue( "b6" ); ws.getRange2( "BB7" ).setValue( "b7" ); oParser = new parserFormula('CONCAT("The"," ","sun"," ","will"," ","come"," ","up"," ","tomorrow.")', "A3", ws); ok(oParser.parse(), "CONCAT(AA:AA, BB:BB)"); strictEqual(oParser.calculate().getValue(), "The sun will come up tomorrow.", "CONCAT(AA:AA, BB:BB)"); oParser = new parserFormula("CONCAT(AA:AA, BB:BB)", "A3", ws); ok(oParser.parse(), "CONCAT(AA:AA, BB:BB)"); strictEqual(oParser.calculate().getValue(), "a1a2a4a5a6a7b1b2b4b5b6b7", "CONCAT(AA:AA, BB:BB)"); oParser = new parserFormula("CONCAT(AA1:BB7)", "A3", ws); ok(oParser.parse(), "CONCAT(AA1:BB7)"); strictEqual(oParser.calculate().getValue(), "a1b1a2b2a4b4a5b5a6b6a7b7", "CONCAT(AA1:BB7)"); oParser = new parserFormula( 'CONCAT(TRUE,"test")', "A2", ws ); ok( oParser.parse(), 'CONCAT(TRUE,"test")' ); strictEqual( oParser.calculate().getValue(), "TRUEtest", 'CONCAT(TRUE,"test")'); testArrayFormulaEqualsValues("13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245;13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245;13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245", "CONCAT(A1:C2,A1:C2,A1:C2)") }); test( "Test: \"CONCATENATE\"", function () { ws.getRange2( "AA2" ).setValue( "brook trout" ); ws.getRange2( "AA3" ).setValue( "species" ); ws.getRange2( "AA4" ).setValue( "32" ); ws.getRange2( "AB2" ).setValue( "Andreas" ); ws.getRange2( "AB3" ).setValue( "Fourth" ); ws.getRange2( "AC2" ).setValue( "Hauser" ); ws.getRange2( "AC3" ).setValue( "Pine" ); oParser = new parserFormula( 'CONCATENATE("Stream population for ", AA2, " ", AA3, " is ", AA4, "/mile.")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Stream population for brook trout species is 32/mile." ); oParser = new parserFormula( 'CONCATENATE(AB2, " ", AC2)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Andreas Hauser" ); oParser = new parserFormula( 'CONCATENATE(AC2, ", ", AB2)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Hauser, Andreas" ); oParser = new parserFormula( 'CONCATENATE(AB3, " & ", AC3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Fourth & Pine" ); oParser = new parserFormula( 'CONCATENATE(TRUE,"test")', "A2", ws ); ok( oParser.parse(), 'CONCATENATE(TRUE,"test")' ); strictEqual( oParser.calculate().getValue(), "TRUEtest", 'CONCATENATE(TRUE,"test")'); testArrayFormula2("CONCATENATE", 1, 8); }); test( "Test: \"DEVSQ\"", function () { ws.getRange2( "A1" ).setValue( "5.6" ); ws.getRange2( "A2" ).setValue( "8.2" ); ws.getRange2( "A3" ).setValue( "9.2" ); oParser = new parserFormula( "DEVSQ(5.6,8.2,9.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 6.906666666666665 ), true ); oParser = new parserFormula( "DEVSQ({5.6,8.2,9.2})", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 6.906666666666665 ), true ); oParser = new parserFormula( "DEVSQ(5.6,8.2,\"9.2\")", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 3.379999999999999 ), true ); oParser = new parserFormula( "DEVSQ(" + ws.getName() + "!A1:A3)", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 6.906666666666665 ), true ); testArrayFormula2("DEVSQ", 1, 8, null, true); } ); test( "Test: \"EXPONDIST\"", function () { oParser = new parserFormula( "EXPONDIST(0.2,10,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 1.353352832366127 ), true ); oParser = new parserFormula( "EXPONDIST(2.3,1.5,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 0.968254363621932 ), true ); testArrayFormula2("EXPONDIST", 3, 3); } ); test( "Test: \"SIN(3.1415926)\"", function () { oParser = new parserFormula( 'SIN(3.1415926)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.sin( 3.1415926 ) ); testArrayFormula("SIN"); } ); test( "Test: \"EXP\"", function () { oParser = new parserFormula( "EXP(1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 2.71828183 ); oParser = new parserFormula( "EXP(2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 7.3890561 ); testArrayFormula("EXP"); } ); test( "Test: \"FISHER\"", function () { function fisher( x ) { return toFixed( 0.5 * Math.ln( (1 + x) / (1 - x) ) ); } oParser = new parserFormula( "FISHER(-0.43)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fisher( -.43 ) ); oParser = new parserFormula( "FISHER(0.578)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fisher( 0.578 ) ); oParser = new parserFormula( "FISHER(1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "FISHER(-1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula("FISHER"); } ); test( "Test: \"FISHERINV\"", function () { function fisherInv( x ) { return toFixed( ( Math.exp( 2 * x ) - 1 ) / ( Math.exp( 2 * x ) + 1 ) ); } oParser = new parserFormula( "FISHERINV(-0.43)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fisherInv( -.43 ) ); oParser = new parserFormula( "FISHERINV(0.578)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fisherInv( 0.578 ) ); oParser = new parserFormula( "FISHERINV(1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fisherInv( 1 ) ); oParser = new parserFormula( "FISHERINV(-1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fisherInv( -1 ) ); testArrayFormula("FISHERINV"); } ); test( "Test: \"FORECAST\"", function () { function forecast( fx, y, x ) { var fSumDeltaXDeltaY = 0, fSumSqrDeltaX = 0, _x = 0, _y = 0, xLength = 0; for ( var i = 0; i < x.length; i++ ) { _x += x[i]; _y += y[i]; xLength++; } _x /= xLength; _y /= xLength; for ( var i = 0; i < x.length; i++ ) { var fValX = x[i]; var fValY = y[i]; fSumDeltaXDeltaY += ( fValX - _x ) * ( fValY - _y ); fSumSqrDeltaX += ( fValX - _x ) * ( fValX - _x ); } return toFixed( _y + fSumDeltaXDeltaY / fSumSqrDeltaX * ( fx - _x ) ); } oParser = new parserFormula( "FORECAST(30,{6,7,9,15,21},{20,28,31,38,40})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), forecast( 30, [6, 7, 9, 15, 21], [20, 28, 31, 38, 40] ) ); } ); function putDataForForecastEts(){ ws.getRange2( 'A4' ).setValue( '39814' ); ws.getRange2( 'A5' ).setValue( '39845' ); ws.getRange2( 'A6' ).setValue( '39873' ); ws.getRange2( 'A7' ).setValue( '39904' ); ws.getRange2( 'A8' ).setValue( '39934' ); ws.getRange2( 'A9' ).setValue( '39965' ); ws.getRange2( 'A10' ).setValue( '39995' ); ws.getRange2( 'A11' ).setValue( '40026' ); ws.getRange2( 'A12' ).setValue( '40057' ); ws.getRange2( 'A13' ).setValue( '40087' ); ws.getRange2( 'A14' ).setValue( '40118' ); ws.getRange2( 'A15' ).setValue( '40148' ); ws.getRange2( 'A16' ).setValue( '40179' ); ws.getRange2( 'A17' ).setValue( '40210' ); ws.getRange2( 'A18' ).setValue( '40238' ); ws.getRange2( 'A19' ).setValue( '40269' ); ws.getRange2( 'A20' ).setValue( '40299' ); ws.getRange2( 'A21' ).setValue( '40330' ); ws.getRange2( 'A22' ).setValue( '40360' ); ws.getRange2( 'A23' ).setValue( '40391' ); ws.getRange2( 'A24' ).setValue( '40422' ); ws.getRange2( 'A25' ).setValue( '40452' ); ws.getRange2( 'A26' ).setValue( '40483' ); ws.getRange2( 'A27' ).setValue( '40513' ); ws.getRange2( 'A28' ).setValue( '40544' ); ws.getRange2( 'A29' ).setValue( '40575' ); ws.getRange2( 'A30' ).setValue( '40603' ); ws.getRange2( 'A31' ).setValue( '40634' ); ws.getRange2( 'A32' ).setValue( '40664' ); ws.getRange2( 'A33' ).setValue( '40695' ); ws.getRange2( 'A34' ).setValue( '40725' ); ws.getRange2( 'A35' ).setValue( '40756' ); ws.getRange2( 'A36' ).setValue( '40787' ); ws.getRange2( 'A37' ).setValue( '40817' ); ws.getRange2( 'A38' ).setValue( '40848' ); ws.getRange2( 'A39' ).setValue( '40878' ); ws.getRange2( 'A40' ).setValue( '40909' ); ws.getRange2( 'A41' ).setValue( '40940' ); ws.getRange2( 'A42' ).setValue( '40969' ); ws.getRange2( 'A43' ).setValue( '41000' ); ws.getRange2( 'A44' ).setValue( '41030' ); ws.getRange2( 'A45' ).setValue( '41061' ); ws.getRange2( 'A46' ).setValue( '41091' ); ws.getRange2( 'A47' ).setValue( '41122' ); ws.getRange2( 'A48' ).setValue( '41153' ); ws.getRange2( 'A49' ).setValue( '41183' ); ws.getRange2( 'A50' ).setValue( '41214' ); ws.getRange2( 'A51' ).setValue( '41244' ); ws.getRange2( 'A52' ).setValue( '41275' ); ws.getRange2( 'A53' ).setValue( '41306' ); ws.getRange2( 'A54' ).setValue( '41334' ); ws.getRange2( 'A55' ).setValue( '41365' ); ws.getRange2( 'A56' ).setValue( '41395' ); ws.getRange2( 'A57' ).setValue( '41426' ); ws.getRange2( 'A58' ).setValue( '41456' ); ws.getRange2( 'A59' ).setValue( '41487' ); ws.getRange2( 'A60' ).setValue( '41518' ); ws.getRange2( 'B4' ).setValue( '2644539' ); ws.getRange2( 'B5' ).setValue( '2359800' ); ws.getRange2( 'B6' ).setValue( '2925918' ); ws.getRange2( 'B7' ).setValue( '3024973' ); ws.getRange2( 'B8' ).setValue( '3177100' ); ws.getRange2( 'B9' ).setValue( '3419595' ); ws.getRange2( 'B10' ).setValue( '3649702' ); ws.getRange2( 'B11' ).setValue( '3650668' ); ws.getRange2( 'B12' ).setValue( '3191526' ); ws.getRange2( 'B13' ).setValue( '3249428' ); ws.getRange2( 'B14' ).setValue( '2971484' ); ws.getRange2( 'B15' ).setValue( '3074209' ); ws.getRange2( 'B16' ).setValue( '2785466' ); ws.getRange2( 'B17' ).setValue( '2515361' ); ws.getRange2( 'B18' ).setValue( '3105958' ); ws.getRange2( 'B19' ).setValue( '3139059' ); ws.getRange2( 'B20' ).setValue( '3380355' ); ws.getRange2( 'B21' ).setValue( '3612886' ); ws.getRange2( 'B22' ).setValue( '3765824' ); ws.getRange2( 'B23' ).setValue( '3771842' ); ws.getRange2( 'B24' ).setValue( '3356365' ); ws.getRange2( 'B25' ).setValue( '3490100' ); ws.getRange2( 'B26' ).setValue( '3163659' ); ws.getRange2( 'B27' ).setValue( '3167124' ); ws.getRange2( 'B28' ).setValue( '2883810' ); ws.getRange2( 'B29' ).setValue( '2610667' ); ws.getRange2( 'B30' ).setValue( '3129205' ); ws.getRange2( 'B31' ).setValue( '3200527' ); ws.getRange2( 'B32' ).setValue( '3547804' ); ws.getRange2( 'B33' ).setValue( '3766323' ); ws.getRange2( 'B34' ).setValue( '3935589' ); ws.getRange2( 'B35' ).setValue( '3917884' ); ws.getRange2( 'B36' ).setValue( '3564970' ); ws.getRange2( 'B37' ).setValue( '3602455' ); ws.getRange2( 'B38' ).setValue( '3326859' ); ws.getRange2( 'B39' ).setValue( '3441693' ); ws.getRange2( 'B40' ).setValue( '3211600' ); ws.getRange2( 'B41' ).setValue( '2998119' ); ws.getRange2( 'B42' ).setValue( '3472440' ); ws.getRange2( 'B43' ).setValue( '3563007' ); ws.getRange2( 'B44' ).setValue( '3820570' ); ws.getRange2( 'B45' ).setValue( '4107195' ); ws.getRange2( 'B46' ).setValue( '4284443' ); ws.getRange2( 'B47' ).setValue( '4356216' ); ws.getRange2( 'B48' ).setValue( '3819379' ); ws.getRange2( 'B49' ).setValue( '3844987' ); ws.getRange2( 'B50' ).setValue( '3478890' ); ws.getRange2( 'B51' ).setValue( '3443039' ); ws.getRange2( 'B52' ).setValue( '3204637' ); ws.getRange2( 'B53' ).setValue( '2966477' ); ws.getRange2( 'B54' ).setValue( '3593364' ); ws.getRange2( 'B55' ).setValue( '3604104' ); ws.getRange2( 'B56' ).setValue( '3933016' ); ws.getRange2( 'B57' ).setValue( '4146797' ); ws.getRange2( 'B58' ).setValue( '4176486' ); ws.getRange2( 'B59' ).setValue( '4347059' ); ws.getRange2( 'B60' ).setValue( '3781168' ); ws.getRange2( 'A61' ).setValue( '41548' ); ws.getRange2( 'A62' ).setValue( '41579' ); ws.getRange2( 'A63' ).setValue( '41609' ); ws.getRange2( 'A64' ).setValue( '41640' ); ws.getRange2( 'A65' ).setValue( '41671' ); ws.getRange2( 'A66' ).setValue( '41699' ); ws.getRange2( 'A67' ).setValue( '41730' ); ws.getRange2( 'A68' ).setValue( '41760' ); ws.getRange2( 'A69' ).setValue( '41791' ); ws.getRange2( 'A70' ).setValue( '41821' ); ws.getRange2( 'A71' ).setValue( '41852' ); ws.getRange2( 'A72' ).setValue( '41883' ); ws.getRange2( 'A73' ).setValue( '41913' ); ws.getRange2( 'A74' ).setValue( '41944' ); ws.getRange2( 'A75' ).setValue( '41974' ); ws.getRange2( 'A76' ).setValue( '42005' ); ws.getRange2( 'A77' ).setValue( '42036' ); ws.getRange2( 'A78' ).setValue( '42064' ); ws.getRange2( 'A79' ).setValue( '42095' ); ws.getRange2( 'A80' ).setValue( '42125' ); ws.getRange2( 'A81' ).setValue( '42156' ); ws.getRange2( 'A82' ).setValue( '42186' ); ws.getRange2( 'A83' ).setValue( '42217' ); ws.getRange2( 'A84' ).setValue( '42248' ); } test( "Test: \"FORECAST.ETS\"", function () { //результаты данного теста соответсвуют результатам LO, но отличаются от MS!!! putDataForForecastEts(); oParser = new parserFormula( "FORECAST.ETS(A61,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3868499.49723621); oParser = new parserFormula( "FORECAST.ETS(A62,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3560200.99816396); oParser = new parserFormula( "FORECAST.ETS(A63,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3619491.6524986); oParser = new parserFormula( "FORECAST.ETS(A64,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3397521.44972895); oParser = new parserFormula( "FORECAST.ETS(A65,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3152698.4854144); oParser = new parserFormula( "FORECAST.ETS(A66,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3704079.5812005); oParser = new parserFormula( "FORECAST.ETS(A67,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3747546.50043675); oParser = new parserFormula( "FORECAST.ETS(A68,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4042011.75785885); oParser = new parserFormula( "FORECAST.ETS(A69,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4250095.33429725); oParser = new parserFormula( "FORECAST.ETS(A70,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4360538.1411926); oParser = new parserFormula( "FORECAST.ETS(A71,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4463640.2710391); oParser = new parserFormula( "FORECAST.ETS(A72,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3963675.88150212); oParser = new parserFormula( "FORECAST.ETS(A73,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4028087.58056954); oParser = new parserFormula( "FORECAST.ETS(A74,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3719789.0814973); oParser = new parserFormula( "FORECAST.ETS(A75,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3779079.73583193); oParser = new parserFormula( "FORECAST.ETS(A76,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3557109.53306228); oParser = new parserFormula( "FORECAST.ETS(A77,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3312286.56874774); oParser = new parserFormula( "FORECAST.ETS(A78,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3863667.66453383); oParser = new parserFormula( "FORECAST.ETS(A79,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3907134.58377009); oParser = new parserFormula( "FORECAST.ETS(A80,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4201599.84119218); oParser = new parserFormula( "FORECAST.ETS(A81,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4409683.41763059); oParser = new parserFormula( "FORECAST.ETS(A82,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4520126.22452593); oParser = new parserFormula( "FORECAST.ETS(A83,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4623228.35437243); oParser = new parserFormula( "FORECAST.ETS(A84,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4123263.96483545); } ); test( "Test: \"FORECAST.ETS.SEASONALITY\"", function () { //результаты данного теста соответсвуют результатам LO, но отличаются от MS!!! putDataForForecastEts(); oParser = new parserFormula("FORECAST.ETS.SEASONALITY(B4:B60,A4:A60,1,1)", "A1", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 12); } ); test( "Test: \"FORECAST.ETS.STAT\"", function () { //результаты данного теста соответсвуют результатам LO, но отличаются от MS!!! putDataForForecastEts(); oParser = new parserFormula("FORECAST.ETS.STAT(B4:B60,A4:A60,1,1)", "A1", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue().toFixed( 8 ) - 0, 0.65234375); } ); test( "Test: \"FORECAST.LINEAR\"", function () { oParser = new parserFormula( "FORECAST(30,{6,7,9,15,21},{20,28,31,38,40})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 13 ) - 0, 10.6072530864198); } ); test( "FORMULATEXT", function () { wb.dependencyFormulas.unlockRecal(); ws.getRange2( "S101" ).setValue( "=TODAY()" ); ws.getRange2( "S102" ).setValue( "" ); ws.getRange2( "S103" ).setValue( "=1+1" ); oParser = new parserFormula( "FORMULATEXT(S101)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "=TODAY()" ); oParser = new parserFormula( "FORMULATEXT(S101:S102)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "=TODAY()" ); oParser = new parserFormula( "FORMULATEXT(S102)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "FORMULATEXT(S100:105)", "A1", ws ); ok( oParser.parse() ); //"#N/A" - в ms excel strictEqual( oParser.calculate().getValue(), newFormulaParser ? "#N/A" : "#VALUE!"); oParser = new parserFormula( "FORMULATEXT(S103)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "=1+1" ); oParser = new parserFormula( "FORMULATEXT(#REF!)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); wb.dependencyFormulas.lockRecal(); testArrayFormulaEqualsValues("#N/A,#N/A,#N/A,#N/A;#N/A,#N/A,#N/A,#N/A;#N/A,#N/A,#N/A,#N/A", "FORMULATEXT(A1:C2)"); } ); test( "Test: \"FREQUENCY\"", function () { ws.getRange2( "A202" ).setValue( "79" ); ws.getRange2( "A203" ).setValue( "85" ); ws.getRange2( "A204" ).setValue( "78" ); ws.getRange2( "A205" ).setValue( "85" ); ws.getRange2( "A206" ).setValue( "50" ); ws.getRange2( "A207" ).setValue( "81" ); ws.getRange2( "A208" ).setValue( "95" ); ws.getRange2( "A209" ).setValue( "88" ); ws.getRange2( "A210" ).setValue( "97" ); ws.getRange2( "B202" ).setValue( "70" ); ws.getRange2( "B203" ).setValue( "89" ); ws.getRange2( "B204" ).setValue( "79" ); oParser = new parserFormula( "FREQUENCY(A202:A210,B202:B204)", "A201", ws ); ok( oParser.parse() ); var a = oParser.calculate(); strictEqual( a.getElement( 0 ).getValue(), 1 ); strictEqual( a.getElement( 1 ).getValue(), 2 ); strictEqual( a.getElement( 2 ).getValue(), 4 ); strictEqual( a.getElement( 3 ).getValue(), 2 ); } ); test( "Test: \"GAMMALN\"", function () { oParser = new parserFormula( "GAMMALN(4.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 14 ) - 0, 2.45373657084244 ); oParser = new parserFormula( "GAMMALN(-4.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula("GAMMALN"); } ); test( "Test: \"GAMMALN.PRECISE\"", function () { oParser = new parserFormula( "GAMMALN.PRECISE(4)", "A1", ws ); ok( oParser.parse(), "GAMMALN.PRECISE(4)" ); strictEqual( oParser.calculate().getValue().toFixed( 7 ) - 0, 1.7917595, "GAMMALN.PRECISE(4)" ); oParser = new parserFormula( "GAMMALN.PRECISE(-4.5)", "A1", ws ); ok( oParser.parse(), "GAMMALN.PRECISE(-4.5)" ); strictEqual( oParser.calculate().getValue(), "#NUM!", "GAMMALN.PRECISE(-4.5)" ); testArrayFormula2("GAMMALN.PRECISE", 1, 1); } ); test( "Test: \"GEOMEAN\"", function () { function geommean( x ) { var s1 = 0, _x = 1, xLength = 0, _tx; for ( var i = 0; i < x.length; i++ ) { _x *= x[i]; } return Math.pow( _x, 1 / x.length ) } oParser = new parserFormula( "GEOMEAN(10.5,5.3,2.9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), geommean( [10.5, 5.3, 2.9] ) ); oParser = new parserFormula( "GEOMEAN(10.5,{5.3,2.9},\"12\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), geommean( [10.5, 5.3, 2.9, 12] ) ); oParser = new parserFormula( "GEOMEAN(10.5,{5.3,2.9},\"12\",0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); } ); test( "Test: \"HARMEAN\"", function () { function harmmean( x ) { var _x = 0, xLength = 0; for ( var i = 0; i < x.length; i++ ) { _x += 1 / x[i]; xLength++; } return xLength / _x; } oParser = new parserFormula( "HARMEAN(10.5,5.3,2.9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), harmmean( [10.5, 5.3, 2.9] ) ); oParser = new parserFormula( "HARMEAN(10.5,{5.3,2.9},\"12\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), harmmean( [10.5, 5.3, 2.9, 12] ) ); oParser = new parserFormula( "HARMEAN(10.5,{5.3,2.9},\"12\",0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("HARMEAN", 1, 8, null, true); } ); test( "Test: \"HYPGEOMDIST\"", function () { function hypgeomdist( x, n, M, N ) { return toFixed( Math.binomCoeff( M, x ) * Math.binomCoeff( N - M, n - x ) / Math.binomCoeff( N, n ) ); } oParser = new parserFormula( "HYPGEOMDIST(1,4,8,20)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), hypgeomdist( 1, 4, 8, 20 ) ); oParser = new parserFormula( "HYPGEOMDIST(1,4,8,20)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), hypgeomdist( 1, 4, 8, 20 ) ); oParser = new parserFormula( "HYPGEOMDIST(-1,4,8,20)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "HYPGEOMDIST(5,4,8,20)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("HYPGEOMDIST", 4, 4); } ); test( "Test: \"HYPGEOM.DIST\"", function () { oParser = new parserFormula( "HYPGEOM.DIST(1,4,8,20,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(4) - 0, 0.4654 ); oParser = new parserFormula( "HYPGEOM.DIST(1,4,8,20,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(4) - 0, 0.3633 ); oParser = new parserFormula( "HYPGEOM.DIST(2,2,3,40,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.003846154); oParser = new parserFormula( "HYPGEOM.DIST(2,3,3,40,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.999898785); oParser = new parserFormula( "HYPGEOM.DIST(1,2,3,4,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue() - 0, 0.5); testArrayFormula2("HYPGEOM.DIST", 5, 5); } ); test( "Test: \"HYPLINK\"", function () { ws.getRange2( "D101" ).setValue( "" ); ws.getRange2( "D102" ).setValue( "123" ); oParser = new parserFormula( 'HYPERLINK("http://example.microsoft.com/report/budget report.xlsx", "Click for report")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Click for report" ); strictEqual( oParser.value.hyperlink, "http://example.microsoft.com/report/budget report.xlsx" ); oParser = new parserFormula( 'HYPERLINK("[http://example.microsoft.com/report/budget report.xlsx]Annual!F10", D1)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue() - 0, 0 ); strictEqual( oParser.value.hyperlink, "[http://example.microsoft.com/report/budget report.xlsx]Annual!F10" ); oParser = new parserFormula( 'HYPERLINK("http://example.microsoft.com/Annual Report.docx]QrtlyProfits", "Quarterly Profit Report")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Quarterly Profit Report" ); strictEqual( oParser.value.hyperlink, 'http://example.microsoft.com/Annual Report.docx]QrtlyProfits' ); oParser = new parserFormula( 'HYPERLINK("\\FINANCE\Statements\1stqtr.xlsx",D101)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue() - 0, 0 ); strictEqual( oParser.value.hyperlink, '\\FINANCE\Statements\1stqtr.xlsx' ); oParser = new parserFormula( 'HYPERLINK("http://test.com")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "http://test.com" ); strictEqual( oParser.value.hyperlink, "http://test.com" ); oParser = new parserFormula( 'HYPERLINK(D101,111)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 111 ); strictEqual( oParser.value.hyperlink - 0, 0 ); oParser = new parserFormula( 'HYPERLINK(D102,111)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 111 ); strictEqual( oParser.value.hyperlink, "123" ); oParser = new parserFormula( 'HYPERLINK(D102)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "123" ); strictEqual( oParser.value.hyperlink - 0, 123 ); oParser = new parserFormula( 'HYPERLINK(D101,TRUE)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); strictEqual( oParser.value.hyperlink - 0, 0 ); } ); test( "Test: \"HOUR\"", function () { ws.getRange2( "A202" ).setValue( "0.75" ); ws.getRange2( "A203" ).setValue( "7/18/2011 7:45" ); ws.getRange2( "A204" ).setValue( "4/21/2012" ); oParser = new parserFormula( "HOUR(A202)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 18 ); oParser = new parserFormula( "HOUR(A203)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( "HOUR(A204)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); testArrayFormula2("HOUR", 1, 1); } ); test( "Test: \"INTERCEPT\"", function () { function intercept( y, x ) { var fSumDeltaXDeltaY = 0, fSumSqrDeltaX = 0, _x = 0, _y = 0, xLength = 0; for ( var i = 0; i < x.length; i++ ) { _x += x[i]; _y += y[i]; xLength++; } _x /= xLength; _y /= xLength; for ( var i = 0; i < x.length; i++ ) { var fValX = x[i]; var fValY = y[i]; fSumDeltaXDeltaY += ( fValX - _x ) * ( fValY - _y ); fSumSqrDeltaX += ( fValX - _x ) * ( fValX - _x ); } return toFixed( _y - fSumDeltaXDeltaY / fSumSqrDeltaX * _x ); } oParser = new parserFormula( "INTERCEPT({6,7,9,15,21},{20,28,31,38,40})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), intercept( [6, 7, 9, 15, 21], [20, 28, 31, 38, 40] ) ); testArrayFormula2("INTERCEPT", 2, 2, null, true); } ); test( "Test: \"INT\"", function () { ws.getRange2( "A202" ).setValue( "19.5" ); oParser = new parserFormula( "INT(8.9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 8 ); oParser = new parserFormula( "INT(-8.9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -9 ); oParser = new parserFormula( "A202-INT(A202)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0.5 ); testArrayFormula("INT"); } ); test( "Test: \"KURT\"", function () { function kurt( x ) { var sumSQRDeltaX = 0, _x = 0, xLength = 0, standDev = 0, sumSQRDeltaXDivstandDev = 0; for ( var i = 0; i < x.length; i++ ) { _x += x[i]; xLength++; } _x /= xLength; for ( var i = 0; i < x.length; i++ ) { sumSQRDeltaX += Math.pow( x[i] - _x, 2 ); } standDev = Math.sqrt( sumSQRDeltaX / ( xLength - 1 ) ); for ( var i = 0; i < x.length; i++ ) { sumSQRDeltaXDivstandDev += Math.pow( (x[i] - _x) / standDev, 4 ); } return toFixed( xLength * (xLength + 1) / (xLength - 1) / (xLength - 2) / (xLength - 3) * sumSQRDeltaXDivstandDev - 3 * (xLength - 1) * (xLength - 1) / (xLength - 2) / (xLength - 3) ) } oParser = new parserFormula( "KURT(10.5,12.4,19.4,23.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), kurt( [10.5, 12.4, 19.4, 23.2] ) ); oParser = new parserFormula( "KURT(10.5,{12.4,19.4},23.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), kurt( [10.5, 12.4, 19.4, 23.2] ) ); oParser = new parserFormula( "KURT(10.5,12.4,19.4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("KURT", 1, 8, null, true); } ); test( "Test: \"LARGE\"", function () { oParser = new parserFormula( "LARGE({3,5,3,5,4;4,2,4,6,7},3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "LARGE({3,5,3,5,4;4,2,4,6,7},7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); //TODO нужна другая функция для тестирования //testArrayFormula2("LARGE", 2, 2) } ); test( "Test: \"LN\"", function () { oParser = new parserFormula( "LN(86)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 4.4543473 ); oParser = new parserFormula( "LN(2.7182818)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(1) - 0, 1 ); oParser = new parserFormula( "LN(EXP(3))", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); testArrayFormula("LN"); } ); test( "Test: \"LOG10\"", function () { oParser = new parserFormula( "LOG10(86)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(4) - 0, 1.9345 ); oParser = new parserFormula( "LOG10(10)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "LOG10(100000)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "LOG10(10^5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); testArrayFormula("LOG10"); } ); test( "Test: \"LINEST\"", function () { ws.getRange2( "A202" ).setValue( "1" ); ws.getRange2( "A203" ).setValue( "2" ); ws.getRange2( "A204" ).setValue( "3" ); ws.getRange2( "B202" ).setValue( "2" ); ws.getRange2( "B203" ).setValue( "3" ); ws.getRange2( "B204" ).setValue( "4" ); oParser = new parserFormula( "LINEST(A202:B204)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 0.54285714); oParser = new parserFormula( "LINEST(A202:B204, A202:B204)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1); oParser = new parserFormula( "LINEST(A202:B204, A202:B204, 1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1); oParser = new parserFormula( "LINEST(A202:B204, A202:B204, 1, 1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1); ws.getRange2( "A202" ).setValue( "1" ); ws.getRange2( "A203" ).setValue( "9" ); ws.getRange2( "A204" ).setValue( "5" ); ws.getRange2( "A205" ).setValue( "7" ); ws.getRange2( "B202" ).setValue( "0" ); ws.getRange2( "B203" ).setValue( "4" ); ws.getRange2( "B204" ).setValue( "2" ); ws.getRange2( "B205" ).setValue( "3" ); oParser = new parserFormula( "LINEST(A202:A205,B202:B205,,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 2); oParser = new parserFormula( "LINEST(A202:A205,B202:B205,FALSE,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 2.31034483); oParser = new parserFormula( "LINEST(A202:A205,B202:B205,FALSE,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 2.31034483); ws.getRange2( "A102" ).setValue( "1" ); ws.getRange2( "A103" ).setValue( "9" ); ws.getRange2( "A104" ).setValue( "5" ); ws.getRange2( "A105" ).setValue( "7" ); ws.getRange2( "B102" ).setValue( "0" ); ws.getRange2( "B103" ).setValue( "4" ); ws.getRange2( "B104" ).setValue( "2" ); ws.getRange2( "B105" ).setValue( "3" ); oParser = new parserFormula( "LINEST(A102:A105,B102:B105,,FALSE)", "A1", ws ); oParser.setArrayFormulaRef(ws.getRange2("E106:F106").bbox); ok( oParser.parse() ); var array = oParser.calculate(); if(AscCommonExcel.cElementType.array === array.type) { strictEqual( array.getElementRowCol(0,0).getValue(), 2); strictEqual( array.getElementRowCol(0,1).getValue(), 1); } ws.getRange2( "A102" ).setValue( "2310" ); ws.getRange2( "A103" ).setValue( "2333" ); ws.getRange2( "A104" ).setValue( "2356" ); ws.getRange2( "A105" ).setValue( "2379" ); ws.getRange2( "A106" ).setValue( "2402" ); ws.getRange2( "A107" ).setValue( "2425" ); ws.getRange2( "A108" ).setValue( "2448" ); ws.getRange2( "A109" ).setValue( "2471" ); ws.getRange2( "A110" ).setValue( "2494" ); ws.getRange2( "A111" ).setValue( "2517" ); ws.getRange2( "A112" ).setValue( "2540" ); ws.getRange2( 'B102' ).setValue( '2') ws.getRange2( 'B103' ).setValue( '2') ws.getRange2( 'B104' ).setValue( '3') ws.getRange2( 'B105' ).setValue( '3') ws.getRange2( 'B106' ).setValue( '2') ws.getRange2( 'B107' ).setValue( '4') ws.getRange2( 'B108' ).setValue( '2') ws.getRange2( 'B109' ).setValue( '2') ws.getRange2( 'B110' ).setValue( '3') ws.getRange2( 'B111' ).setValue( '4') ws.getRange2( 'B112' ).setValue( '2') ws.getRange2( 'C102' ).setValue( '2') ws.getRange2( 'C103' ).setValue( '2') ws.getRange2( 'C104' ).setValue( '1.5') ws.getRange2( 'C105' ).setValue( '2') ws.getRange2( 'C106' ).setValue( '3') ws.getRange2( 'C107' ).setValue( '2') ws.getRange2( 'C108' ).setValue( '1.5') ws.getRange2( 'C109' ).setValue( '2') ws.getRange2( 'C110' ).setValue( '3') ws.getRange2( 'C111' ).setValue( '4') ws.getRange2( 'C112' ).setValue( '3') ws.getRange2( 'D102' ).setValue( '20') ws.getRange2( 'D103' ).setValue( '12') ws.getRange2( 'D104' ).setValue( '33') ws.getRange2( 'D105' ).setValue( '43') ws.getRange2( 'D106' ).setValue( '53') ws.getRange2( 'D107' ).setValue( '23') ws.getRange2( 'D108' ).setValue( '99') ws.getRange2( 'D109' ).setValue( '34') ws.getRange2( 'D110' ).setValue( '23') ws.getRange2( 'D111' ).setValue( '55') ws.getRange2( 'D112' ).setValue( '22') ws.getRange2( 'E102' ).setValue( '142000') ws.getRange2( 'E103' ).setValue( '144000') ws.getRange2( 'E104' ).setValue( '151000') ws.getRange2( 'E105' ).setValue( '150000') ws.getRange2( 'E106' ).setValue( '139000') ws.getRange2( 'E107' ).setValue( '169000') ws.getRange2( 'E108' ).setValue( '126000') ws.getRange2( 'E109' ).setValue( '142900') ws.getRange2( 'E110' ).setValue( '163000') ws.getRange2( 'E111' ).setValue( '169000') ws.getRange2( 'E112' ).setValue( '149000') oParser = new parserFormula( "LINEST(E102:E112,A102:D112,TRUE,TRUE)", "A1", ws ); oParser.setArrayFormulaRef(ws.getRange2("E120:E123").bbox); ok( oParser.parse() ); var array = oParser.calculate(); if(AscCommonExcel.cElementType.array === array.type) { strictEqual( array.getElementRowCol(0,0).getValue().toFixed(7) - 0, -234.2371645); strictEqual( array.getElementRowCol(1,0).getValue().toFixed(8) - 0, 13.26801148); strictEqual( array.getElementRowCol(2,0).getValue().toFixed(9) - 0, 0.996747993); strictEqual( array.getElementRowCol(3,0).getValue().toFixed(7) - 0, 459.7536742); } } ); test( "Test: \"MEDIAN\"", function () { function median( x ) { x.sort(fSortAscending); if ( x.length % 2 ) return x[(x.length - 1) / 2]; else return (x[x.length / 2 - 1] + x[x.length / 2]) / 2; } oParser = new parserFormula( "MEDIAN(10.5,12.4,19.4,23.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), median( [10.5, 12.4, 19.4, 23.2] ) ); oParser = new parserFormula( "MEDIAN(10.5,{12.4,19.4},23.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), median( [10.5, 12.4, 19.4, 23.2] ) ); oParser = new parserFormula( "MEDIAN(-3.5,1.4,6.9,-4.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), median( [-3.5, 1.4, 6.9, -4.5] ) ); testArrayFormula2("MEDIAN", 1, 8, null, true); } ); test( "Test: \"MODE\"", function () { function mode( x ) { x.sort(AscCommon.fSortAscending); if ( x.length < 1 ) return "#VALUE!"; else { var nMaxIndex = 0, nMax = 1, nCount = 1, nOldVal = x[0], i; for ( i = 1; i < x.length; i++ ) { if ( x[i] == nOldVal ) nCount++; else { nOldVal = x[i]; if ( nCount > nMax ) { nMax = nCount; nMaxIndex = i - 1; } nCount = 1; } } if ( nCount > nMax ) { nMax = nCount; nMaxIndex = i - 1; } if ( nMax == 1 && nCount == 1 ) return "#VALUE!"; else if ( nMax == 1 ) return nOldVal; else return x[nMaxIndex]; } } oParser = new parserFormula( "MODE(9,1,5,1,9,5,6,6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), mode( [9, 1, 5, 1, 9, 5, 6, 6] ) ); oParser = new parserFormula( "MODE(1,9,5,1,9,5,6,6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), mode( [1, 9, 5, 1, 9, 5, 6, 6] ) ); oParser = new parserFormula( "MODE(1,9,5,5,9,5,6,6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), mode( [1, 9, 5, 5, 9, 5, 6, 6] ) ); testArrayFormula2("mode", 1, 8, null, true); } ); test( "Test: \"MODE.MULT \"", function () { ws.getRange2( "F202" ).setValue( "1" ); ws.getRange2( "F203" ).setValue( "2" ); ws.getRange2( "F204" ).setValue( "3" ); ws.getRange2( "F205" ).setValue( "4" ); ws.getRange2( "F206" ).setValue( "3" ); ws.getRange2( "F207" ).setValue( "2" ); ws.getRange2( "F208" ).setValue( "1" ); ws.getRange2( "F209" ).setValue( "2" ); ws.getRange2( "F210" ).setValue( "3" ); ws.getRange2( "F211" ).setValue( "5" ); ws.getRange2( "F212" ).setValue( "6" ); ws.getRange2( "F213" ).setValue( "1" ); oParser = new parserFormula( "MODE.MULT(F202:F213)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); } ); test( "Test: \"MODE.SNGL \"", function () { ws.getRange2( "F202" ).setValue( "5.6" ); ws.getRange2( "F203" ).setValue( "4" ); ws.getRange2( "F204" ).setValue( "4" ); ws.getRange2( "F205" ).setValue( "3" ); ws.getRange2( "F206" ).setValue( "2" ); ws.getRange2( "F207" ).setValue( "4" ); oParser = new parserFormula( "MODE.SNGL(F202:F207)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); } ); test( "Test: \"NUMBERVALUE\"", function () { oParser = new parserFormula( 'NUMBERVALUE("2.500,27",",",".")', "A1", ws ); ok( oParser.parse(), 'NUMBERVALUE("2.500,27",",",".")'); strictEqual( oParser.calculate().getValue(), 2500.27, 'NUMBERVALUE("2.500,27",",",".")'); oParser = new parserFormula( 'NUMBERVALUE("3.5%")', "A1", ws ); ok( oParser.parse(), 'NUMBERVALUE("3.5%")'); strictEqual( oParser.calculate().getValue(), 0.035, 'NUMBERVALUE("3.5%")'); oParser = new parserFormula( 'NUMBERVALUE("3.5%%%")', "A1", ws ); ok( oParser.parse(), 'NUMBERVALUE("3.5%%%")'); strictEqual( oParser.calculate().getValue(), 0.0000035, 'NUMBERVALUE("3.5%%%")'); oParser = new parserFormula( 'NUMBERVALUE(123123,6,6)', "A1", ws ); ok( oParser.parse(), 'NUMBERVALUE(123123,6,6)'); strictEqual( oParser.calculate().getValue(), "#VALUE!", 'NUMBERVALUE(123123,6,6)'); testArrayFormula2("NUMBERVALUE", 1, 3); }); test( "Test: \"NORMDIST\"", function () { function normdist( x, mue, sigma, kum ) { if ( sigma <= 0 ) return "#NUM!"; else if ( kum == false ) return toFixed( AscCommonExcel.phi( (x - mue) / sigma ) / sigma ); else return toFixed( 0.5 + AscCommonExcel.gauss( (x - mue) / sigma ) ); } oParser = new parserFormula( "NORMDIST(42,40,1.5,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normdist( 42, 40, 1.5, true ) ); oParser = new parserFormula( "NORMDIST(42,40,1.5,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normdist( 42, 40, 1.5, false ) ); oParser = new parserFormula( "NORMDIST(42,40,-1.5,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normdist( 42, 40, -1.5, true ) ); oParser = new parserFormula( "NORMDIST(1,40,-1.5,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normdist( 1, 40, -1.5, true ) ); testArrayFormula2("NORMDIST", 4, 4); } ); test( "Test: \"NORM.DIST \"", function () { ws.getRange2( "F202" ).setValue( "42" ); ws.getRange2( "F203" ).setValue( "40" ); ws.getRange2( "F204" ).setValue( "1.5" ); oParser = new parserFormula( "NORM.DIST(F202,F203,F204,TRUE)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.9087888 ); oParser = new parserFormula( "NORM.DIST(F202,F203,F204,FALSE)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 0.10934 ); } ); test( "Test: \"NORMSDIST\"", function () { function normsdist( x ) { return toFixed( 0.5 + AscCommonExcel.gauss( x ) ); } oParser = new parserFormula( "NORMSDIST(1.333333)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normsdist( 1.333333 ) ); oParser = new parserFormula( "NORMSDIST(-1.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normsdist( -1.5 ) ); testArrayFormula("NORMSDIST"); } ); test( "Test: \"NORM.S.DIST\"", function () { oParser = new parserFormula( "NORM.S.DIST(1.333333,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.908788726 ); oParser = new parserFormula( "NORM.S.DIST(1.333333,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.164010148 ); testArrayFormula2("NORM.S.DIST", 2, 2) } ); test( "Test: \"NEGBINOMDIST\"", function () { function negbinomdist( x, r, p ) { x = parseInt( x ); r = parseInt( r ); if ( x < 0 || r < 1 || p < 0 || p > 1 ) return "#NUM!"; else return toFixed( Math.binomCoeff( x + r - 1, r - 1 ) * Math.pow( p, r ) * Math.pow( 1 - p, x ) ); } oParser = new parserFormula( "NEGBINOMDIST(6,10,0.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), negbinomdist( 6, 10, 0.5 ) ); oParser = new parserFormula( "NEGBINOMDIST(6,10,1.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), negbinomdist( 6, 10, 1.5 ) ); oParser = new parserFormula( "NEGBINOMDIST(20,10,0.63)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), negbinomdist( 20, 10, 0.63 ) ); testArrayFormula2("NEGBINOMDIST", 3, 3); } ); test( "Test: \"NEGBINOM.DIST \"", function () { ws.getRange2( "F202" ).setValue( "10" ); ws.getRange2( "F203" ).setValue( "5" ); ws.getRange2( "F204" ).setValue( "0.25" ); oParser = new parserFormula( "NEGBINOM.DIST(F202,F203,F204,TRUE)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.3135141 ); oParser = new parserFormula( "NEGBINOM.DIST(F202,F203,F204,FALSE)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0550487 ); testArrayFormula2("NEGBINOM.DIST", 4, 4); } ); test( "Test: \"NEGBINOMDIST \"", function () { ws.getRange2( "F202" ).setValue( "10" ); ws.getRange2( "F203" ).setValue( "5" ); ws.getRange2( "F204" ).setValue( "0.25" ); oParser = new parserFormula( "NEGBINOMDIST(F202,F203,F204)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.05504866 ); } ); test( "Test: \"NORMSINV\"", function () { function normsinv( x ) { if ( x <= 0.0 || x >= 1.0 ) return "#N/A"; else return toFixed( AscCommonExcel.gaussinv( x ) ); } oParser = new parserFormula( "NORMSINV(0.954)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normsinv( 0.954 ) ); oParser = new parserFormula( "NORMSINV(0.13)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normsinv( 0.13 ) ); oParser = new parserFormula( "NORMSINV(0.6782136)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normsinv( 0.6782136 ) ); oParser = new parserFormula( "NORMSINV(1.6782136)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normsinv( 1.6782136 ) ); oParser = new parserFormula( "NORMSINV(-1.6782136)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normsinv( -1.6782136 ) ); testArrayFormula("NORMSINV"); } ); test( "Test: \"NORM.S.INV \"", function () { oParser = new parserFormula( "NORM.S.INV(0.908789)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 1.3333347 ); } ); test( "Test: \"LOGINV\"", function () { function loginv( x, mue, sigma ) { if ( sigma <= 0 || x <= 0 || x >= 1 ) return "#NUM!"; else return toFixed( Math.exp( mue + sigma * ( AscCommonExcel.gaussinv( x ) ) ) ); } oParser = new parserFormula( "LOGINV(0.039084,3.5,1.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), loginv( 0.039084, 3.5, 1.2 ) ); oParser = new parserFormula( "LOGINV(0,3.5,1.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), loginv( 0, 3.5, 1.2 ) ); oParser = new parserFormula( "LOGINV(0,3.5,1.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), loginv( 10, 3.5, 1.2 ) ); oParser = new parserFormula( "LOGINV(0,3.5,1.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), loginv( -10, 3.5, 1.2 ) ); testArrayFormula2("LOGINV", 3, 3); } ); test( "Test: \"NORMINV\"", function () { function norminv( x, mue, sigma ) { if ( sigma <= 0.0 || x <= 0.0 || x >= 1.0 ) return "#NUM!"; else return toFixed( AscCommonExcel.gaussinv( x ) * sigma + mue ); } oParser = new parserFormula( "NORMINV(0.954,40,1.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), norminv( 0.954, 40, 1.5 ) ); oParser = new parserFormula( "NORMINV(0.13,100,0.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), norminv( 0.13, 100, 0.5 ) ); oParser = new parserFormula( "NORMINV(0.6782136,6,0.005)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), norminv( 0.6782136, 6, 0.005 ) ); oParser = new parserFormula( "NORMINV(-1.6782136,7,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), norminv( -1.6782136, 7, 0 ) ); testArrayFormula2("NORMINV", 3, 3); } ); test( "Test: \"NORM.INV \"", function () { ws.getRange2( "F202" ).setValue( "0.908789" ); ws.getRange2( "F203" ).setValue( "40" ); ws.getRange2( "F204" ).setValue( "1.5" ); oParser = new parserFormula( "NORM.INV(F202,F203,F204)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 42.000002 ); } ); test( "Test: \"PEARSON\"", function () { function pearson( x, y ) { var sumXDeltaYDelta = 0, sqrXDelta = 0, sqrYDelta = 0, _x = 0, _y = 0, xLength = 0; if ( x.length != y.length ) return "#N/A" for ( var i = 0; i < x.length; i++ ) { _x += x[i] _y += y[i] xLength++; } _x /= xLength; _y /= xLength; for ( var i = 0; i < x.length; i++ ) { sumXDeltaYDelta += (x[i] - _x) * (y[i] - _y); sqrXDelta += (x[i] - _x) * (x[i] - _x); sqrYDelta += (y[i] - _y) * (y[i] - _y); } if ( sqrXDelta == 0 || sqrYDelta == 0 ) return "#DIV/0!" else return toFixed( sumXDeltaYDelta / Math.sqrt( sqrXDelta * sqrYDelta ) ); } oParser = new parserFormula( "PEARSON({9,7,5,3,1},{10,6,1,5,3})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), pearson( [9, 7, 5, 3, 1], [10, 6, 1, 5, 3] ) ); testArrayFormula2("PEARSON", 2, 2, null, true) } ); test( "Test: \"PERCENTILE\"", function () { function percentile( A, k ) { A.sort(fSortAscending) var nSize = A.length; if ( A.length < 1 || nSize == 0 ) return new AscCommonExcel.cError( AscCommonExcel.cErrorType.not_available ).toString(); else { if ( nSize == 1 ) return toFixed( A[0] ); else { var nIndex = Math.floor( k * (nSize - 1) ); var fDiff = k * (nSize - 1) - Math.floor( k * (nSize - 1) ); if ( fDiff == 0.0 ) return toFixed( A[nIndex] ); else { return toFixed( A[nIndex] + fDiff * (A[nIndex + 1] - A[nIndex]) ); } } } } oParser = new parserFormula( "PERCENTILE({1,3,2,4},0.3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), percentile( [1, 3, 2, 4], 0.3 ) ); oParser = new parserFormula( "PERCENTILE({1,3,2,4},0.75)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), percentile( [1, 3, 2, 4], 0.75 ) ); //TODO нужна другая функция для тестирования //testArrayFormula2("PERCENTILE", 2, 2, null, true); } ); test( "Test: \"PERCENTILE.INC\"", function () { ws.getRange2( "A2" ).setValue( "1" ); ws.getRange2( "A3" ).setValue( "2" ); ws.getRange2( "A4" ).setValue( "3" ); ws.getRange2( "A5" ).setValue( "4" ); oParser = new parserFormula( "PERCENTILE.INC(A2:A5,0.3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1.9 ); } ); test( "Test: \"PERCENTILE.EXC\"", function () { ws.getRange2( "A202" ).setValue( "1" ); ws.getRange2( "A203" ).setValue( "2" ); ws.getRange2( "A204" ).setValue( "3" ); ws.getRange2( "A205" ).setValue( "6" ); ws.getRange2( "A206" ).setValue( "6" ); ws.getRange2( "A207" ).setValue( "6" ); ws.getRange2( "A208" ).setValue( "7" ); ws.getRange2( "A209" ).setValue( "8" ); ws.getRange2( "A210" ).setValue( "9" ); oParser = new parserFormula( "PERCENTILE.EXC(A202:A210, 0.25)", "A1", ws ); ok( oParser.parse(), "PERCENTILE.EXC(A202:A210, 0.25)" ); strictEqual( oParser.calculate().getValue(), 2.5, "PERCENTILE.EXC(A202:A210, 0.25)" ); oParser = new parserFormula( "PERCENTILE.EXC(A202:A210, 0)", "A1", ws ); ok( oParser.parse(), "PERCENTILE.EXC(A202:A210, 0)" ); strictEqual( oParser.calculate().getValue(), "#NUM!", "PERCENTILE.EXC(A202:A210, 0)" ); oParser = new parserFormula( "PERCENTILE.EXC(A202:A210, 0.01)", "A1", ws ); ok( oParser.parse(), "PERCENTILE.EXC(A202:A210, 0.01)" ); strictEqual( oParser.calculate().getValue(), "#NUM!", "PERCENTILE.EXC(A202:A210, 0.01)" ); oParser = new parserFormula( "PERCENTILE.EXC(A202:A210, 2)", "A1", ws ); ok( oParser.parse(), "PERCENTILE.EXC(A202:A210, 2)" ); strictEqual( oParser.calculate().getValue(), "#NUM!", "PERCENTILE.EXC(A202:A210, 2)" ); //TODO нужна другая функция для тестирования //testArrayFormula2("PERCENTILE.EXC", 2, 2, null, true) } ); test( "Test: \"PERCENTRANK\"", function () { function percentrank( A, x, k ) { var tA = A, t, fNum = x; if ( !k ) k = 3; tA.sort(fSortAscending); var nSize = tA.length; if ( tA.length < 1 || nSize == 0 ) return "#N/A"; else { if ( fNum < tA[0] || fNum > tA[nSize - 1] ) return "#N/A"; else if ( nSize == 1 ) return 1 else { var fRes, nOldCount = 0, fOldVal = tA[0], i; for ( i = 1; i < nSize && tA[i] < fNum; i++ ) { if ( tA[i] != fOldVal ) { nOldCount = i; fOldVal = tA[i]; } } if ( tA[i] != fOldVal ) nOldCount = i; if ( fNum == tA[i] ) fRes = nOldCount / (nSize - 1); else { if ( nOldCount == 0 ) { fRes = 0.0; } else { var fFract = ( fNum - tA[nOldCount - 1] ) / ( tA[nOldCount] - tA[nOldCount - 1] ); fRes = ( nOldCount - 1 + fFract ) / (nSize - 1); } } return fRes.toString().substr( 0, fRes.toString().indexOf( "." ) + 1 + k ) - 0; } } } oParser = new parserFormula( "PERCENTRANK({12,6,7,9,3,8},4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), percentrank( [12, 6, 7, 9, 3, 8], 4 ) ); oParser = new parserFormula( "PERCENTRANK({12,6,7,9,3,8},5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), percentrank( [12, 6, 7, 9, 3, 8], 5 ) ); //TODO нужен другой тест //testArrayFormula2("PERCENTRANK", 2, 3, null, true); } ); test( "Test: \"PERCENTRANK.EXC\"", function () { ws.getRange2( "A202" ).setValue( "1" ); ws.getRange2( "A203" ).setValue( "2" ); ws.getRange2( "A204" ).setValue( "3" ); ws.getRange2( "A205" ).setValue( "6" ); ws.getRange2( "A206" ).setValue( "6" ); ws.getRange2( "A207" ).setValue( "6" ); ws.getRange2( "A208" ).setValue( "7" ); ws.getRange2( "A209" ).setValue( "8" ); ws.getRange2( "A210" ).setValue( "9" ); oParser = new parserFormula( "PERCENTRANK.EXC(A202:A210, 7)", "A1", ws ); ok( oParser.parse(), "PERCENTRANK.EXC(A202:A210, 7)" ); strictEqual( oParser.calculate().getValue(), 0.7, "PERCENTRANK.EXC(A202:A210, 7)" ); oParser = new parserFormula( "PERCENTRANK.EXC(A202:A210, 5.43)", "A1", ws ); ok( oParser.parse(), "PERCENTRANK.EXC(A202:A210, 5.43)" ); strictEqual( oParser.calculate().getValue(), 0.381, "PERCENTRANK.EXC(A202:A210, 5.43)" ); oParser = new parserFormula( "PERCENTRANK.EXC(A202:A210, 5.43, 1)", "A1", ws ); ok( oParser.parse(), "PERCENTRANK.EXC(A202:A210, 5.43, 1)" ); strictEqual( oParser.calculate().getValue(), 0.3, "PERCENTRANK.EXC(A202:A210, 5.43, 1)" ); //TODO нужен другой тест //testArrayFormula2("PERCENTRANK.EXC", 2, 3, null, true); } ); test( "Test: \"PERCENTRANK.INC\"", function () { ws.getRange2( "A202" ).setValue( "13" ); ws.getRange2( "A203" ).setValue( "12" ); ws.getRange2( "A204" ).setValue( "11" ); ws.getRange2( "A205" ).setValue( "8" ); ws.getRange2( "A206" ).setValue( "4" ); ws.getRange2( "A207" ).setValue( "3" ); ws.getRange2( "A208" ).setValue( "2" ); ws.getRange2( "A209" ).setValue( "1" ); ws.getRange2( "A210" ).setValue( "1" ); ws.getRange2( "A211" ).setValue( "1" ); oParser = new parserFormula( "PERCENTRANK.INC(A202:A211, 2)", "A1", ws ); ok( oParser.parse(), "PERCENTRANK.INC(A202:A211, 2)" ); strictEqual( oParser.calculate().getValue(), 0.333, "PERCENTRANK.INC(A202:A211, 2)" ); oParser = new parserFormula( "PERCENTRANK.INC(A202:A211, 4)", "A1", ws ); ok( oParser.parse(), "PERCENTRANK.INC(A202:A211, 4)" ); strictEqual( oParser.calculate().getValue(), 0.555, "PERCENTRANK.INC(A202:A211, 4)" ); oParser = new parserFormula( "PERCENTRANK.INC(A202:A211, 8)", "A1", ws ); ok( oParser.parse(), "PERCENTRANK.INC(A202:A211, 8)" ); strictEqual( oParser.calculate().getValue(), 0.666, "PERCENTRANK.INC(A202:A211, 8)" ); oParser = new parserFormula( "PERCENTRANK.INC(A202:A211, 5)", "A1", ws ); ok( oParser.parse(), "PERCENTRANK.INC(A202:A211, 5)" ); strictEqual( oParser.calculate().getValue(), 0.583, "PERCENTRANK.INC(A202:A211, 5)" ); } ); test( "Test: \"PERMUT\"", function () { ws.getRange2( "A2" ).setValue( "100" ); ws.getRange2( "A3" ).setValue( "3" ); oParser = new parserFormula( "PERMUT(A2,A3)", "A1", ws ); ok( oParser.parse(), "PERMUT(A2,A3)" ); strictEqual( oParser.calculate().getValue(), 970200, "PERMUT(A2,A3)" ); oParser = new parserFormula( "PERMUT(3,2)", "A1", ws ); ok( oParser.parse(), "PERMUT(3,2)" ); strictEqual( oParser.calculate().getValue(), 6, "PERMUT(3,2)" ); testArrayFormula2("PERMUT", 2, 2); } ); test( "Test: \"PERMUTATIONA\"", function () { oParser = new parserFormula( "PERMUTATIONA(3,2)", "A1", ws ); ok( oParser.parse(), "PERMUTATIONA(3,2)" ); strictEqual( oParser.calculate().getValue(), 9, "PERMUTATIONA(3,2)" ); oParser = new parserFormula( "PERMUTATIONA(2,2)", "A1", ws ); ok( oParser.parse(), "PERMUTATIONA(2,2)" ); strictEqual( oParser.calculate().getValue(), 4, "PERMUTATIONA(2,2)" ); testArrayFormula2("PERMUTATIONA", 2, 2); } ); test( "Test: \"PHI\"", function () { oParser = new parserFormula( "PHI(0.75)", "A1", ws ); ok( oParser.parse(), "PHI(0.75)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.301137432, "PHI(0.75)" ); testArrayFormula2("PHI", 1, 1); } ); test( "Test: \"POISSON\"", function () { function poisson( x, l, cumulativeFlag ) { var _x = parseInt( x ), _l = l, f = cumulativeFlag; if ( f ) { var sum = 0; for ( var k = 0; k <= x; k++ ) { sum += Math.pow( _l, k ) / Math.fact( k ); } sum *= Math.exp( -_l ); return toFixed( sum ); } else { return toFixed( Math.exp( -_l ) * Math.pow( _l, _x ) / Math.fact( _x ) ); } } oParser = new parserFormula( "POISSON(8,2,false)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), poisson( 8, 2, false ) ); oParser = new parserFormula( "POISSON(8,2,true)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), poisson( 8, 2, true ) ); oParser = new parserFormula( "POISSON(2.6,5,false)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), poisson( 2, 5, false ) ); oParser = new parserFormula( "POISSON(2,5.7,true)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), poisson( 2, 5.7, true ) ); oParser = new parserFormula( "POISSON(-6,5,true)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "POISSON(6,-5,false)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("POISSON", 3, 3); } ); test( "Test: \"POISSON.DIST\"", function () { ws.getRange2( "A202" ).setValue( "2" ); ws.getRange2( "A203" ).setValue( "5" ); oParser = new parserFormula( "POISSON.DIST(A202,A203,TRUE)", "A1", ws ); ok( oParser.parse(), "POISSON.DIST(A202,A203,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.124652, "POISSON.DIST(A202,A203,TRUE)" ); oParser = new parserFormula( "POISSON.DIST(A202,A203,FALSE)", "A1", ws ); ok( oParser.parse(), "POISSON.DIST(A202,A203,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.084224, "POISSON.DIST(A202,A203,FALSE)" ); testArrayFormula2("POISSON.DIST", 3, 3); } ); test( "Test: \"PROB\"", function () { oParser = new parserFormula( "PROB({0,1,2,3},{0.2,0.3,0.1,0.4},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0.1 ); oParser = new parserFormula( "PROB({0,1,2,3},{0.2,0.3,0.1,0.4},1,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0.8 ); } ); test( "Test: \"PROB\"", function () { function quartile( A, k ) { var fFlag = k; A.sort(fSortAscending); var nSize = A.length; if ( A.length < 1 || nSize == 0 ) return "#N/A" else { if ( nSize == 1 ) return toFixed( A[0] ); else { if ( fFlag < 0.0 || fFlag > 4 ) return "#NUM!"; else if ( fFlag == 0.0 ) return toFixed( A[0] ); else if ( fFlag == 1.0 ) { var nIndex = Math.floor( 0.25 * (nSize - 1) ), fDiff = 0.25 * (nSize - 1) - Math.floor( 0.25 * (nSize - 1) ); if ( fDiff == 0.0 ) return toFixed( A[nIndex] ); else { return toFixed( A[nIndex] + fDiff * (A[nIndex + 1] - A[nIndex]) ); } } else if ( fFlag == 2.0 ) { if ( nSize % 2 == 0 ) return toFixed( (A[nSize / 2 - 1] + A[nSize / 2]) / 2.0 ); else return toFixed( A[(nSize - 1) / 2] ); } else if ( fFlag == 3.0 ) { var nIndex = Math.floor( 0.75 * (nSize - 1) ), fDiff = 0.75 * (nSize - 1) - Math.floor( 0.75 * (nSize - 1) ); if ( fDiff == 0.0 ) return toFixed( A[nIndex] ); else { return toFixed( A[nIndex] + fDiff * (A[nIndex + 1] - A[nIndex]) ); } } else return toFixed( A[nSize - 1] ); } } } oParser = new parserFormula( "QUARTILE({1,2,4,7,8,9,10,12},-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), quartile( [1, 2, 4, 7, 8, 9, 10, 12], -1 ) ); oParser = new parserFormula( "QUARTILE({1,2,4,7,8,9,10,12},0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), quartile( [1, 2, 4, 7, 8, 9, 10, 12], 0 ) ); oParser = new parserFormula( "QUARTILE({1,2,4,7,8,9,10,12},1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), quartile( [1, 2, 4, 7, 8, 9, 10, 12], 1 ) ); oParser = new parserFormula( "QUARTILE({1,2,4,7,8,9,10,12},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), quartile( [1, 2, 4, 7, 8, 9, 10, 12], 2 ) ); oParser = new parserFormula( "QUARTILE({1,2,4,7,8,9,10,12},3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), quartile( [1, 2, 4, 7, 8, 9, 10, 12], 3 ) ); oParser = new parserFormula( "QUARTILE({1,2,4,7,8,9,10,12},4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), quartile( [1, 2, 4, 7, 8, 9, 10, 12], 4 ) ); oParser = new parserFormula( "QUARTILE({1,2,4,7,8,9,10,12},5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), quartile( [1, 2, 4, 7, 8, 9, 10, 12], 5 ) ); } ); test( "Test: \"QUARTILE\"", function () { ws.getRange2( "A202" ).setValue( "1" ); ws.getRange2( "A203" ).setValue( "2" ); ws.getRange2( "A204" ).setValue( "4" ); ws.getRange2( "A205" ).setValue( "7" ); ws.getRange2( "A206" ).setValue( "8" ); ws.getRange2( "A207" ).setValue( "9" ); ws.getRange2( "A208" ).setValue( "10" ); ws.getRange2( "A209" ).setValue( "12" ); oParser = new parserFormula( "QUARTILE(A202:A209,1)", "A1", ws ); ok( oParser.parse(), "QUARTILE(A202:A209,1)" ); strictEqual( oParser.calculate().getValue(), 3.5, "QUARTILE(A202:A209,1)" ); //TODO нужна другая функция для тестирования //testArrayFormula2("QUARTILE", 2, 2) } ); test( "Test: \"QUARTILE.INC\"", function () { ws.getRange2( "A202" ).setValue( "1" ); ws.getRange2( "A203" ).setValue( "2" ); ws.getRange2( "A204" ).setValue( "4" ); ws.getRange2( "A205" ).setValue( "7" ); ws.getRange2( "A206" ).setValue( "8" ); ws.getRange2( "A207" ).setValue( "9" ); ws.getRange2( "A208" ).setValue( "10" ); ws.getRange2( "A209" ).setValue( "12" ); oParser = new parserFormula( "QUARTILE.INC(A202:A209,1)", "A1", ws ); ok( oParser.parse(), "QUARTILE.INC(A202:A209,1)" ); strictEqual( oParser.calculate().getValue(), 3.5, "QUARTILE.INC(A202:A209,1)" ); } ); test( "Test: \"QUARTILE.EXC\"", function () { ws.getRange2( "A202" ).setValue( "6" ); ws.getRange2( "A203" ).setValue( "7" ); ws.getRange2( "A204" ).setValue( "15" ); ws.getRange2( "A205" ).setValue( "36" ); ws.getRange2( "A206" ).setValue( "39" ); ws.getRange2( "A207" ).setValue( "40" ); ws.getRange2( "A208" ).setValue( "41" ); ws.getRange2( "A209" ).setValue( "42" ); ws.getRange2( "A210" ).setValue( "43" ); ws.getRange2( "A211" ).setValue( "47" ); ws.getRange2( "A212" ).setValue( "49" ); oParser = new parserFormula( "QUARTILE.EXC(A202:A212,1)", "A1", ws ); ok( oParser.parse(), "QUARTILE.EXC(A202:A212,1)" ); strictEqual( oParser.calculate().getValue(), 15, "QUARTILE.EXC(A202:A212,1)" ); oParser = new parserFormula( "QUARTILE.EXC(A202:A212,3)", "A1", ws ); ok( oParser.parse(), "QUARTILE.EXC(A202:A212,3)" ); strictEqual( oParser.calculate().getValue(), 43, "QUARTILE.EXC(A202:A212,3)" ); //TODO нужна другая функция для тестирования //testArrayFormula2("QUARTILE.EXC", 2, 2) } ); test( "Test: \"RSQ\"", function () { function rsq( x, y ) { var sumXDeltaYDelta = 0, sqrXDelta = 0, sqrYDelta = 0, _x = 0, _y = 0, xLength = 0; if ( x.length != y.length ) return "#N/A" for ( var i = 0; i < x.length; i++ ) { _x += x[i] _y += y[i] xLength++; } _x /= xLength; _y /= xLength; for ( var i = 0; i < x.length; i++ ) { sumXDeltaYDelta += (x[i] - _x) * (y[i] - _y); sqrXDelta += (x[i] - _x) * (x[i] - _x); sqrYDelta += (y[i] - _y) * (y[i] - _y); } if ( sqrXDelta == 0 || sqrYDelta == 0 ) return "#DIV/0!" else return toFixed( Math.pow( sumXDeltaYDelta / Math.sqrt( sqrXDelta * sqrYDelta ), 2 ) ); } oParser = new parserFormula( "RSQ({9,7,5,3,1},{10,6,1,5,3})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), rsq( [9, 7, 5, 3, 1], [10, 6, 1, 5, 3] ) ); oParser = new parserFormula( "RSQ({2,3,9,1,8,7,5},{6,5,11,7,5,4,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), rsq( [2, 3, 9, 1, 8, 7, 5], [6, 5, 11, 7, 5, 4, 4] ) ); testArrayFormula2("RSQ", 2, 2, null, true) } ); test( "Test: \"SKEW\"", function () { function skew( x ) { var sumSQRDeltaX = 0, _x = 0, xLength = 0, standDev = 0, sumSQRDeltaXDivstandDev = 0; for ( var i = 0; i < x.length; i++ ) { _x += x[i]; xLength++; } if ( xLength <= 2 ) return "#N/A" _x /= xLength; for ( var i = 0; i < x.length; i++ ) { sumSQRDeltaX += Math.pow( x[i] - _x, 2 ); } standDev = Math.sqrt( sumSQRDeltaX / ( xLength - 1 ) ); for ( var i = 0; i < x.length; i++ ) { sumSQRDeltaXDivstandDev += Math.pow( (x[i] - _x) / standDev, 3 ); } return toFixed( xLength / (xLength - 1) / (xLength - 2) * sumSQRDeltaXDivstandDev ) } oParser = new parserFormula( "SKEW(3,4,5,2,3,4,5,6,4,7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), skew( [3, 4, 5, 2, 3, 4, 5, 6, 4, 7] ) ); oParser = new parserFormula( "SKEW({2,3,9,1,8,7,5},{6,5,11,7,5,4,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), skew( [2, 3, 9, 1, 8, 7, 5, 6, 5, 11, 7, 5, 4, 4] ) ); testArrayFormula2("SKEW", 1, 8, null, true); } ); test( "Test: \"SKEW.P\"", function () { ws.getRange2( "A202" ).setValue( "3" ); ws.getRange2( "A203" ).setValue( "4" ); ws.getRange2( "A204" ).setValue( "5" ); ws.getRange2( "A205" ).setValue( "2" ); ws.getRange2( "A206" ).setValue( "3" ); ws.getRange2( "A207" ).setValue( "4" ); ws.getRange2( "A208" ).setValue( "5" ); ws.getRange2( "A209" ).setValue( "6" ); ws.getRange2( "A210" ).setValue( "4" ); ws.getRange2( "A211" ).setValue( "7" ); oParser = new parserFormula( "SKEW.P(A202:A211)", "A1", ws ); ok( oParser.parse(), "SKEW.P(A202:A211)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.303193, "SKEW.P(A202:A211)" ); } ); test( "Test: \"SMALL\"", function () { oParser = new parserFormula( "SMALL({3,5,3,5,4;4,2,4,6,7},3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "SMALL({3,5,3,5,4;4,2,4,6,7},7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "SMALL({1,TRUE,FALSE,3,4,5,32,5,4,3},9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "SMALL({1,TRUE,FALSE,3,4,5,32,5,4,3},8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 32 ); oParser = new parserFormula( "SMALL({1,TRUE,10,3,4,5,32,5,4,3},10)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "SMALL({1,TRUE,10,3,4,5,32,5,4,3},1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); //TODO нужна другая функция для тестирования //testArrayFormula2("SMALL", 2, 2) } ); test( "Test: \"SLOPE\"", function () { function slope( y, x ) { var sumXDeltaYDelta = 0, sqrXDelta = 0, _x = 0, _y = 0, xLength = 0; if ( x.length != y.length ) return "#N/A" for ( var i = 0; i < x.length; i++ ) { _x += x[i] _y += y[i] xLength++; } _x /= xLength; _y /= xLength; for ( var i = 0; i < x.length; i++ ) { sumXDeltaYDelta += (x[i] - _x) * (y[i] - _y); sqrXDelta += (x[i] - _x) * (x[i] - _x); } if ( sqrXDelta == 0 ) return "#DIV/0!" else return toFixed( sumXDeltaYDelta / sqrXDelta ); } oParser = new parserFormula( "SLOPE({9,7,5,3,1},{10,6,1,5,3})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), slope( [9, 7, 5, 3, 1], [10, 6, 1, 5, 3] ) ); oParser = new parserFormula( "SLOPE({2,3,9,1,8,7,5},{6,5,11,7,5,4,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), slope( [2, 3, 9, 1, 8, 7, 5], [6, 5, 11, 7, 5, 4, 4] ) ); testArrayFormula2("SLOPE", 2, 2, null, true); } ); test( "Test: \"STEYX\"", function () { ws.getRange2( "A203" ).setValue( "2" ); ws.getRange2( "A204" ).setValue( "3" ); ws.getRange2( "A205" ).setValue( "9" ); ws.getRange2( "A206" ).setValue( "1" ); ws.getRange2( "A207" ).setValue( "8" ); ws.getRange2( "A208" ).setValue( "7" ); ws.getRange2( "A209" ).setValue( "5" ); ws.getRange2( "B203" ).setValue( "6" ); ws.getRange2( "B204" ).setValue( "5" ); ws.getRange2( "B205" ).setValue( "11" ); ws.getRange2( "B206" ).setValue( "7" ); ws.getRange2( "B207" ).setValue( "5" ); ws.getRange2( "B208" ).setValue( "4" ); ws.getRange2( "B209" ).setValue( "4" ); oParser = new parserFormula( "STEYX(A203:A209,B203:B209)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 3.305719 ); testArrayFormula2("STEYX", 2, 2, null, true); } ); test( "Test: \"STANDARDIZE\"", function () { function STANDARDIZE( x, mean, sigma ) { if ( sigma <= 0 ) return "#NUM!" else return toFixed( (x - mean) / sigma ); } oParser = new parserFormula( "STANDARDIZE(42,40,1.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), STANDARDIZE( 42, 40, 1.5 ) ); oParser = new parserFormula( "STANDARDIZE(22,12,2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), STANDARDIZE( 22, 12, 2 ) ); oParser = new parserFormula( "STANDARDIZE(22,12,-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), STANDARDIZE( 22, 12, -2 ) ); testArrayFormula2("STANDARDIZE", 3, 3); } ); test( "Test: \"STDEV\"", function () { function stdev() { var average = 0, res = 0; for ( var i = 0; i < arguments.length; i++ ) { average += arguments[i]; } average /= arguments.length; for ( var i = 0; i < arguments.length; i++ ) { res += (arguments[i] - average) * (arguments[i] - average); } return toFixed( Math.sqrt( res / (arguments.length - 1) ) ); } oParser = new parserFormula( "STDEV(123,134,143,173,112,109)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), stdev( 123, 134, 143, 173, 112, 109 ) ); ws.getRange2( "E400" ).setValue( "\"123\"" ); ws.getRange2( "E401" ).setValue( "134" ); ws.getRange2( "E402" ).setValue( "143" ); ws.getRange2( "E403" ).setValue( "173" ); ws.getRange2( "E404" ).setValue( "112" ); ws.getRange2( "E405" ).setValue( "109" ); oParser = new parserFormula( "STDEV(E400:E405)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), stdev( 134, 143, 173, 112, 109 ) ); } ); test( "Test: \"STDEV.S\"", function () { ws.getRange2( "A202" ).setValue( "1345" ); ws.getRange2( "A203" ).setValue( "1301" ); ws.getRange2( "A204" ).setValue( "1368" ); ws.getRange2( "A205" ).setValue( "1322" ); ws.getRange2( "A206" ).setValue( "1310" ); ws.getRange2( "A207" ).setValue( "1370" ); ws.getRange2( "A208" ).setValue( "1318" ); ws.getRange2( "A209" ).setValue( "1350" ); ws.getRange2( "A210" ).setValue( "1303" ); ws.getRange2( "A211" ).setValue( "1299" ); oParser = new parserFormula( "STDEV.S(A202:A211)", "A1", ws ); ok( oParser.parse(), "STDEV.S(A202:A211)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 27.46391572, "STDEV.S(A202:A211)" ); } ); test( "Test: \"STDEV.P\"", function () { ws.getRange2( "A202" ).setValue( "1345" ); ws.getRange2( "A203" ).setValue( "1301" ); ws.getRange2( "A204" ).setValue( "1368" ); ws.getRange2( "A205" ).setValue( "1322" ); ws.getRange2( "A206" ).setValue( "1310" ); ws.getRange2( "A207" ).setValue( "1370" ); ws.getRange2( "A208" ).setValue( "1318" ); ws.getRange2( "A209" ).setValue( "1350" ); ws.getRange2( "A210" ).setValue( "1303" ); ws.getRange2( "A211" ).setValue( "1299" ); oParser = new parserFormula( "STDEV.P(A202:A211)", "A1", ws ); ok( oParser.parse(), "STDEV.P(A202:A211)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 26.05455814, "STDEV.P(A202:A211)" ); } ); test( "Test: \"STDEVA\"", function () { ws.getRange2( "E400" ).setValue( "\"123\"" ); ws.getRange2( "E401" ).setValue( "134" ); ws.getRange2( "E402" ).setValue( "143" ); ws.getRange2( "E403" ).setValue( "173" ); ws.getRange2( "E404" ).setValue( "112" ); ws.getRange2( "E405" ).setValue( "109" ); function stdeva() { var average = 0, res = 0; for ( var i = 0; i < arguments.length; i++ ) { average += arguments[i]; } average /= arguments.length; for ( var i = 0; i < arguments.length; i++ ) { res += (arguments[i] - average) * (arguments[i] - average); } return toFixed( Math.sqrt( res / (arguments.length - 1) ) ); } oParser = new parserFormula( "STDEVA(123,134,143,173,112,109)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), stdeva( 123, 134, 143, 173, 112, 109 ) ); oParser = new parserFormula( "STDEVA(123,134,143,173,112,109)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), stdeva( 123, 134, 143, 173, 112, 109 ) ); testArrayFormula2("STDEVA", 1, 8, null, true); } ); test( "Test: \"SWITCH\"", function () { ws.getRange2( "A2" ).setValue( "2" ); ws.getRange2( "A3" ).setValue( "99" ); ws.getRange2( "A4" ).setValue( "99" ); ws.getRange2( "A5" ).setValue( "2" ); ws.getRange2( "A6" ).setValue( "3" ); oParser = new parserFormula( 'SWITCH(WEEKDAY(A2),1,"Sunday",2,"Monday",3,"Tuesday","No match")', "A1", ws ); ok( oParser.parse(), 'SWITCH(WEEKDAY(A2),1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); strictEqual( oParser.calculate().getValue(), "Monday", 'SWITCH(WEEKDAY(A2),1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); oParser = new parserFormula( 'SWITCH(A3,1,"Sunday",2,"Monday",3,"Tuesday")', "A1", ws ); ok( oParser.parse(), 'SWITCH(A3,1,"Sunday",2,"Monday",3,"Tuesday")' ); strictEqual( oParser.calculate().getValue(), "#N/A", 'SWITCH(A3,1,"Sunday",2,"Monday",3,"Tuesday")' ); oParser = new parserFormula( 'SWITCH(A4,1,"Sunday",2,"Monday",3,"Tuesday","No match")', "A1", ws ); ok( oParser.parse(), 'SWITCH(A4,1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); strictEqual( oParser.calculate().getValue(), "No match", 'SWITCH(A4,1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); oParser = new parserFormula( 'SWITCH(A5,1,"Sunday",7,"Saturday","weekday")', "A1", ws ); ok( oParser.parse(), 'SWITCH(A5,1,"Sunday",7,"Saturday","weekday")' ); strictEqual( oParser.calculate().getValue(), "weekday", 'SWITCH(A5,1,"Sunday",7,"Saturday","weekday")' ); oParser = new parserFormula( 'SWITCH(A6,1,"Sunday",2,"Monday",3,"Tuesday","No match")', "A1", ws ); ok( oParser.parse(), 'SWITCH(A6,1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); strictEqual( oParser.calculate().getValue(), "Tuesday", 'SWITCH(A6,1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); oParser = new parserFormula( 'SWITCH(122,1,"Sunday",2,"Monday",3,"Tuesday","No match")', "A1", ws ); ok( oParser.parse(), 'SWITCH(122,1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); strictEqual( oParser.calculate().getValue(), "No match", 'SWITCH(122,1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); oParser = new parserFormula( 'SWITCH({1,"2asd",3},{12,2,3},{"asd",2,3,4})', "A1", ws ); ok( oParser.parse(), 'SWITCH({1,"2asd",3},{12,2,3},{"asd",2,3,4})' ); strictEqual( oParser.calculate().getValue(), "#N/A", 'SWITCH({1,"2asd",3},{12,2,3},{"asd",2,3,4})' ); oParser = new parserFormula( 'SWITCH({"asd1","2asd",3},{"asd1",1,3},"sdf")', "A1", ws ); ok( oParser.parse(), 'SWITCH({"asd1","2asd",3},{"asd1",1,3},"sdf")' ); strictEqual( oParser.calculate().getValue(), "sdf", 'SWITCH({"asd1","2asd",3},{"asd1",1,3},"sdf")' ); testArrayFormulaEqualsValues("1,3.123,-4,#N/A;2,4,5,#N/A;#N/A,#N/A,#N/A,#N/A", "SWITCH(A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,1,1,#N/A;1,1,1,#N/A;#N/A,#N/A,#N/A,#N/A", "SWITCH(A1:C2,A1:C2,A1:A1,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,1,1,#N/A;2,2,2,#N/A;#N/A,#N/A,#N/A,#N/A", "SWITCH(A1:C2,A1:C2,A1:A2,A1:C2,A1:A2,A1:C2)"); } ); test( "Test: \"VAR\"", function () { function _var( x ) { var sumSQRDeltaX = 0, _x = 0, xLength = 0, standDev = 0, sumSQRDeltaXDivstandDev = 0; for ( var i = 0; i < x.length; i++ ) { _x += x[i]; xLength++; } _x /= xLength; for ( var i = 0; i < x.length; i++ ) { sumSQRDeltaX += Math.pow( x[i] - _x, 2 ); } return toFixed( sumSQRDeltaX / (xLength - 1) ) } oParser = new parserFormula( "VAR(10.5,12.4,19.4,23.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _var( [10.5, 12.4, 19.4, 23.2] ) ); oParser = new parserFormula( "VAR(10.5,{12.4,19.4},23.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _var( [10.5, 12.4, 19.4, 23.2] ) ); oParser = new parserFormula( "VAR(10.5,12.4,19.4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _var( [10.5, 12.4, 19.4] ) ); oParser = new parserFormula( "VAR(1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "VAR({1})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); ws.getRange2( "A202" ).setValue( "1345" ); ws.getRange2( "A203" ).setValue( "" ); ws.getRange2( "A204" ).setValue( "" ); oParser = new parserFormula( "VAR(A202)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "VAR(A202:A204)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "VAR(#REF!)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); } ); test( "Test: \"VAR.P\"", function () { ws.getRange2( "A202" ).setValue( "1345" ); ws.getRange2( "A203" ).setValue( "1301" ); ws.getRange2( "A204" ).setValue( "1368" ); ws.getRange2( "A205" ).setValue( "1322" ); ws.getRange2( "A206" ).setValue( "1310" ); ws.getRange2( "A207" ).setValue( "1370" ); ws.getRange2( "A208" ).setValue( "1318" ); ws.getRange2( "A209" ).setValue( "1350" ); ws.getRange2( "A210" ).setValue( "1303" ); ws.getRange2( "A211" ).setValue( "1299" ); oParser = new parserFormula( "VAR.P(A202:A211)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 678.84 ); testArrayFormula2("VAR.P", 1, 8, null, true); } ); test( "Test: \"VAR.S\"", function () { ws.getRange2( "A202" ).setValue( "1345" ); ws.getRange2( "A203" ).setValue( "1301" ); ws.getRange2( "A204" ).setValue( "1368" ); ws.getRange2( "A205" ).setValue( "1322" ); ws.getRange2( "A206" ).setValue( "1310" ); ws.getRange2( "A207" ).setValue( "1370" ); ws.getRange2( "A208" ).setValue( "1318" ); ws.getRange2( "A209" ).setValue( "1350" ); ws.getRange2( "A210" ).setValue( "1303" ); ws.getRange2( "A211" ).setValue( "1299" ); oParser = new parserFormula( "VAR.S(A202:A211)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 754.27 ); testArrayFormula2("VAR.S", 1, 8, null, true); } ); test( "Test: \"VARPA\"", function () { ws.getRange2( "A202" ).setValue( "1345" ); ws.getRange2( "A203" ).setValue( "1301" ); ws.getRange2( "A204" ).setValue( "1368" ); ws.getRange2( "A205" ).setValue( "1322" ); ws.getRange2( "A206" ).setValue( "1310" ); ws.getRange2( "A207" ).setValue( "1370" ); ws.getRange2( "A208" ).setValue( "1318" ); ws.getRange2( "A209" ).setValue( "1350" ); ws.getRange2( "A210" ).setValue( "1303" ); ws.getRange2( "A211" ).setValue( "1299" ); oParser = new parserFormula( "VARPA(A202:A211)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 678.84 ); testArrayFormula2("VARPA", 1, 8, null, true); } ); /* * Lookup and Reference */ test( "Test: \"HLOOKUP\"", function () { ws.getRange2( "A401" ).setValue( "Axles" );ws.getRange2( "B401" ).setValue( "Bearings" );ws.getRange2( "C401" ).setValue( "Bolts" ); ws.getRange2( "A402" ).setValue( "4" );ws.getRange2( "B402" ).setValue( "6" );ws.getRange2( "C402" ).setValue( "9" ); ws.getRange2( "A403" ).setValue( "5" );ws.getRange2( "B403" ).setValue( "7" );ws.getRange2( "C403" ).setValue( "10" ); ws.getRange2( "A404" ).setValue( "6" );ws.getRange2( "B404" ).setValue( "8" );ws.getRange2( "C404" ).setValue( "11" ); oParser = new parserFormula( "HLOOKUP(\"Axles\",A401:C404,2,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "HLOOKUP(\"Bearings\",A401:C404,3,FALSE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( "HLOOKUP(\"B\",A401:C404,3,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "HLOOKUP(\"Bolts\",A401:C404,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 11 ); oParser = new parserFormula( "HLOOKUP(3,{1,2,3;\"a\",\"b\",\"c\";\"d\",\"e\",\"f\"},2,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "c" ); /*oParser = new parserFormula( "HLOOKUP(1,{1,2,3;2,3,4},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "HLOOKUP(1,{1,2,3;2,3,4},3,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "HLOOKUP(1,{1,2,3;2,3,4},3,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "HLOOKUP({2,3,4},{1,2,3;2,3,4},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "HLOOKUP({2,3,4},{1,2,3;2,3,4},{4,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "HLOOKUP({2,3,4},{1,2,3;2,3,4},{1,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "HLOOKUP({2,3,4},{1,2,3;2,3,4;6,7,8},{1,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "HLOOKUP({5,3,4},{1,2,3;2,3,4;6,7,8},{1,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "HLOOKUP(4,{1,2,3;2,3,4;6,7,8},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "HLOOKUP(4,{1,2,3;2,3,4;6,7,8},3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 8 ); oParser = new parserFormula( "HLOOKUP(4,{1,2,3;2,3,4;6,7,8},5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "HLOOKUP({2,3,4},{1,2,3;2,3,4;6,7,8},1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 );*/ } ); test( "Test: \"VLOOKUP\"", function () { ws.getRange2( "A501" ).setValue( "Density" );ws.getRange2( "B501" ).setValue( "Bearings" );ws.getRange2( "C501" ).setValue( "Bolts" ); ws.getRange2( "A502" ).setValue( "0.457" );ws.getRange2( "B502" ).setValue( "3.55" );ws.getRange2( "C502" ).setValue( "500" ); ws.getRange2( "A503" ).setValue( "0.525" );ws.getRange2( "B503" ).setValue( "3.25" );ws.getRange2( "C503" ).setValue( "400" ); ws.getRange2( "A504" ).setValue( "0.616" );ws.getRange2( "B504" ).setValue( "2.93" );ws.getRange2( "C504" ).setValue( "300" ); ws.getRange2( "A505" ).setValue( "0.675" );ws.getRange2( "B505" ).setValue( "2.75" );ws.getRange2( "C505" ).setValue( "250" ); ws.getRange2( "A506" ).setValue( "0.746" );ws.getRange2( "B506" ).setValue( "2.57" );ws.getRange2( "C506" ).setValue( "200" ); ws.getRange2( "A507" ).setValue( "0.835" );ws.getRange2( "B507" ).setValue( "2.38" );ws.getRange2( "C507" ).setValue( "15" ); ws.getRange2( "A508" ).setValue( "0.946" );ws.getRange2( "B508" ).setValue( "2.17" );ws.getRange2( "C508" ).setValue( "100" ); ws.getRange2( "A509" ).setValue( "1.09" );ws.getRange2( "B509" ).setValue( "1.95" );ws.getRange2( "C509" ).setValue( "50" ); ws.getRange2( "A510" ).setValue( "1.29" );ws.getRange2( "B510" ).setValue( "1.71" );ws.getRange2( "C510" ).setValue( "0" ); oParser = new parserFormula( "VLOOKUP(1,A502:C510,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2.17 ); oParser = new parserFormula( "VLOOKUP(1,A502:C510,3,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 100.00 ); oParser = new parserFormula( "VLOOKUP(2,A502:C510,2,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1.71 ); oParser = new parserFormula( "VLOOKUP(1,{1,2,3;2,3,4},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "VLOOKUP(1,{1,2,3;2,3,4},3,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "VLOOKUP(1,{1,2,3;2,3,4},3,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "VLOOKUP({2,3,4},{1,2,3;2,3,4},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "VLOOKUP({2,3,4},{1,2,3;2,3,4},{4,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "VLOOKUP({2,3,4},{1,2,3;2,3,4},{1,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "VLOOKUP({2,3,4},{1,2,3;2,3,4;6,7,8},{1,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "VLOOKUP({5,3,4},{1,2,3;2,3,4;6,7,8},{1,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "VLOOKUP(4,{1,2,3;2,3,4;6,7,8},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "VLOOKUP(4,{1,2,3;2,3,4;6,7,8},3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "VLOOKUP(4,{1,2,3;2,3,4;6,7,8},5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "VLOOKUP({2,3,4},{1,2,3;2,3,4;6,7,8},1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); } ); test( "Test: \"LOOKUP\"", function () { ws.getRange2( "A102" ).setValue( "4.14" ); ws.getRange2( "A103" ).setValue( "4.19" ); ws.getRange2( "A104" ).setValue( "5.17" ); ws.getRange2( "A105" ).setValue( "5.77" ); ws.getRange2( "A106" ).setValue( "6.39" ); ws.getRange2( "B102" ).setValue( "red" ); ws.getRange2( "B103" ).setValue( "orange" ); ws.getRange2( "B104" ).setValue( "yellow" ); ws.getRange2( "B105" ).setValue( "green" ); ws.getRange2( "B106" ).setValue( "blue" ); oParser = new parserFormula( "LOOKUP(4.19, A102:A106, B102:B106)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "orange" ); oParser = new parserFormula( "LOOKUP(5.75, A102:A106, B102:B106)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "yellow" ); oParser = new parserFormula( "LOOKUP(7.66, A102:A106, B102:B106)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "blue" ); oParser = new parserFormula( "LOOKUP(0, A102:A106, B102:B106)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); ws.getRange2( "C101" ).setValue( "4.14" ); ws.getRange2( "D101" ).setValue( "4.19" ); ws.getRange2( "E101" ).setValue( "5.17" ); ws.getRange2( "F101" ).setValue( "5.77" ); ws.getRange2( "G101" ).setValue( "6.39" ); ws.getRange2( "H101" ).setValue( "7.99" ); ws.getRange2( "C102" ).setValue( "red" ); ws.getRange2( "D102" ).setValue( "orange" ); ws.getRange2( "E102" ).setValue( "yellow" ); ws.getRange2( "F102" ).setValue( "green" ); ws.getRange2( "G102" ).setValue( "blue" ); ws.getRange2( "H102" ).setValue( "black" ); oParser = new parserFormula( "LOOKUP(4.19,C101:H101,C102:H102)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "orange" ); oParser = new parserFormula( "LOOKUP(5.75,C101:H101,C102:H102)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "yellow" ); oParser = new parserFormula( "LOOKUP(7.66,C101:H101,C102:H102)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "blue" ); oParser = new parserFormula( "LOOKUP(0,C101:H101,C102:H102)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "LOOKUP(5.17,C101:H101,C102:H102)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "yellow" ); oParser = new parserFormula( "LOOKUP(9,C101:H101,C102:H102)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "black" ); }); test( "Test: \"MATCH\"", function () { ws.getRange2( "A551" ).setValue( "28" ); ws.getRange2( "A552" ).setValue( "29" ); ws.getRange2( "A553" ).setValue( "31" ); ws.getRange2( "A554" ).setValue( "45" ); ws.getRange2( "A555" ).setValue( "89" ); ws.getRange2( "B551" ).setValue( "89" ); ws.getRange2( "B552" ).setValue( "45" ); ws.getRange2( "B553" ).setValue( "31" ); ws.getRange2( "B554" ).setValue( "29" ); ws.getRange2( "B555" ).setValue( "28" ); ws.getRange2( "C551" ).setValue( "89" ); ws.getRange2( "C552" ).setValue( "45" ); ws.getRange2( "C553" ).setValue( "31" ); ws.getRange2( "C554" ).setValue( "29" ); ws.getRange2( "C555" ).setValue( "28" ); oParser = new parserFormula( "MATCH(30,A551:A555,-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "MATCH(30,A551:A555,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "MATCH(30,A551:A555,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "MATCH(30,B551:B555)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "MATCH(30,B551:B555,-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "MATCH(30,B551:B555,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "MATCH(31,C551:C555,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "MATCH(\"b\",{\"a\";\"b\";\"c\"},0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); ws.getRange2( "F3" ).setValue( "" ); ws.getRange2( "F106" ).setValue( "1" ); ws.getRange2( "F107" ).setValue( "" ); ws.getRange2( "F108" ).setValue( "" ); ws.getRange2( "F109" ).setValue( "" ); ws.getRange2( "F110" ).setValue( "2" ); ws.getRange2( "F111" ).setValue( "123" ); ws.getRange2( "F112" ).setValue( "4" ); ws.getRange2( "F113" ).setValue( "5" ); ws.getRange2( "F114" ).setValue( "6" ); ws.getRange2( "F115" ).setValue( "0" ); ws.getRange2( "F116" ).setValue( "" ); ws.getRange2( "F117" ).setValue( "0" ); oParser = new parserFormula( "MATCH(F3,F106:F114,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "MATCH(F3,F106:F117,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( "MATCH(0,F106:F114,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "MATCH(0,F106:F117,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( "MATCH(6,F106:F117,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 9 ); oParser = new parserFormula( "MATCH(6,F106:F117,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "MATCH(6,F106:F117,-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); //TODO excel по-другому работает /*oParser = new parserFormula( "MATCH(123,F106:F117,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 );*/ } ); test( "Test: \"INDEX\"", function () { ws.getRange2( "A651" ).setValue( "1" ); ws.getRange2( "A652" ).setValue( "2" ); ws.getRange2( "A653" ).setValue( "3" ); ws.getRange2( "A654" ).setValue( "4" ); ws.getRange2( "A655" ).setValue( "5" ); ws.getRange2( "B651" ).setValue( "6" ); ws.getRange2( "B652" ).setValue( "7" ); ws.getRange2( "B653" ).setValue( "8" ); ws.getRange2( "B654" ).setValue( "9" ); ws.getRange2( "B655" ).setValue( "10" ); ws.getRange2( "C651" ).setValue( "11" ); ws.getRange2( "C652" ).setValue( "12" ); ws.getRange2( "C653" ).setValue( "13" ); ws.getRange2( "C654" ).setValue( "14" ); ws.getRange2( "C655" ).setValue( "15" ); oParser = new parserFormula( "INDEX({\"Apples\",\"Lemons\";\"Bananas\",\"Pears\"},2,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Pears" ); oParser = new parserFormula( "INDEX({\"Apples\",\"Lemons\";\"Bananas\",\"Pears\"},1,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Lemons" ); oParser = new parserFormula( "INDEX(\"Apples\",2,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "INDEX({\"Apples\",\"Lemons\"},,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Lemons" ); //данная функция возвращает area а далее уже в функции simplifyRefType находится резальтат // - пересечение а ячейкой, где располагается формула oParser = new parserFormula( "INDEX(A651:C655,,2)", "A2", ws ); ok( oParser.parse() ); var parent = AscCommonExcel.g_oRangeCache.getAscRange(oParser.parent); strictEqual( oParser.simplifyRefType(oParser.calculate(), ws, parent.r1, parent.c1).getValue(), "#VALUE!" ); oParser = new parserFormula( "INDEX(A651:C655,,2)", "D651", ws ); ok( oParser.parse() ); parent = AscCommonExcel.g_oRangeCache.getAscRange(oParser.parent); strictEqual( oParser.simplifyRefType(oParser.calculate(), ws, parent.r1, parent.c1).getValue(), 6 ); oParser = new parserFormula( "INDEX(A651:C655,,2)", "D652", ws ); ok( oParser.parse() ); parent = AscCommonExcel.g_oRangeCache.getAscRange(oParser.parent); strictEqual( oParser.simplifyRefType(oParser.calculate(), ws, parent.r1, parent.c1).getValue(), 7 ); oParser = new parserFormula( "INDEX(A651:C655,,3)", "E652", ws ); ok( oParser.parse() ); parent = AscCommonExcel.g_oRangeCache.getAscRange(oParser.parent); strictEqual( oParser.simplifyRefType(oParser.calculate(), ws, parent.r1, parent.c1).getValue(), 12 ); oParser = new parserFormula( "INDEX(A651:C655,,4)", "E652", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "INDEX(A651:C655,,14)", "E652", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "INDEX(A651:C655,3,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 8 ); oParser = new parserFormula( "INDEX(A651:C655,10,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "INDEX(A651:C651,1,3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 11 ); oParser = new parserFormula( "INDEX(A651:C651,1,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 6 ); oParser = new parserFormula( "INDEX(A651:C651,0,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 1 ); oParser = new parserFormula( "INDEX(A651:C651,1,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 1 ); oParser = new parserFormula( "INDEX(A651:C651,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 6 ); oParser = new parserFormula( "INDEX(A651:C651,3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 11 ); oParser = new parserFormula( "INDEX(A651:C651,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "INDEX(A651:C652,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "INDEX(A651:C652,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "INDEX(A651:C652,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "INDEX(A651:C651,1,1,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 1 ); oParser = new parserFormula( "INDEX(A651:C651,1,1,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); } ); test( "Test: \"INDIRECT\"", function () { ws.getRange2( "A22" ).setValue( "B22" ); ws.getRange2( "B22" ).setValue( "1.333" ); ws.getRange2( "A23" ).setValue( "B23" ); ws.getRange2( "B23" ).setValue( "45" ); ws.getRange2( "A24" ).setValue( "George" ); ws.getRange2( "B24" ).setValue( "10" ); ws.getRange2( "A25" ).setValue( "25" ); ws.getRange2( "B25" ).setValue( "62" ); oParser = new parserFormula( "INDIRECT(A22)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 1.333 ); oParser = new parserFormula( "INDIRECT(A23)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 45 ); /*oParser = new parserFormula( "INDIRECT(A24)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 10 );*/ oParser = new parserFormula( 'INDIRECT("B"&A25)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 62 ); } ); test( "Test: \"OFFSET\"", function () { ws.getRange2( "C150" ).setValue( "1" ); ws.getRange2( "D150" ).setValue( "2" ); ws.getRange2( "E150" ).setValue( "3" ); ws.getRange2( "C151" ).setValue( "2" ); ws.getRange2( "D151" ).setValue( "3" ); ws.getRange2( "E151" ).setValue( "4" ); ws.getRange2( "C152" ).setValue( "3" ); ws.getRange2( "D152" ).setValue( "4" ); ws.getRange2( "E152" ).setValue( "5" ); oParser = new parserFormula( "OFFSET(C3,2,3,1,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "F5" ); oParser = new parserFormula( "SUM(OFFSET(C151:E155,-1,0,3,3))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 27 ); oParser = new parserFormula( "OFFSET(B3, -2, 0, 1, 1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "B1" ); oParser = new parserFormula( "OFFSET(B3, 0, 0, -1, 1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "B3" ); oParser = new parserFormula( "OFFSET(B3, 0, 0, -1, -1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "B3" ); oParser = new parserFormula( "OFFSET(B3, 0, 0,,)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "B3" ); oParser = new parserFormula( "OFFSET(B3, 0, 0, 1,)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "B3" ); oParser = new parserFormula( "OFFSET(B3, 0, 0, -2, -2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "A2:B3" ); oParser = new parserFormula( "OFFSET(B3, 0, 0, -1, -2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "A3:B3" ); oParser = new parserFormula( "OFFSET(B3, 0, 0, 0, -2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "#REF!" ); oParser = new parserFormula( "OFFSET(B3, 0, 0, 2, 0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "#REF!" ); oParser = new parserFormula( "OFFSET(C3:D4, 0, 0, 2, 2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "C3:D4" ); oParser = new parserFormula( "OFFSET(C3:D4, 0, 0, 3, 3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "C3:E5" ); oParser = new parserFormula( "OFFSET(C3:D4, 2, 2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "E5:F6" ); oParser = new parserFormula( "OFFSET(C3:D4,2,2,3,3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "E5:G7" ); oParser = new parserFormula( "OFFSET(C3:E6, 0, 0, 3, 3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "C3:E5" ); oParser = new parserFormula( "OFFSET(C3:D4, 0, 0, -2, -2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "B2:C3" ); oParser = new parserFormula( "OFFSET(C3:D4, 0, 0, -3, -3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "A1:C3" ); oParser = new parserFormula( "OFFSET(C3:E6, 0, 0, -3, -3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "A1:C3" ); oParser = new parserFormula( "OFFSET(F10:M17, 0, 0, -7,-5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "B4:F10" ); } ); /* * Financial */ test( "Test: \"FV\"", function () { function fv( rate, nper, pmt, pv, type ) { var res; if ( type === undefined || type === null ) type = 0; if ( pv === undefined || pv === null ) pv = 0; if ( rate != 0 ) { res = -1 * ( pv * Math.pow( 1 + rate, nper ) + pmt * ( 1 + rate * type ) * ( Math.pow( 1 + rate, nper ) - 1) / rate ); } else { res = -1 * ( pv + pmt * nper ); } return res; } oParser = new parserFormula( "FV(0.06/12,10,-200,-500,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fv( 0.06 / 12, 10, -200, -500, 1 ) ); oParser = new parserFormula( "FV(0.12/12,12,-1000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fv( 0.12 / 12, 12, -1000 ) ); oParser = new parserFormula( "FV(0.11/12,35,-2000,,1)", "A2", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - fv( 0.11 / 12, 35, -2000, null, 1 ) ) < dif ); oParser = new parserFormula( "FV(0.06/12,12,-100,-1000,1)", "A2", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - fv( 0.06 / 12, 12, -100, -1000, 1 ) ) < dif ); testArrayFormula2("FV", 3, 5); } ); test( "Test: \"PMT\"", function () { function pmt( rate, nper, pv, fv, type ) { var res; if ( type === undefined || type === null ) type = 0; if ( fv === undefined || fv === null ) fv = 0; if ( rate != 0 ) { res = -1 * ( pv * Math.pow( 1 + rate, nper ) + fv ) / ( ( 1 + rate * type ) * ( Math.pow( 1 + rate, nper ) - 1 ) / rate ); } else { res = -1 * ( pv + fv ) / nper; } return res; } oParser = new parserFormula( "PMT(0.08/12,10,10000)", "A2", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - pmt( 0.08 / 12, 10, 10000 ) ) < dif ); oParser = new parserFormula( "PMT(0.08/12,10,10000,0,1)", "A2", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - pmt( 0.08 / 12, 10, 10000, 0, 1 ) ) < dif ); testArrayFormula2("PMT", 3, 5); } ); test( "Test: \"NPER\"", function () { function nper(rate,pmt,pv,fv,type){ if ( rate === undefined || rate === null ) rate = 0; if ( pmt === undefined || pmt === null ) pmt = 0; if ( pv === undefined || pv === null ) pv = 0; if ( type === undefined || type === null ) type = 0; if ( fv === undefined || fv === null ) fv = 0; var res; if ( rate != 0 ) { res = (-fv * rate + pmt * (1 + rate * type)) / (rate * pv + pmt * (1 + rate * type)) res = Math.log( res ) / Math.log( 1+rate ) } else { res = (- pv - fv )/ pmt ; } return res; } oParser = new parserFormula( "NPER(0.12/12,-100,-1000,10000,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), nper(0.12/12,-100,-1000,10000,1) ); oParser = new parserFormula( "NPER(0.12/12,-100,-1000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), nper(0.12/12,-100,-1000) ); testArrayFormula2("NPER", 3, 5); } ); test( "Test: \"PV\"", function () { function pv( rate, nper, pmt, fv, type ) { if ( rate != 0 ) { return -1 * ( fv + pmt * (1 + rate * type) * ( (Math.pow( (1 + rate), nper ) - 1) / rate ) ) / Math.pow( 1 + rate, nper ) } else { return -1 * ( fv + pmt * nper ); } } oParser = new parserFormula( "PV(0.08/12,12*20,500,,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), pv( 0.08 / 12, 12 * 20, 500, 0, 0 ) ); oParser = new parserFormula( "PV(0,12*20,500,,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), pv( 0, 12 * 20, 500, 0, 0 ) ); testArrayFormula2("PV", 3, 5); } ); test( "Test: \"NPV\"", function () { oParser = new parserFormula( "NPV(0.1,-10000,3000,4200,6800)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1188.4434123352216 ); } ); test( "Test: \"EFFECT\"", function () { function effect(nr,np){ if( nr <= 0 || np < 1 ) return "#NUM!"; return Math.pow( ( 1 + nr/np ), np ) - 1; } oParser = new parserFormula( "EFFECT(0.0525,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), effect(0.0525,4) ); oParser = new parserFormula( "EFFECT(0.0525,-4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), effect(0.0525,-4) ); oParser = new parserFormula( "EFFECT(0.0525,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), effect(0.0525,1) ); oParser = new parserFormula( "EFFECT(-1,54)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), effect(-1,54) ); testArrayFormula2("EFFECT", 2, 2, true) } ); test( "Test: \"ISPMT\"", function () { function ISPMT( rate, per, nper, pv ){ return pv * rate * (per / nper - 1.0) } oParser = new parserFormula( "ISPMT(0.1/12,1,3*12,8000000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ISPMT(0.1/12,1,3*12,8000000) ); oParser = new parserFormula( "ISPMT(0.1,1,3,8000000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ISPMT(0.1,1,3,8000000) ); testArrayFormula2("ISPMT", 4, 4); } ); test( "Test: \"ISFORMULA\"", function () { ws.getRange2( "C150" ).setValue( "=TODAY()" ); ws.getRange2( "C151" ).setValue( "7" ); ws.getRange2( "C152" ).setValue( "Hello, world!" ); ws.getRange2( "C153" ).setValue( "=3/0" ); oParser = new parserFormula( "ISFORMULA(C150)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "TRUE" ); oParser = new parserFormula( "ISFORMULA(C151)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "FALSE" ); oParser = new parserFormula( "ISFORMULA(C152)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "FALSE" ); oParser = new parserFormula( "ISFORMULA(C153)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "TRUE" ); testArrayFormulaEqualsValues("FALSE,FALSE,FALSE,#N/A;FALSE,FALSE,FALSE,#N/A;#N/A,#N/A,#N/A,#N/A", "ISFORMULA(A1:C2)"); testArrayFormulaEqualsValues("FALSE,FALSE,#N/A,#N/A;FALSE,FALSE,#N/A,#N/A;FALSE,FALSE,#N/A,#N/A", "ISFORMULA(A1:B1)"); testArrayFormulaEqualsValues("FALSE,FALSE,FALSE,FALSE;FALSE,FALSE,FALSE,FALSE;FALSE,FALSE,FALSE,FALSE", "ISFORMULA(A1)"); } ); test( "Test: \"IFNA\"", function () { oParser = new parserFormula( 'IFNA(MATCH(30,B1:B5,0),"Not found")', "A2", ws ); ok( oParser.parse(), 'IFNA(MATCH(30,B1:B5,0),"Not found")' ); strictEqual( oParser.calculate().getValue(), "Not found", 'IFNA(MATCH(30,B1:B5,0),"Not found")' ); } ); test( "Test: \"IFERROR\"", function () { ws.getRange2( "A2" ).setValue( "210" ); ws.getRange2( "A3" ).setValue( "55" ); ws.getRange2( "A4" ).setValue( "" ); ws.getRange2( "B2" ).setValue( "35" ); ws.getRange2( "B3" ).setValue( "0" ); ws.getRange2( "B4" ).setValue( "23" ); oParser = new parserFormula( 'IFERROR(A2/B2,"Error in calculation")', "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( 'IFERROR(A3/B3,"Error in calculation")', "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 'Error in calculation'); oParser = new parserFormula( 'IFERROR(A4/B4,"Error in calculation")', "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0); //testArrayFormula2("IFERROR", 2, 2); } ); test( "Test: \"XNPV\"", function () { function xnpv( rate, valueArray, dateArray ){ var res = 0, r = rate; var d1 = dateArray[0]; for( var i = 0; i < dateArray.length; i++ ){ res += valueArray[i] / ( Math.pow( ( 1 + r ), ( dateArray[i] - d1 ) / 365 ) ) } return res; } ws.getRange2( "A701" ).setValue( "39448" ); ws.getRange2( "A702" ).setValue( "39508" ); ws.getRange2( "A703" ).setValue( "39751" ); ws.getRange2( "A704" ).setValue( "39859" ); ws.getRange2( "A705" ).setValue( "39904" ); oParser = new parserFormula( "XNPV(0.09,{-10000,2750,4250,3250,2750},A701:A705)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), xnpv( 0.09, [-10000,2750,4250,3250,2750], [39448,39508,39751,39859,39904] ) ); ws.getRange2( "A705" ).setValue( "43191" ); oParser = new parserFormula( "XNPV(0.09,{-10000,2750,4250,3250,2750},A701:A705)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), xnpv( 0.09, [-10000,2750,4250,3250,2750], [39448,39508,39751,39859,43191] ) ); } ); test( "Test: \"IRR\"", function () { function irr( costArr, x ){ if (!x) x = 0.1 var nC = 0, g_Eps = 1e-7, fEps = 1.0, fZ = 0, fN = 0, xN = 0, nIM = 100, nMC = 0,arr0 = costArr[0], arrI, wasNegative = false, wasPositive = false; if( arr0 < 0 ) wasNegative = true; else if( arr0 > 0 ) wasPositive = true; while(fEps > g_Eps && nMC < nIM ){ nC = 0; fZ = 0; fN = 0; fZ += costArr[0]/Math.pow( 1.0 + x, nC ); fN += -nC * costArr[0]/Math.pow( 1 + x, nC + 1 ); nC++; for(var i = 1; i < costArr.length; i++){ arrI = costArr[i]; fZ += arrI/Math.pow( 1.0 + x, nC ); fN += -nC * arrI/Math.pow( 1 + x, nC + 1 ); if( arrI < 0 ) wasNegative = true; else if( arrI > 0 ) wasPositive = true nC++ } xN = x - fZ / fN; nMC ++; fEps = Math.abs( xN - x ); x = xN; } if( !(wasNegative && wasPositive) ) return "#NUM!"; if (fEps < g_Eps) return x; else return "#NUM!"; } oParser = new parserFormula( "IRR({-70000,12000,15000,18000,21000})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -0.021244848273410923 ); ws.getRange2( "A705" ).setValue( "43191" ); oParser = new parserFormula( "IRR({-70000,12000,15000,18000,21000,26000})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0.08663094803653171 ); oParser = new parserFormula( "IRR({-70000,12000,15000},-0.1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -0.44350694133450463 ); oParser = new parserFormula( "IRR({-70000},-0.1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); //TODO пересмотреть тест для этой функции //testArrayFormula2("IRR", 1, 2, true) } ); test( "Test: \"ACCRINT\"", function () { oParser = new parserFormula( "ACCRINT(DATE(2006,3,1),DATE(2006,9,1),DATE(2006,5,1),0.1,1100,2,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 18.333333333333332 ); oParser = new parserFormula( "ACCRINT(DATE(2006,3,1),DATE(2006,9,1),DATE(2006,5,1),0.1,,2,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 16.666666666666664 ); oParser = new parserFormula( "ACCRINT(DATE(2008,3,1),DATE(2008,8,31),DATE(2010,5,1),0.1,1000,2,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 216.94444444444444 ); oParser = new parserFormula( "ACCRINT(DATE(2008,3,1),DATE(2008,8,31),DATE(2010,5,1),0.1,1000,2,0,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 216.94444444444444 ); oParser = new parserFormula( "ACCRINT(DATE(2008,3,1),DATE(2008,8,31),DATE(2010,5,1),0.1,1000,2,0,FALSE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 216.66666666666666 ); testArrayFormula2("ACCRINT", 6, 8, true); } ); test( "Test: \"ACCRINTM\"", function () { oParser = new parserFormula( "ACCRINTM(DATE(2006,3,1),DATE(2006,5,1),0.1,1100,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 18.333333333333332 ); oParser = new parserFormula( "ACCRINTM(DATE(2006,3,1),DATE(2006,5,1),0.1,,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 16.666666666666664 ); oParser = new parserFormula( "ACCRINTM(DATE(2006,3,1),DATE(2006,5,1),0.1,)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 16.666666666666664 ); testArrayFormula2("ACCRINTM", 4, 5, true) } ); test( "Test: \"AMORDEGRC\"", function () { oParser = new parserFormula( "AMORDEGRC(2400,DATE(2008,8,19),DATE(2008,12,31),300,1,0.15,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 776 ); oParser = new parserFormula( "AMORDEGRC(2400,DATE(2008,8,19),DATE(2008,12,31),300,1,0.50,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "AMORDEGRC(2400,DATE(2008,8,19),DATE(2008,12,31),300,1,0.20,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 819 ); oParser = new parserFormula( "AMORDEGRC(2400,DATE(2008,8,19),DATE(2008,12,31),300,1,0.33,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 972 ); testArrayFormula2("AMORDEGRC", 6, 7, true); } ); test( "Test: \"AMORLINC\"", function () { oParser = new parserFormula( "AMORLINC(2400,DATE(2008,8,19),DATE(2008,12,31),300,1,0.15,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 360 ); oParser = new parserFormula( "AMORLINC(2400,DATE(2008,8,19),DATE(2008,12,31),300,1,0.70,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1484 ); testArrayFormula2("AMORLINC", 6, 7, true); } ); test( "Test: \"CUMIPMT\"", function () { function cumipmt(fRate, nNumPeriods, fVal, nStartPer, nEndPer, nPayType){ var fRmz, fZinsZ; if( nStartPer < 1 || nEndPer < nStartPer || fRate <= 0.0 || nEndPer > nNumPeriods || nNumPeriods <= 0 || fVal <= 0.0 || ( nPayType != 0 && nPayType != 1 ) ) return "#NUM!" fRmz = _getPMT( fRate, nNumPeriods, fVal, 0.0, nPayType ); fZinsZ = 0.0; if( nStartPer == 1 ) { if( nPayType <= 0 ) fZinsZ = -fVal; nStartPer++; } for( var i = nStartPer ; i <= nEndPer ; i++ ) { if( nPayType > 0 ) fZinsZ += _getFV( fRate, i - 2, fRmz, fVal, 1 ) - fRmz; else fZinsZ += _getFV( fRate, i - 1, fRmz, fVal, 0 ); } fZinsZ *= fRate; return fZinsZ; } oParser = new parserFormula( "CUMIPMT(0.09/12,30*12,125000,1,1,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), cumipmt(0.09/12,30*12,125000,1,1,0) ); oParser = new parserFormula( "CUMIPMT(0.09/12,30*12,125000,13,24,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), cumipmt(0.09/12,30*12,125000,13,24,0) ); testArrayFormula2("CUMIPMT", 6, 6, true); } ); test( "Test: \"CUMPRINC\"", function () { function cumpring(fRate, nNumPeriods, fVal, nStartPer, nEndPer, nPayType){ var fRmz, fKapZ; if( nStartPer < 1 || nEndPer < nStartPer || nEndPer < 1 || fRate <= 0 || nNumPeriods <= 0 || fVal <= 0 || ( nPayType != 0 && nPayType != 1 ) ) return "#NUM!" fRmz = _getPMT( fRate, nNumPeriods, fVal, 0.0, nPayType ); fKapZ = 0.0; var nStart = nStartPer; var nEnd = nEndPer; if( nStart == 1 ) { if( nPayType <= 0 ) fKapZ = fRmz + fVal * fRate; else fKapZ = fRmz; nStart++; } for( var i = nStart ; i <= nEnd ; i++ ) { if( nPayType > 0 ) fKapZ += fRmz - ( _getFV( fRate, i - 2, fRmz, fVal, 1 ) - fRmz ) * fRate; else fKapZ += fRmz - _getFV( fRate, i - 1, fRmz, fVal, 0 ) * fRate; } return fKapZ } oParser = new parserFormula( "CUMPRINC(0.09/12,30*12,125000,1,1,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), cumpring(0.09/12,30*12,125000,1,1,0) ); oParser = new parserFormula( "CUMPRINC(0.09/12,30*12,-125000,1,1,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), cumpring(0.09/12,30*12,-125000,1,1,0) ); oParser = new parserFormula( "CUMPRINC(0.09/12,30*12,125000,13,24,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), cumpring(0.09/12,30*12,125000,13,24,0) ); testArrayFormula2("CUMPRINC", 6, 6, true); } ); test( "Test: \"NOMINAL\"", function () { function nominal(rate,np){ if( rate <= 0 || np < 1 ) return "#NUM!" return ( Math.pow( rate + 1, 1 / np ) - 1 ) * np; } oParser = new parserFormula( "NOMINAL(0.053543,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), nominal(0.053543,4) ); oParser = new parserFormula( "NOMINAL(0.053543,-4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), nominal(0.053543,-4) ); testArrayFormula2("NOMINAL", 2, 2, true); } ); test( "Test: \"NOT\"", function () { testArrayFormula2("NOT", 1, 1); } ); test( "Test: \"FVSCHEDULE\"", function () { function fvschedule(rate,shedList){ for( var i = 0; i < shedList.length; i++){ rate *= 1 + shedList[i] } return rate; } oParser = new parserFormula( "FVSCHEDULE(1,{0.09,0.11,0.1})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fvschedule(1,[0.09,0.11,0.1]) ); //testArrayFormula2("FVSCHEDULE", 2, 2, true, true); } ); test( "Test: \"DISC\"", function () { function disc( settlement, maturity, pr, redemption, basis ){ if( settlement >= maturity || pr <= 0 || redemption <= 0 || basis < 0 || basis > 4 ) return "#NUM!" return ( 1.0 - pr / redemption ) / AscCommonExcel.yearFrac( settlement, maturity, basis ); } oParser = new parserFormula( "DISC(DATE(2007,1,25),DATE(2007,6,15),97.975,100,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), disc( new cDate(2007,0,25),new cDate(2007,5,15),97.975,100,1 ) ); testArrayFormula2("DISC",4,5,true); } ); test( "Test: \"DOLLARDE\"", function () { function dollarde( fractionalDollar, fraction ){ if( fraction < 0 ) return "#NUM!"; else if( fraction == 0 ) return "#DIV/0!"; var fInt = Math.floor( fractionalDollar ), res = fractionalDollar - fInt; res /= fraction; res *= Math.pow( 10, Math.ceil( Math.log( fraction ) / Math.log( 10 ) ) ); res += fInt; return res; } oParser = new parserFormula( "DOLLARDE(1.02,16)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), dollarde( 1.02,16 ) ); oParser = new parserFormula( "DOLLARDE(1.1,32)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), dollarde( 1.1,32 ) ); testArrayFormula2("DOLLARDE", 2, 2, true); } ); test( "Test: \"DOLLARFR\"", function () { function dollarde( fractionalDollar, fraction ){ if( fraction < 0 ) return "#NUM!"; else if( fraction == 0 ) return "#DIV/0!"; var fInt = Math.floor( fractionalDollar ), res = fractionalDollar - fInt; res *= fraction; res *= Math.pow( 10.0, -Math.ceil( Math.log( fraction ) / Math.log( 10 ) ) ); res += fInt; return res; } oParser = new parserFormula( "DOLLARFR(1.125,16)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), dollarde( 1.125,16 ) ); oParser = new parserFormula( "DOLLARFR(1.125,32)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), dollarde( 1.125,32 ) ); testArrayFormula2("DOLLARFR", 2, 2, true); } ); test( "Test: \"RECEIVED\"", function () { function received( settlement, maturity, investment, discount, basis ){ if( settlement >= maturity || investment <= 0 || discount <= 0 || basis < 0 || basis > 4 ) return "#NUM!" return investment / ( 1 - ( discount * AscCommonExcel.yearFrac( settlement, maturity, basis) ) ) } oParser = new parserFormula( "RECEIVED(DATE(2008,2,15),DATE(2008,5,15),1000000,0.0575,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), received( new cDate(2008,1,15),new cDate(2008,4,15),1000000,0.0575,2 ) ); testArrayFormula2("RECEIVED", 4, 5, true); } ); test( "Test: \"RATE\"", function () { function RateIteration( fNper, fPayment, fPv, fFv, fPayType, fGuess ) { function approxEqual( a, b ) { if ( a == b ) return true; var x = a - b; return (x < 0.0 ? -x : x) < ((a < 0.0 ? -a : a) * (1.0 / (16777216.0 * 16777216.0))); } var bValid = true, bFound = false, fX, fXnew, fTerm, fTermDerivation, fGeoSeries, fGeoSeriesDerivation; var nIterationsMax = 150, nCount = 0, fEpsilonSmall = 1.0E-14, SCdEpsilon = 1.0E-7; fFv = fFv - fPayment * fPayType; fPv = fPv + fPayment * fPayType; if ( fNper == Math.round( fNper ) ) { fX = fGuess.fGuess; var fPowN, fPowNminus1; while ( !bFound && nCount < nIterationsMax ) { fPowNminus1 = Math.pow( 1.0 + fX, fNper - 1.0 ); fPowN = fPowNminus1 * (1.0 + fX); if ( approxEqual( Math.abs( fX ), 0.0 ) ) { fGeoSeries = fNper; fGeoSeriesDerivation = fNper * (fNper - 1.0) / 2.0; } else { fGeoSeries = (fPowN - 1.0) / fX; fGeoSeriesDerivation = fNper * fPowNminus1 / fX - fGeoSeries / fX; } fTerm = fFv + fPv * fPowN + fPayment * fGeoSeries; fTermDerivation = fPv * fNper * fPowNminus1 + fPayment * fGeoSeriesDerivation; if ( Math.abs( fTerm ) < fEpsilonSmall ) bFound = true; else { if ( approxEqual( Math.abs( fTermDerivation ), 0.0 ) ) fXnew = fX + 1.1 * SCdEpsilon; else fXnew = fX - fTerm / fTermDerivation; nCount++; bFound = (Math.abs( fXnew - fX ) < SCdEpsilon); fX = fXnew; } } bValid =(fX >=-1.0); } else { fX = (fGuess.fGuest < -1.0) ? -1.0 : fGuess.fGuest; while ( bValid && !bFound && nCount < nIterationsMax ) { if ( approxEqual( Math.abs( fX ), 0.0 ) ) { fGeoSeries = fNper; fGeoSeriesDerivation = fNper * (fNper - 1.0) / 2.0; } else { fGeoSeries = (Math.pow( 1.0 + fX, fNper ) - 1.0) / fX; fGeoSeriesDerivation = fNper * Math.pow( 1.0 + fX, fNper - 1.0 ) / fX - fGeoSeries / fX; } fTerm = fFv + fPv * pow( 1.0 + fX, fNper ) + fPayment * fGeoSeries; fTermDerivation = fPv * fNper * Math.pow( 1.0 + fX, fNper - 1.0 ) + fPayment * fGeoSeriesDerivation; if ( Math.abs( fTerm ) < fEpsilonSmall ) bFound = true; else { if ( approxEqual( Math.abs( fTermDerivation ), 0.0 ) ) fXnew = fX + 1.1 * SCdEpsilon; else fXnew = fX - fTerm / fTermDerivation; nCount++; bFound = (Math.abs( fXnew - fX ) < SCdEpsilon); fX = fXnew; bValid = (fX >= -1.0); } } } fGuess.fGuess = fX; return bValid && bFound; } function rate(nper, pmt, pv, fv, type, quess){ if ( fv === undefined ) fv = 0; if ( type === undefined ) type = 0; if ( quess === undefined ) quess = 0.1; var res = {fGuess:0}; if( RateIteration(nper, pmt, pv, fv, type, res) ) return res.fGuess; return "#VALUE!" } oParser = new parserFormula( "RATE(4*12,-200,8000)", "A2", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), rate(4*12,-200,8000) ), true ); oParser = new parserFormula( "RATE(4*12,-200,8000)*12", "A2", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), rate(4*12,-200,8000)*12 ), true ); testArrayFormula2("RATE", 3, 6, true); } ); test( "Test: \"RRI\"", function () { oParser = new parserFormula( "RRI(96, 10000, 11000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0009933 ); oParser = new parserFormula( "RRI(0, 10000, 11000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "RRI(-10, 10000, 11000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "RRI(10, 10000, -11000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "RRI(1, 1, -1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -2 ); testArrayFormula2("RRI", 3, 3); } ); test( "Test: \"INTRATE\"", function () { function intrate( settlement, maturity, investment, redemption, basis ){ if( settlement >= maturity || investment <= 0 || redemption <= 0 || basis < 0 || basis > 4 ) return "#NUM!" return ( ( redemption / investment ) - 1 ) / AscCommonExcel.yearFrac( settlement, maturity, basis ) } oParser = new parserFormula( "INTRATE(DATE(2008,2,15),DATE(2008,5,15),1000000,1014420,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), intrate( new cDate(2008,1,15),new cDate(2008,4,15),1000000,1014420,2 ) ); testArrayFormula2("INTRATE", 4, 5, true); } ); test( "Test: \"TBILLEQ\"", function () { function tbilleq( settlement, maturity, discount ){ maturity = cDate.prototype.getDateFromExcel(maturity.getExcelDate() + 1); var d1 = settlement, d2 = maturity; var date1 = d1.getDate(), month1 = d1.getMonth(), year1 = d1.getFullYear(), date2 = d2.getDate(), month2 = d2.getMonth(), year2 = d2.getFullYear(); var nDiff = GetDiffDate360( date1, month1, year1, date2, month2, year2, true ); if( settlement >= maturity || discount <= 0 || nDiff > 360 ) return "#NUM!"; return ( 365 * discount ) / ( 360 - discount * nDiff ); } oParser = new parserFormula( "TBILLEQ(DATE(2008,3,31),DATE(2008,6,1),0.0914)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), tbilleq( new cDate(Date.UTC(2008,2,31)), new cDate(Date.UTC(2008,5,1)), 0.0914 ) ); testArrayFormula2("TBILLEQ", 3, 3, true); } ); test( "Test: \"TBILLPRICE\"", function () { function tbillprice( settlement, maturity, discount ){ maturity = cDate.prototype.getDateFromExcel(maturity.getExcelDate() + 1) var d1 = settlement var d2 = maturity var fFraction = AscCommonExcel.yearFrac(d1, d2, 0); if( fFraction - Math.floor( fFraction ) == 0 ) return "#NUM!"; return 100 * ( 1 - discount * fFraction ); } oParser = new parserFormula( "TBILLPRICE(DATE(2008,3,31),DATE(2008,6,1),0.09)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), tbillprice( new cDate(Date.UTC(2008,2,31)), new cDate(Date.UTC(2008,5,1)), 0.09 ) ); testArrayFormula2("TBILLPRICE", 3, 3, true); } ); test( "Test: \"TBILLYIELD\"", function () { function tbillyield( settlement, maturity, pr ){ var d1 = settlement; var d2 = maturity; var date1 = d1.getDate(), month1 = d1.getMonth(), year1 = d1.getFullYear(), date2 = d2.getDate(), month2 = d2.getMonth(), year2 = d2.getFullYear(); var nDiff = GetDiffDate360( date1, month1, year1, date2, month2, year2, true ); nDiff++; if( settlement >= maturity || pr <= 0 || nDiff > 360 ) return "#NUM!"; return ( ( 100 - pr ) / pr) * (360 / nDiff); } oParser = new parserFormula( "TBILLYIELD(DATE(2008,3,31),DATE(2008,6,1),98.45)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), tbillyield( new cDate(2008,2,31), new cDate(2008,5,1), 98.45 ) ); } ); test( "Test: \"COUPDAYBS\"", function () { function coupdaybs( settlement, maturity, frequency, basis ){ basis = ( basis !== undefined ? basis : 0 ); return _getcoupdaybs(settlement, maturity, frequency, basis) } oParser = new parserFormula( "COUPDAYBS(DATE(2007,1,25),DATE(2008,11,15),2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 71 ); oParser = new parserFormula( "COUPDAYBS(DATE(2007,1,25),DATE(2008,11,15),2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), coupdaybs( new cDate(2007,0,25), new cDate(2008,10,15), 2 ) ); testArrayFormula2("COUPDAYBS", 3, 4, true); } ); test( "Test: \"COUPDAYS\"", function () { function coupdays( settlement, maturity, frequency, basis ){ basis = ( basis !== undefined ? basis : 0 ); return _getcoupdays(settlement, maturity, frequency, basis) } oParser = new parserFormula( "COUPDAYS(DATE(2007,1,25),DATE(2008,11,15),2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), coupdays( new cDate(2007,0,25), new cDate(2008,10,15), 2, 1 ) ); oParser = new parserFormula( "COUPDAYS(DATE(2007,1,25),DATE(2008,11,15),2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), coupdays( new cDate(2007,0,25), new cDate(2008,10,15), 2 ) ); testArrayFormula2("COUPDAYS", 3, 4, true); } ); test( "Test: \"COUPDAYSNC\"", function () { function coupdaysnc( settlement, maturity, frequency, basis ) { basis = ( basis !== undefined ? basis : 0 ); if ( (basis != 0) && (basis != 4) ) { _lcl_GetCoupncd( settlement, maturity, frequency ); return _diffDate( settlement, maturity, basis ); } return _getcoupdays( new cDate( settlement ), new cDate( maturity ), frequency, basis ) - _getcoupdaybs( new cDate( settlement ), new cDate( maturity ), frequency, basis ); } oParser = new parserFormula( "COUPDAYSNC(DATE(2007,1,25),DATE(2008,11,15),2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 110 ); oParser = new parserFormula( "COUPDAYSNC(DATE(2007,1,25),DATE(2008,11,15),2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), coupdaysnc( new cDate(2007,0,25), new cDate(2008,10,15), 2 ) ); testArrayFormula2("COUPDAYSNC", 3, 4, true); } ); test( "Test: \"COUPNCD\"", function () { function coupncd( settlement, maturity, frequency, basis ) { basis = ( basis !== undefined ? basis : 0 ); _lcl_GetCoupncd( settlement, maturity, frequency ); return maturity.getExcelDate(); } oParser = new parserFormula( "COUPNCD(DATE(2007,1,25),DATE(2008,11,15),2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), coupncd( new cDate(Date.UTC(2007,0,25)), new cDate(Date.UTC(2008,10,15)), 2, 1 ) ); testArrayFormula2("COUPNCD", 3, 4, true); } ); test( "Test: \"COUPNUM\"", function () { oParser = new parserFormula( "COUPNUM(DATE(2007,1,25),DATE(2008,11,15),2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _coupnum( new cDate(2007,0,25), new cDate(2008,10,15), 2, 1 ) ); testArrayFormula2("COUPNUM", 3, 4, true); } ); test( "Test: \"COUPPCD\"", function () { function couppcd( settlement, maturity, frequency, basis ) { basis = ( basis !== undefined ? basis : 0 ); _lcl_GetCouppcd( settlement, maturity, frequency ); return maturity.getExcelDate(); } oParser = new parserFormula( "COUPPCD(DATE(2007,1,25),DATE(2008,11,15),2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), couppcd( new cDate(Date.UTC(2007,0,25)), new cDate(Date.UTC(2008,10,15)), 2, 1 ) ); testArrayFormula2("COUPPCD", 3, 4, true); } ); test( "Test: \"CONVERT\"", function () { oParser = new parserFormula( 'CONVERT(68, "F", "C")', "A2", ws ); ok( oParser.parse(), 'CONVERT(68, "F", "C")' ); strictEqual( oParser.calculate().getValue(), 20, 'CONVERT(68, "F", "C")' ); oParser = new parserFormula( 'CONVERT(2.5, "ft", "sec")', "A2", ws ); ok( oParser.parse(), 'CONVERT(2.5, "ft", "sec")' ); strictEqual( oParser.calculate().getValue(), "#N/A", 'CONVERT(2.5, "ft", "sec")' ); oParser = new parserFormula( 'CONVERT(CONVERT(100,"ft","m"),"ft","m")', "A2", ws ); ok( oParser.parse(), 'CONVERT(CONVERT(100,"ft","m"),"ft","m")' ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 9.290304, 'CONVERT(CONVERT(100,"ft","m"),"ft","m")' ); oParser = new parserFormula( 'CONVERT(7,"bit","byte")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(3) - 0, 0.875 ); oParser = new parserFormula( 'CONVERT(7,"admkn","kn")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14) - 0, 6.99999939524838 ); oParser = new parserFormula( 'CONVERT(7,"admkn","m/s")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 3.6011108 ); oParser = new parserFormula( 'CONVERT(7,"admkn","mph")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 8.0554554 ); oParser = new parserFormula( 'CONVERT(7,"m/h","m/sec")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0019444 ); oParser = new parserFormula( 'CONVERT(7,"m/hr","mph")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0043496 ); oParser = new parserFormula( 'CONVERT(7,"m","mi")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0043496 ); oParser = new parserFormula( 'CONVERT(7,"m","Pica")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 19842.5196850 ); oParser = new parserFormula( 'CONVERT(7,"m","pica")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 1653.5433071 ); oParser = new parserFormula( 'CONVERT(7,"Nmi","pica")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 3062362.2047251 ); oParser = new parserFormula( 'CONVERT(7,"yr","day")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2556.75 ); oParser = new parserFormula( 'CONVERT(7,"yr","min")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3681720 ); oParser = new parserFormula( 'CONVERT(7,"day","min")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10080 ); oParser = new parserFormula( 'CONVERT(7,"hr","sec")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 25200 ); oParser = new parserFormula( 'CONVERT(7,"min","sec")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 420 ); oParser = new parserFormula( 'CONVERT(7,"Pa","mmHg")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0525043 ); oParser = new parserFormula( 'CONVERT(7,"Pa","psi")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0010153 ); oParser = new parserFormula( 'CONVERT(7,"Pa","Torr")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0525045 ); oParser = new parserFormula( 'CONVERT(7,"g","sg")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0004797 ); oParser = new parserFormula( 'CONVERT(7,"g","lbm")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0154324 ); oParser = new parserFormula( 'CONVERT(1, "lbm", "kg")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.4535924 ); oParser = new parserFormula( 'CONVERT(1, "lbm", "mg")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(0) - 0, 453592 ); oParser = new parserFormula( 'CONVERT(1, "klbm", "mg")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); testArrayFormula2("CONVERT", 3, 3, true); } ); test( "Test: \"PRICE\"", function () { oParser = new parserFormula( "PRICE(DATE(2008,2,15),DATE(2017,11,15),0.0575,0.065,100,2,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _getprice( new cDate( Date.UTC(2008, 1, 15 )), new cDate( Date.UTC(2017, 10, 15 )), 0.0575, 0.065, 100, 2, 0 ) ); testArrayFormula2("PRICE", 6, 7, true); } ); test( "Test: \"PRICEDISC\"", function () { function pricedisc(settl, matur, discount, redemption, basis){ return redemption * ( 1.0 - discount * _getdiffdate( settl, matur, basis ) ); } oParser = new parserFormula( "PRICEDISC(DATE(2008,2,16),DATE(2008,3,1),0.0525,100,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), pricedisc( new cDate(2008,1,16), new cDate(2008,2,1),0.0525,100,2 ) ); testArrayFormula2("PMT", 4, 5, true); } ); test( "Test: \"PRICEMAT\"", function () { function pricemat( settl, matur, iss, rate, yld, basis ) { var fIssMat = _yearFrac( new cDate(iss), new cDate(matur), basis ); var fIssSet = _yearFrac( new cDate(iss), new cDate(settl), basis ); var fSetMat = _yearFrac( new cDate(settl), new cDate(matur), basis ); var res = 1.0 + fIssMat * rate; res /= 1.0 + fSetMat * yld; res -= fIssSet * rate; res *= 100.0; return res; } oParser = new parserFormula( "PRICEMAT(DATE(2008,2,15),DATE(2008,4,13),DATE(2007,11,11),0.061,0.061,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), pricemat( new cDate(2008,1,15),new cDate(2008,3,13),new cDate(2007,10,11),0.061,0.061,0 ) ); testArrayFormula2("PRICEMAT", 5, 6, true); } ); test( "Test: \"YIELD\"", function () { oParser = new parserFormula( "YIELD(DATE(2008,2,15),DATE(2016,11,15),0.0575,95.04287,100,2,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _getYield( new cDate(Date.UTC(2008,1,15)), new cDate(Date.UTC(2016,10,15)),0.0575,95.04287,100,2,0 ) ); testArrayFormula2("YIELD", 6, 7, true); } ); test( "Test: \"YIELDDISC\"", function () { function yielddisc( settlement, maturity, pr, redemption, basis ){ var fRet = ( redemption / pr ) - 1.0; fRet /= _yearFrac( settlement, maturity, basis ); return fRet; } oParser = new parserFormula( "YIELDDISC(DATE(2008,2,16),DATE(2008,3,1),99.795,100,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), yielddisc( new cDate( 2008, 1, 16 ), new cDate( 2008, 2, 1 ), 99.795, 100, 2 ) ); testArrayFormula2("YIELDDISC", 4, 5, true); } ); test( "Test: \"YIELDMAT\"", function () { oParser = new parserFormula( "YIELDMAT(DATE(2008,3,15),DATE(2008,11,3),DATE(2007,11,8),0.0625,100.0123,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _getyieldmat( new cDate( 2008, 2, 15 ), new cDate( 2008, 10, 3 ), new cDate( 2007, 10, 8 ), 0.0625, 100.0123, 0 ) ); testArrayFormula2("YIELDMAT", 5, 6, true); } ); test( "Test: \"ODD\"", function () { oParser = new parserFormula( "ODD(1.5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "ODD(3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "ODD(2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "ODD(-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1 ); oParser = new parserFormula( "ODD(-2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -3 ); testArrayFormula("ODD"); } ); test( "Test: \"ODDLPRICE\"", function () { function oddlprice( settlement, maturity, last_interest, rate, yld, redemption, frequency, basis ){ var fDCi = _yearFrac( last_interest, maturity, basis ) * frequency; var fDSCi = _yearFrac( settlement, maturity, basis ) * frequency; var fAi = _yearFrac( last_interest, settlement, basis ) * frequency; var res = redemption + fDCi * 100.0 * rate / frequency; res /= fDSCi * yld / frequency + 1.0; res -= fAi * 100.0 * rate / frequency; return res; } oParser = new parserFormula( "ODDLPRICE(DATE(2008,11,11),DATE(2021,3,1),DATE(2008,10,15),0.0785,0.0625,100,2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), oddlprice( new cDate(Date.UTC(2008,10,11)), new cDate(Date.UTC(2021,2,1)), new cDate(Date.UTC(2008,9,15)), 0.0785, 0.0625, 100, 2, 1 ) ); testArrayFormula2("ODDLPRICE", 7, 8, true); } ); test( "Test: \"ODDLYIELD\"", function () { function oddlyield( settlement, maturity, last_interest, rate, pr, redemption, frequency, basis ){ var fDCi = _yearFrac( last_interest, maturity, basis ) * frequency; var fDSCi = _yearFrac( settlement, maturity, basis ) * frequency; var fAi = _yearFrac( last_interest, settlement, basis ) * frequency; var res = redemption + fDCi * 100.0 * rate / frequency; res /= pr + fAi * 100.0 * rate / frequency; res--; res *= frequency / fDSCi; return res; } oParser = new parserFormula( "ODDLYIELD(DATE(2008,11,11),DATE(2021,3,1),DATE(2008,10,15),0.0575,84.5,100,2,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), oddlyield( new cDate(2008,10,11), new cDate(2021,2,1), new cDate(2008,9,15), 0.0575, 84.5, 100, 2, 0 ) ); testArrayFormula2("ODDLYIELD", 7, 8, true); } ); test( "Test: \"DURATION\"", function () { oParser = new parserFormula( "DURATION(DATE(2008,1,1),DATE(2016,1,1),0.08,0.09,2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _duration( new cDate(Date.UTC(2008,0,1)), new cDate(Date.UTC(2016,0,1)), 0.08, 0.09, 2, 1 ) ); oParser = new parserFormula( "DURATION(DATE(2008,1,1),DATE(2016,1,1),-0.08,0.09,2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _duration( new cDate(Date.UTC(2008,0,1)), new cDate(Date.UTC(2016,0,1)), -0.08, 0.09, 2, 1 ) ); oParser = new parserFormula( "DURATION(DATE(2008,1,1),DATE(2016,1,1),-0.08,0.09,5,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _duration( new cDate(Date.UTC(2008,0,1)), new cDate(Date.UTC(2016,0,1)), -0.08, 0.09, 5, 1 ) ); testArrayFormula2("DURATION", 5, 6, true); } ); test( "Test: \"MDURATION\"", function () { function mduration(settl, matur, coupon, yld, frequency, basis){ return _duration( settl, matur, coupon, yld, frequency, basis ) / (1 + yld/frequency); } oParser = new parserFormula( "MDURATION(DATE(2008,1,1),DATE(2016,1,1),0.08,0.09,2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), mduration( new cDate(Date.UTC(2008,0,1)), new cDate(Date.UTC(2016,0,1)), 0.08, 0.09, 2, 1 ) ); testArrayFormula2("MDURATION", 5, 6, true); } ); test( "Test: \"MDETERM\"", function () { ws.getRange2( "A2" ).setValue( "1" ); ws.getRange2( "A3" ).setValue( "1" ); ws.getRange2( "A4" ).setValue( "1" ); ws.getRange2( "A5" ).setValue( "7" ); ws.getRange2( "B2" ).setValue( "3" ); ws.getRange2( "B3" ).setValue( "3" ); ws.getRange2( "B4" ).setValue( "1" ); ws.getRange2( "B5" ).setValue( "3" ); ws.getRange2( "C2" ).setValue( "8" ); ws.getRange2( "C3" ).setValue( "6" ); ws.getRange2( "C4" ).setValue( "1" ); ws.getRange2( "C5" ).setValue( "10" ); ws.getRange2( "D2" ).setValue( "5" ); ws.getRange2( "D3" ).setValue( "1" ); ws.getRange2( "D4" ).setValue( "0" ); ws.getRange2( "D5" ).setValue( "2" ); oParser = new parserFormula( "MDETERM(A2:D5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 88 ); oParser = new parserFormula( "MDETERM({3,6,1;1,1,0;3,10,2})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "MDETERM({3,6;1,1})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -3 ); oParser = new parserFormula( "MDETERM({1,3,8,5;1,3,6,1})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); } ); test( "Test: \"SYD\"", function () { function syd( cost, salvage, life, per ){ if( life == -1 || life == 0 ) return "#NUM!"; var res = 2; res *= cost - salvage; res *= life+1-per; res /= (life+1)*life; return res < 0 ? "#NUM!" : res; } oParser = new parserFormula( "SYD(30000,7500,10,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), syd( 30000,7500,10,1 ) ); oParser = new parserFormula( "SYD(30000,7500,-1,10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), syd( 30000,7500,-1,10 ) ); oParser = new parserFormula( "SYD(30000,7500,-10,10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), syd( 30000,7500,-10,10 ) ); testArrayFormula2("SYD", 4, 4); } ); test( "Test: \"PPMT\"", function () { function ppmt( rate, per, nper, pv, fv, type ){ if( fv == undefined ) fv = 0; if( type == undefined ) type = 0; var fRmz = _getPMT(rate, nper, pv, fv, type); return fRmz - _getIPMT(rate, per, pv, type, fRmz); } oParser = new parserFormula( "PPMT(0.1/12,1,2*12,2000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ppmt( 0.1/12,1,2*12,2000 ) ); oParser = new parserFormula( "PPMT(0.08,10,10,200000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ppmt( 0.08,10,10,200000 ) ); testArrayFormula2("PPMT", 4, 6); } ); test( "Test: \"MIRR\"", function () { function mirr( valueArray, fRate1_invest, fRate1_reinvest ){ fRate1_invest = fRate1_invest + 1; fRate1_reinvest = fRate1_reinvest + 1; var fNPV_reinvest = 0, fPow_reinvest = 1, fNPV_invest = 0, fPow_invest = 1, fCellValue, wasNegative = false, wasPositive = false; for(var i = 0; i < valueArray.length; i++){ fCellValue = valueArray[i]; if( fCellValue > 0 ){ wasPositive = true; fNPV_reinvest += fCellValue * fPow_reinvest; } else if( fCellValue < 0 ){ wasNegative = true; fNPV_invest += fCellValue * fPow_invest; } fPow_reinvest /= fRate1_reinvest; fPow_invest /= fRate1_invest; } if( !( wasNegative && wasPositive ) ) return "#DIV/0!"; var fResult = -fNPV_reinvest / fNPV_invest; fResult *= Math.pow( fRate1_reinvest, valueArray.length - 1 ); fResult = Math.pow( fResult, 1 / (valueArray.length - 1) ); return fResult - 1; } oParser = new parserFormula( "MIRR({-120000,39000,30000,21000,37000,46000},0.1,0.12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), mirr( [-120000,39000,30000,21000,37000,46000],0.1,0.12 ) ); oParser = new parserFormula( "MIRR({-120000,39000,30000,21000},0.1,0.12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), mirr( [-120000,39000,30000,21000],0.1,0.12 ) ); oParser = new parserFormula( "MIRR({-120000,39000,30000,21000,37000,46000},0.1,0.14)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), mirr( [-120000,39000,30000,21000,37000,46000],0.1,0.14 ) ); //testArrayFormula2("MIRR", 3, 3, null, true); } ); test( "Test: \"IPMT\"", function () { function ipmt( rate, per, nper, pv, fv, type ){ if( fv == undefined ) fv = 0; if( type == undefined ) type = 0; var res = AscCommonExcel.getPMT(rate, nper, pv, fv, type); res = AscCommonExcel.getIPMT(rate, per, pv, type, res); return res; } oParser = new parserFormula( "IPMT(0.1/12,1*3,3,8000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ipmt( 0.1/12,1*3,3,8000 ) ); oParser = new parserFormula( "IPMT(0.1,3,3,8000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ipmt( 0.1,3,3,8000 ) ); testArrayFormula2("IPMT", 4, 6); } ); test( "Test: \"DB\"", function () { function db( cost, salvage, life, period, month ){ if ( salvage >= cost ) { return this.value = new AscCommonExcel.cNumber( 0 ); } if ( month < 1 || month > 12 || salvage < 0 || life <= 0 || period < 0 || life + 1 < period || cost < 0 ) { return "#NUM!"; } var nAbRate = 1 - Math.pow( salvage / cost, 1 / life ); nAbRate = Math.floor( (nAbRate * 1000) + 0.5 ) / 1000; var nErsteAbRate = cost * nAbRate * month / 12; var res = 0; if ( Math.floor( period ) == 1 ) res = nErsteAbRate; else { var nSummAbRate = nErsteAbRate, nMin = life; if ( nMin > period ) nMin = period; var iMax = Math.floor( nMin ); for ( var i = 2; i <= iMax; i++ ) { res = (cost - nSummAbRate) * nAbRate; nSummAbRate += res; } if ( period > life ) res = ((cost - nSummAbRate) * nAbRate * (12 - month)) / 12; } return res } oParser = new parserFormula( "DB(1000000,100000,6,1,7)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), db(1000000,100000,6,1,7) ); oParser = new parserFormula( "DB(1000000,100000,6,2,7)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), db(1000000,100000,6,2,7) ); oParser = new parserFormula( "DB(1000000,100000,6,3,7)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), db(1000000,100000,6,3,7) ); oParser = new parserFormula( "DB(1000000,100000,6,4,7)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), db(1000000,100000,6,4,7) ); oParser = new parserFormula( "DB(1000000,100000,6,5,7)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), db(1000000,100000,6,5,7) ); oParser = new parserFormula( "DB(1000000,100000,6,6,7)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), db(1000000,100000,6,6,7) ); oParser = new parserFormula( "DB(1000000,100000,6,7,7)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), db(1000000,100000,6,7,7) ); testArrayFormula2("DB",4,5); } ); test( "Test: \"DDB\"", function () { function ddb( cost, salvage, life, period, factor ){ if( factor === undefined || factor === null ) factor = 2; return _getDDB(cost, salvage, life, period, factor); } oParser = new parserFormula( "DDB(2400,300,10*365,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ddb(2400,300,10*365,1) ); oParser = new parserFormula( "DDB(2400,300,10*12,1,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ddb(2400,300,10*12,1,2) ); oParser = new parserFormula( "DDB(2400,300,10,1,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ddb(2400,300,10,1,2) ); oParser = new parserFormula( "DDB(2400,300,10,2,1.5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ddb(2400,300,10,2,1.5) ); oParser = new parserFormula( "DDB(2400,300,10,10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ddb(2400,300,10,10) ); //TODO format $ ws.getRange2( "A102" ).setValue( "2400" ); ws.getRange2( "A103" ).setValue( "300" ); ws.getRange2( "A104" ).setValue( "10" ); oParser = new parserFormula( "DDB(A102,A103,A104*365,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 1.32 ); oParser = new parserFormula( "DDB(A102,A103,A104*12,1,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 40 ); oParser = new parserFormula( "DDB(A102,A103,A104,1,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 480 ); oParser = new parserFormula( "DDB(A102,A103,A104,2,1.5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(0) - 0, 306 ); oParser = new parserFormula( "DDB(A102,A103,A104,10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 22.12 ); oParser = new parserFormula( "DDB(A102,A103,0,10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("DDB",4,5); } ); test( "Test: \"SLN\"", function () { function sln( cost, salvage, life ){ if ( life == 0 ) return "#NUM!"; return ( cost - salvage ) / life; } oParser = new parserFormula( "SLN(30000,7500,10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), sln(30000,7500,10) ); testArrayFormula2("SLN", 3, 3); } ); test( "Test: \"XIRR\"", function () { function lcl_sca_XirrResult( rValues, rDates, fRate ) { var D_0 = rDates[0]; var r = fRate + 1; var fResult = rValues[0]; for ( var i = 1, nCount = rValues.length; i < nCount; ++i ) fResult += rValues[i] / Math.pow( r, (rDates[i] - D_0) / 365 ); return fResult; } function lcl_sca_XirrResult_Deriv1( rValues, rDates, fRate ) { var D_0 = rDates[0]; var r = fRate + 1; var fResult = 0; for ( var i = 1, nCount = rValues.length; i < nCount; ++i ) { var E_i = (rDates[i] - D_0) / 365; fResult -= E_i * rValues[i] / Math.pow( r, E_i + 1 ); } return fResult; } function xirr( valueArray, dateArray, rate ) { var res = rate if ( res <= -1 ) return "#NUM!" var fMaxEps = 1e-6, maxIter = 100; var newRate, eps, xirrRes, bContLoop; do { xirrRes = lcl_sca_XirrResult( valueArray, dateArray, res ); newRate = res - xirrRes / lcl_sca_XirrResult_Deriv1( valueArray, dateArray, res ); eps = Math.abs( newRate - res ); res = newRate; bContLoop = (eps > fMaxEps) && (Math.abs( xirrRes ) > fMaxEps); } while ( --maxIter && bContLoop ); if ( bContLoop ) return "#NUM!"; return res; } ws.getRange2( "F100" ).setValue( "1/1/2008" ); ws.getRange2( "G100" ).setValue( "3/1/2008" ); ws.getRange2( "H100" ).setValue( "10/30/2008" ); ws.getRange2( "I100" ).setValue( "2/15/2009" ); ws.getRange2( "J100" ).setValue( "4/1/2009" ); oParser = new parserFormula( "XIRR({-10000,2750,4250,3250,2750},F100:J100,0.1)", "A2", ws ); ok( oParser.parse() ); ok( difBetween( oParser.calculate().getValue(), 0.3733625335188316 ) ); ws.getRange2( "F100" ).setValue( 0 ); ok( oParser.parse() ); ok( difBetween( oParser.calculate().getValue(), 0.0024114950175866895 ) ); } ); test( "Test: \"VDB\"", function () { function _getVDB( cost, salvage, life, life1, startperiod, factor){ var fVdb=0, nLoopEnd = end = Math.ceil(startperiod), fTerm, fLia = 0, fRestwert = cost - salvage, bNowLia = false, fGda; for ( var i = 1; i <= nLoopEnd; i++){ if(!bNowLia){ fGda = _getDDB(cost, salvage, life, i, factor); fLia = fRestwert/ (life1 - (i-1)); if (fLia > fGda){ fTerm = fLia; bNowLia = true; } else{ fTerm = fGda; fRestwert -= fGda; } } else{ fTerm = fLia; } if ( i == nLoopEnd) fTerm *= ( startperiod + 1.0 - end ); fVdb += fTerm; } return fVdb; } function vdb( cost, salvage, life, startPeriod, endPeriod, factor, flag ) { if( factor === undefined || factor === null ) factor = 2; if( flag === undefined || flag === null ) flag = false; var start = Math.floor(startPeriod), end = Math.ceil(endPeriod), loopStart = start, loopEnd = end; var res = 0; if ( flag ) { for ( var i = loopStart + 1; i <= loopEnd; i++ ) { var ddb = _getDDB( cost, salvage, life, i, factor ); if ( i == loopStart + 1 ) ddb *= ( Math.min( endPeriod, start + 1 ) - startPeriod ); else if ( i == loopEnd ) ddb *= ( endPeriod + 1 - end ); res += ddb; } } else { var life1 = life; if ( !Math.approxEqual( startPeriod, Math.floor( startPeriod ) ) ) { if ( factor > 1 ) { if ( startPeriod > life / 2 || Math.approxEqual( startPeriod, life / 2 ) ) { var fPart = startPeriod - life / 2; startPeriod = life / 2; endPeriod -= fPart; life1 += 1; } } } cost -= _getVDB( cost, salvage, life, life1, startPeriod, factor ); res = _getVDB( cost, salvage, life, life - startPeriod, endPeriod - startPeriod, factor ); } return res; } oParser = new parserFormula( "VDB(2400,300,10*365,0,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), vdb(2400,300,10*365,0,1) ); oParser = new parserFormula( "VDB(2400,300,10*12,0,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), vdb(2400,300,10*12,0,1) ); oParser = new parserFormula( "VDB(2400,300,10*12,6,18)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), vdb(2400,300,10*12,6,18) ); oParser = new parserFormula( "VDB(0,0,0,0,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); testArrayFormula2("VDB", 5, 7); } ); test( "Test: \"ODDFPRICE\"", function () { oParser = new parserFormula( "ODDFPRICE(DATE(1999,2,28),DATE(2016,1,1),DATE(1998,2,28),DATE(2015,1,1),7%,0,100,2,1)", "A2", ws ); ok( oParser.parse() ); ok( difBetween(oParser.calculate().getValue(), 217.878453038674) ); oParser = new parserFormula( "ODDFPRICE(DATE(2008,11,11),DATE(2021,3,1),DATE(2008,10,15),DATE(2009,3,1),0.0785,0.0625,100,2,1)", "A2", ws ); ok( oParser.parse() ); ok( difBetween(oParser.calculate().getValue(), 113.597717474079) ); oParser = new parserFormula( "ODDFPRICE(DATE(1990,6,1),DATE(1995,12,31),DATE(1990,1,1),DATE(1990,12,31),6%,5%,1000,1,1)", "A2", ws ); ok( oParser.parse() ); ok( difBetween(oParser.calculate().getValue(), 790.11323221867) ); testArrayFormula2("ODDFPRICE", 8, 9, true); } ); test( "Test: \"ODDFYIELD\"", function () { oParser = new parserFormula( "ODDFYIELD(DATE(1990,6,1),DATE(1995,12,31),DATE(1990,1,1),DATE(1990,12,31),6%,790,100,1,1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "ODDFYIELD(DATE(1990,6,1),DATE(1995,12,31),DATE(1990,1,1),DATE(1990,12,31),6%,790,100,1,1)" ); ok( difBetween(oParser.calculate().getValue(),-0.2889178784774840 ) ); oParser = new parserFormula( "ODDFYIELD(DATE(2008,11,11),DATE(2021,3,1),DATE(2008,10,15),DATE(2009,3,1),0.0575,84.5,100,2,0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "ODDFYIELD(DATE(2008,11,11),DATE(2021,3,1),DATE(2008,10,15),DATE(2009,3,1),0.0575,84.5,100,2,0)" ); ok( difBetween(oParser.calculate().getValue(), 0.0772455415972989 ) ); oParser = new parserFormula( "ODDFYIELD(DATE(2008,12,11),DATE(2021,4,1),DATE(2008,10,15),DATE(2009,4,1),6%,100,100,4,1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "ODDFYIELD(DATE(2008,12,11),DATE(2021,4,1),DATE(2008,10,15),DATE(2009,4,1),6%,100,100,4,1)" ); ok( difBetween(oParser.calculate().getValue(), 0.0599769985558904 ) ); testArrayFormula2("ODDFYIELD", 8, 9, true); } ); /* * Engineering * */ test( "Test: \"BIN2DEC\"", function () { oParser = new parserFormula( "BIN2DEC(101010)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2DEC(101010)" ); strictEqual( oParser.calculate().getValue(), 42 ); oParser = new parserFormula( "BIN2DEC(\"101010\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2DEC(\"101010\")" ); strictEqual( oParser.calculate().getValue(), 42 ); oParser = new parserFormula( "BIN2DEC(111111111)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2DEC(111111111)" ); strictEqual( oParser.calculate().getValue(), 511 ); oParser = new parserFormula( "BIN2DEC(1000000000)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2DEC(1000000000)" ); strictEqual( oParser.calculate().getValue(), -512 ); oParser = new parserFormula( "BIN2DEC(1111111111)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2DEC(1111111111)" ); strictEqual( oParser.calculate().getValue(), -1 ); oParser = new parserFormula( "BIN2DEC(1234567890)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2DEC(1234567890)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2DEC(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2DEC(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("BIN2DEC",1,1,true); }); test( "Test: \"BIN2HEX\"", function () { oParser = new parserFormula( "BIN2HEX(101010)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010)" ); strictEqual( oParser.calculate().getValue(), "2A" ); oParser = new parserFormula( "BIN2HEX(\"101010\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(\"101010\")" ); strictEqual( oParser.calculate().getValue(), "2A" ); oParser = new parserFormula( "BIN2HEX(111111111)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(111111111)" ); strictEqual( oParser.calculate().getValue(), "1FF" ); oParser = new parserFormula( "BIN2HEX(1000000000)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(1000000000)" ); strictEqual( oParser.calculate().getValue(), "FFFFFFFE00" ); oParser = new parserFormula( "BIN2HEX(1111111111)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(1111111111)" ); strictEqual( oParser.calculate().getValue(), "FFFFFFFFFF" ); oParser = new parserFormula( "BIN2HEX(101010,2)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010,2)" ); strictEqual( oParser.calculate().getValue(), "2A" ); oParser = new parserFormula( "BIN2HEX(101010,4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010,4)" ); strictEqual( oParser.calculate().getValue(), "002A" ); oParser = new parserFormula( "BIN2HEX(101010,4.5)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010,4.5)" ); strictEqual( oParser.calculate().getValue(), "002A" ); oParser = new parserFormula( "BIN2HEX(1234567890)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(1234567890)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2HEX(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2HEX(101010101010)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010101010)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2HEX(101010,1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010,1)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2HEX(101010,-4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010,-4)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2HEX(101010, \"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010,\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("BIN2HEX", 1, 2, true) }); test( "Test: \"BIN2OCT\"", function () { oParser = new parserFormula( "BIN2OCT(101010)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010)" ); strictEqual( oParser.calculate().getValue(), "52" ); oParser = new parserFormula( "BIN2OCT(\"101010\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(\"101010\")" ); strictEqual( oParser.calculate().getValue(), "52" ); oParser = new parserFormula( "BIN2OCT(111111111)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(111111111)" ); strictEqual( oParser.calculate().getValue(), "777" ); oParser = new parserFormula( "BIN2OCT(1000000000)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(1000000000)" ); strictEqual( oParser.calculate().getValue(), "7777777000" ); oParser = new parserFormula( "BIN2OCT(1111111111)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(1111111111)" ); strictEqual( oParser.calculate().getValue(), "7777777777" ); oParser = new parserFormula( "BIN2OCT(101010, 2)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010,2)" ); strictEqual( oParser.calculate().getValue(), "52" ); oParser = new parserFormula( "BIN2OCT(101010, 4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010,4)" ); strictEqual( oParser.calculate().getValue(), "0052" ); oParser = new parserFormula( "BIN2OCT(101010, 4.5)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010,4.5)" ); strictEqual( oParser.calculate().getValue(), "0052" ); oParser = new parserFormula( "BIN2OCT(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2OCT(1234567890)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(1234567890)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2OCT(101010101010)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010101010)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2OCT(101010, 1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010,1)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2OCT(101010, -4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010,-4)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2OCT(101010, \"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010,\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("BIN2OCT", 1, 2, true); }); test( "Test: \"DEC2BIN\"", function () { oParser = new parserFormula( "DEC2BIN(42)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(42)" ); strictEqual( oParser.calculate().getValue(), "101010" ); oParser = new parserFormula( "DEC2BIN(\"42\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(\"42\")" ); strictEqual( oParser.calculate().getValue(), "101010" ); oParser = new parserFormula( "DEC2BIN(-512)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(-512)" ); strictEqual( oParser.calculate().getValue(), "1000000000" ); oParser = new parserFormula( "DEC2BIN(-511)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(-511)" ); strictEqual( oParser.calculate().getValue(), "1000000001" ); oParser = new parserFormula( "DEC2BIN(-1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(-1)" ); strictEqual( oParser.calculate().getValue(), "1111111111" ); oParser = new parserFormula( "DEC2BIN(0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(0)" ); strictEqual( oParser.calculate().getValue(), "0" ); oParser = new parserFormula( "DEC2BIN(1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(1)" ); strictEqual( oParser.calculate().getValue(), "1" ); oParser = new parserFormula( "DEC2BIN(510)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(510)" ); strictEqual( oParser.calculate().getValue(), "111111110" ); oParser = new parserFormula( "DEC2BIN(511)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(511)" ); strictEqual( oParser.calculate().getValue(), "111111111" ); oParser = new parserFormula( "DEC2BIN(42, 6)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(42,6)" ); strictEqual( oParser.calculate().getValue(), "101010" ); oParser = new parserFormula( "DEC2BIN(42, 8)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(42,8)" ); strictEqual( oParser.calculate().getValue(), "00101010" ); oParser = new parserFormula( "DEC2BIN(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "DEC2BIN(\"2a\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(\"2a\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "DEC2BIN(-513)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(-513)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "DEC2BIN(512)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(512)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "DEC2BIN(42, -8)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(42,-8)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("DEC2BIN", 1, 2, true) }); test( "Test: \"DEC2HEX\"", function () { oParser = new parserFormula( "DEC2HEX(42)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(42)" ); strictEqual( oParser.calculate().getValue(), "2A" ); oParser = new parserFormula( "DEC2HEX(\"42\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(\"42\")" ); strictEqual( oParser.calculate().getValue(), "2A" ); oParser = new parserFormula( "DEC2HEX(-549755813888)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(-549755813888)" ); strictEqual( oParser.calculate().getValue(), "8000000000" ); oParser = new parserFormula( "DEC2HEX(-549755813887)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(-549755813887)" ); strictEqual( oParser.calculate().getValue(), "8000000001" ); oParser = new parserFormula( "DEC2HEX(-1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(-1)" ); strictEqual( oParser.calculate().getValue(), "FFFFFFFFFF" ); oParser = new parserFormula( "DEC2HEX(0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(0)" ); strictEqual( oParser.calculate().getValue(), "0" ); oParser = new parserFormula( "DEC2HEX(1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(1)" ); strictEqual( oParser.calculate().getValue(), "1" ); oParser = new parserFormula( "DEC2HEX(549755813886)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(549755813886)" ); strictEqual( oParser.calculate().getValue(), "7FFFFFFFFE" ); oParser = new parserFormula( "DEC2HEX(549755813887)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(549755813887)" ); strictEqual( oParser.calculate().getValue(), "7FFFFFFFFF" ); oParser = new parserFormula( "DEC2HEX(42, 2)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(42,2)" ); strictEqual( oParser.calculate().getValue(), "2A" ); oParser = new parserFormula( "DEC2HEX(42, 4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(42,4)" ); strictEqual( oParser.calculate().getValue(), "002A" ); oParser = new parserFormula( "DEC2HEX(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "DEC2HEX(\"2a\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(\"2a\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("DEC2HEX", 1, 2, true); }); test( "Test: \"DEC2OCT\"", function () { oParser = new parserFormula( "DEC2OCT(42)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(42)" ); strictEqual( oParser.calculate().getValue(), "52" ); oParser = new parserFormula( "DEC2OCT(\"42\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(\"42\")" ); strictEqual( oParser.calculate().getValue(), "52" ); oParser = new parserFormula( "DEC2OCT(-536870912)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(-536870912)" ); strictEqual( oParser.calculate().getValue(), "4000000000" ); oParser = new parserFormula( "DEC2OCT(-536870911)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(-536870911)" ); strictEqual( oParser.calculate().getValue(), "4000000001" ); oParser = new parserFormula( "DEC2OCT(-1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(-1)" ); strictEqual( oParser.calculate().getValue(), "7777777777" ); oParser = new parserFormula( "DEC2OCT(0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(0)" ); strictEqual( oParser.calculate().getValue(), "0" ); oParser = new parserFormula( "DEC2OCT(-0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(-0)" ); strictEqual( oParser.calculate().getValue(), "0" ); oParser = new parserFormula( "DEC2OCT(1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(1)" ); strictEqual( oParser.calculate().getValue(), "1" ); oParser = new parserFormula( "DEC2OCT(536870910)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(536870910)" ); strictEqual( oParser.calculate().getValue(), "3777777776" ); oParser = new parserFormula( "DEC2OCT(536870911)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(536870911)" ); strictEqual( oParser.calculate().getValue(), "3777777777" ); oParser = new parserFormula( "DEC2OCT(42, 2)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(42,2)" ); strictEqual( oParser.calculate().getValue(), "52" ); oParser = new parserFormula( "DEC2OCT(42, 4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(42,4)" ); strictEqual( oParser.calculate().getValue(), "0052" ); oParser = new parserFormula( "DEC2OCT(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "DEC2OCT(\"2a\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(\"2a\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "DEC2OCT(-536870913)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(-536870913)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "DEC2OCT(536870912)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(536870912)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "DEC2OCT(42, 1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(42,1)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("DEC2OCT", 1, 2, true); }); test( "Test: \"HEX2BIN\"", function () { oParser = new parserFormula( "HEX2BIN(\"2a\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"2a\")" ); strictEqual( oParser.calculate().getValue(), "101010" ); oParser = new parserFormula( "HEX2BIN(\"fffffffe00\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"fffffffe00\")" ); strictEqual( oParser.calculate().getValue(), "1000000000" ); oParser = new parserFormula( "HEX2BIN(\"fffffffe01\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"fffffffe01\")" ); strictEqual( oParser.calculate().getValue(), "1000000001" ); oParser = new parserFormula( "HEX2BIN(\"ffffffffff\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"ffffffffff\")" ); strictEqual( oParser.calculate().getValue(), "1111111111" ); oParser = new parserFormula( "HEX2BIN(0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(0)" ); strictEqual( oParser.calculate().getValue(), "0" ); oParser = new parserFormula( "HEX2BIN(1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(1)" ); strictEqual( oParser.calculate().getValue(), "1" ); oParser = new parserFormula( "HEX2BIN(\"1fe\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"1fe\")" ); strictEqual( oParser.calculate().getValue(), "111111110" ); oParser = new parserFormula( "HEX2BIN(\"1ff\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"1ff\")" ); strictEqual( oParser.calculate().getValue(), "111111111" ); oParser = new parserFormula( "HEX2BIN(\"2a\",6)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"2a\",6)" ); strictEqual( oParser.calculate().getValue(), "101010" ); oParser = new parserFormula( "HEX2BIN(\"2a\",8)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"2a\",8)" ); strictEqual( oParser.calculate().getValue(), "00101010" ); oParser = new parserFormula( "HEX2BIN(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "HEX2BIN(\"fffffffdff\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"fffffffdff\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "HEX2BIN(\"200\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"200\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "HEX2BIN(\"2a\", 5)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"2a\",5)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "HEX2BIN(\"2a\", -8)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"2a\",-8)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "HEX2BIN(\"2a\", \"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"2a\",\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("HEX2BIN", 1, 2, true); }); test( "Test: \"HEX2DEC\"", function () { oParser = new parserFormula( "HEX2DEC(\"2a\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(\"2a\")" ); strictEqual( oParser.calculate().getValue(), 42); oParser = new parserFormula( "HEX2DEC(\"8000000000\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(\"8000000000\")" ); strictEqual( oParser.calculate().getValue(), -549755813888); oParser = new parserFormula( "HEX2DEC(\"ffffffffff\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(\"ffffffffff\")" ); strictEqual( oParser.calculate().getValue(), -1); oParser = new parserFormula( "HEX2DEC(\"0\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(\"0\")" ); strictEqual( oParser.calculate().getValue(), 0); oParser = new parserFormula( "HEX2DEC(\"1\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(\"1\")" ); strictEqual( oParser.calculate().getValue(), 1); oParser = new parserFormula( "HEX2DEC(0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(0)" ); strictEqual( oParser.calculate().getValue(), 0); oParser = new parserFormula( "HEX2DEC(1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(1)" ); strictEqual( oParser.calculate().getValue(), 1); oParser = new parserFormula( "HEX2DEC(\"7fffffffff\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(\"7fffffffff\")" ); strictEqual( oParser.calculate().getValue(), 549755813887); testArrayFormula2("HEX2DEC", 1, 1, true); }); test( "Test: \"HEX2OCT\"", function () { oParser = new parserFormula( "HEX2OCT(\"2a\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"2a\")" ); strictEqual( oParser.calculate().getValue(), "52"); oParser = new parserFormula( "HEX2OCT(\"ffe0000000\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"ffe0000000\")" ); strictEqual( oParser.calculate().getValue(), "4000000000"); oParser = new parserFormula( "HEX2OCT(\"ffe0000001\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"ffe0000001\")" ); strictEqual( oParser.calculate().getValue(), "4000000001"); oParser = new parserFormula( "HEX2OCT(0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(0)" ); strictEqual( oParser.calculate().getValue(), "0"); oParser = new parserFormula( "HEX2OCT(1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(1)" ); strictEqual( oParser.calculate().getValue(), "1"); oParser = new parserFormula( "HEX2OCT(\"1ffffffe\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"1ffffffe\")" ); strictEqual( oParser.calculate().getValue(), "3777777776"); oParser = new parserFormula( "HEX2OCT(\"1fffffff\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"1fffffff\")" ); strictEqual( oParser.calculate().getValue(), "3777777777"); oParser = new parserFormula( "HEX2OCT(\"2a\",2)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"2a\",2)" ); strictEqual( oParser.calculate().getValue(), "52"); oParser = new parserFormula( "HEX2OCT(\"2a\",4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"2a\",4)" ); strictEqual( oParser.calculate().getValue(), "0052"); oParser = new parserFormula( "HEX2OCT(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "HEX2OCT(\"ffdfffffff\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"ffdfffffff\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "HEX2OCT(\"2a\", 1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"2a\",1)" ); strictEqual( oParser.calculate().getValue(), "#NUM!"); testArrayFormula2("HEX2OCT", 1, 2, true); }); test( "Test: \"OCT2BIN\"", function () { oParser = new parserFormula( "OCT2BIN(\"52\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"52\")" ); strictEqual( oParser.calculate().getValue(), "101010"); oParser = new parserFormula( "OCT2BIN(\"7777777000\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"7777777000\")" ); strictEqual( oParser.calculate().getValue(), "1000000000"); oParser = new parserFormula( "OCT2BIN(\"7777777001\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"7777777001\")" ); strictEqual( oParser.calculate().getValue(), "1000000001"); oParser = new parserFormula( "OCT2BIN(\"7777777777\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"7777777777\")" ); strictEqual( oParser.calculate().getValue(), "1111111111"); oParser = new parserFormula( "OCT2BIN(\"0\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"0\")" ); strictEqual( oParser.calculate().getValue(), "0"); oParser = new parserFormula( "OCT2BIN(\"1\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"1\")" ); strictEqual( oParser.calculate().getValue(), "1"); oParser = new parserFormula( "OCT2BIN(\"776\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"776\")" ); strictEqual( oParser.calculate().getValue(), "111111110"); oParser = new parserFormula( "OCT2BIN(\"777\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"777\")" ); strictEqual( oParser.calculate().getValue(), "111111111"); oParser = new parserFormula( "OCT2BIN(\"52\", 6)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"52\",6)" ); strictEqual( oParser.calculate().getValue(), "101010"); oParser = new parserFormula( "OCT2BIN(\"52\", 8)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"52\",8)" ); strictEqual( oParser.calculate().getValue(), "00101010"); oParser = new parserFormula( "OCT2BIN(\"Hello World!\", 8)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"Hello World!\",8)" ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "OCT2BIN(\"52\",\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"52\",\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!"); testArrayFormula2("OCT2BIN", 1, 2, true) }); test( "Test: \"OCT2DEC\"", function () { oParser = new parserFormula( "OCT2DEC(\"52\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"52\")" ); strictEqual( oParser.calculate().getValue(), 42); oParser = new parserFormula( "OCT2DEC(\"4000000000\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"4000000000\")" ); strictEqual( oParser.calculate().getValue(), -536870912); oParser = new parserFormula( "OCT2DEC(\"7777777777\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"7777777777\")" ); strictEqual( oParser.calculate().getValue(), -1); oParser = new parserFormula( "OCT2DEC(\"0\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"0\")" ); strictEqual( oParser.calculate().getValue(), 0); oParser = new parserFormula( "OCT2DEC(\"1\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"1\")" ); strictEqual( oParser.calculate().getValue(), 1); oParser = new parserFormula( "OCT2DEC(\"3777777776\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"3777777776\")" ); strictEqual( oParser.calculate().getValue(), 536870910); oParser = new parserFormula( "OCT2DEC(\"3777777777\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"3777777777\")" ); strictEqual( oParser.calculate().getValue(), 536870911); oParser = new parserFormula( "OCT2DEC(\"3777777777\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"3777777777\")" ); strictEqual( oParser.calculate().getValue(), 536870911); testArrayFormula2("OCT2DEC",1,1,true); }); test( "Test: \"OCT2HEX\"", function () { oParser = new parserFormula( "OCT2HEX(\"52\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"52\")" ); strictEqual( oParser.calculate().getValue(), "2A"); oParser = new parserFormula( "OCT2HEX(\"4000000000\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"4000000000\")" ); strictEqual( oParser.calculate().getValue(), "FFE0000000"); oParser = new parserFormula( "OCT2HEX(\"4000000001\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"4000000001\")" ); strictEqual( oParser.calculate().getValue(), "FFE0000001"); oParser = new parserFormula( "OCT2HEX(\"7777777777\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"7777777777\")" ); strictEqual( oParser.calculate().getValue(), "FFFFFFFFFF"); oParser = new parserFormula( "OCT2HEX(\"0\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"0\")" ); strictEqual( oParser.calculate().getValue(), "0"); oParser = new parserFormula( "OCT2HEX(\"1\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"1\")" ); strictEqual( oParser.calculate().getValue(), "1"); oParser = new parserFormula( "OCT2HEX(\"3777777776\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"3777777776\")" ); strictEqual( oParser.calculate().getValue(), "1FFFFFFE"); oParser = new parserFormula( "OCT2HEX(\"3777777777\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"3777777777\")" ); strictEqual( oParser.calculate().getValue(), "1FFFFFFF"); oParser = new parserFormula( "OCT2HEX(\"52\", 2)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"52\",2)" ); strictEqual( oParser.calculate().getValue(), "2A"); oParser = new parserFormula( "OCT2HEX(\"52\", 4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"52\",4)" ); strictEqual( oParser.calculate().getValue(), "002A"); oParser = new parserFormula( "OCT2HEX(\"Hello World!\", 4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"Hello World!\",4)" ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "OCT2HEX(\"52\", -4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"52\",-4)" ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "OCT2HEX(\"52\", \"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"52\",\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!"); testArrayFormula2("OCT2HEX", 1, 2, true) }); test( "Test: \"COMPLEX\"", function () { oParser = new parserFormula( "COMPLEX(-3.5,19.6)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "COMPLEX(-3.5,19.6)" ); strictEqual( oParser.calculate().getValue(), "-3.5+19.6i"); oParser = new parserFormula( "COMPLEX(3.5,-19.6,\"j\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "COMPLEX(3.5,-19.6,\"j\")" ); strictEqual( oParser.calculate().getValue(), "3.5-19.6j"); oParser = new parserFormula( "COMPLEX(3.5,0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "COMPLEX(3.5,0)" ); strictEqual( oParser.calculate().getValue(), "3.5"); oParser = new parserFormula( "COMPLEX(0,2.4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "COMPLEX(0,2.4)" ); strictEqual( oParser.calculate().getValue(), "2.4i"); oParser = new parserFormula( "COMPLEX(0,0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "COMPLEX(0,0)" ); strictEqual( oParser.calculate().getValue(), "0"); testArrayFormula2("COMPLEX", 2, 3, true); }); test( "Test: \"DELTA\"", function () { oParser = new parserFormula( "DELTA(10.5,10.5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1); oParser = new parserFormula( "DELTA(10.5,10.6)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0); oParser = new parserFormula( "DELTA(10.5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0); oParser = new parserFormula( "DELTA(0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1); testArrayFormula2("DELTA", 1, 2, true); }); test( "Test: \"ERF\"", function () { oParser = new parserFormula( "ERF(1.234,4.5432)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.08096058291050978.toFixed(14)-0 ); oParser = new parserFormula( "ERF(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.8427007929497149.toFixed(14)-0 ); oParser = new parserFormula( "ERF(0,1.345)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.9428441710878559.toFixed(14)-0 ); oParser = new parserFormula( "ERF(1.234)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.9190394169576684.toFixed(14)-0 ); testArrayFormula2("ERF", 1, 2, true); }); test( "Test: \"GESTEP\"", function () { oParser = new parserFormula( "GESTEP(5, 4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1); oParser = new parserFormula( "GESTEP(5, 5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1); oParser = new parserFormula( "GESTEP(-4, -5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1); oParser = new parserFormula( "GESTEP(-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0); testArrayFormula2("GESTEP", 1, 2, true); }); test( "Test: \"ERF.PRECISE\"", function () { oParser = new parserFormula( "ERF.PRECISE(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.8427007929497149.toFixed(14)-0 ); oParser = new parserFormula( "ERF.PRECISE(1.234)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.9190394169576684.toFixed(14)-0 ); oParser = new parserFormula( "ERF.PRECISE(0.745)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.70792892 ); oParser = new parserFormula( "ERF.PRECISE(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.84270079 ); testArrayFormula2("ERF.PRECISE",1,1,true); }); test( "Test: \"ERFC\"", function () { oParser = new parserFormula( "ERFC(1.234)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.08096058304233157.toFixed(14)-0 ); oParser = new parserFormula( "ERFC(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.15729920705028513.toFixed(14)-0 ); oParser = new parserFormula( "ERFC(0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "ERFC(-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 1.8427007929497148.toFixed(14)-0 ); testArrayFormula2("ERFC",1,1,true); }); test( "Test: \"ERFC.PRECISE\"", function () { oParser = new parserFormula( "ERFC.PRECISE(1.234)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.08096058304233157.toFixed(14)-0 ); oParser = new parserFormula( "ERFC.PRECISE(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.15729920705028513.toFixed(14)-0 ); oParser = new parserFormula( "ERFC.PRECISE(0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "ERFC.PRECISE(-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 1.8427007929497148.toFixed(14)-0 ); }); test( "Test: \"BITAND\"", function () { oParser = new parserFormula( 'BITAND(1,5)', "AA2", ws ); ok( oParser.parse(), 'BITAND(1,5)' ); strictEqual( oParser.calculate().getValue(), 1, 'BITAND(1,5)' ); oParser = new parserFormula( 'BITAND(13,25)', "AA2", ws ); ok( oParser.parse(), 'BITAND(13,25)' ); strictEqual( oParser.calculate().getValue(), 9, 'BITAND(13,25)' ); testArrayFormula2("BITAND", 2, 2); }); test( "Test: \"BITOR\"", function () { oParser = new parserFormula( 'BITOR(23,10)', "AA2", ws ); ok( oParser.parse()); strictEqual( oParser.calculate().getValue(), 31 ); testArrayFormula2("BITOR", 2, 2); }); test( "Test: \"BITXOR\"", function () { oParser = new parserFormula( 'BITXOR(5,3)', "AA2", ws ); ok( oParser.parse()); strictEqual( oParser.calculate().getValue(), 6 ); testArrayFormula2("BITXOR", 2, 2); }); test( "Test: \"BITRSHIFT\"", function () { oParser = new parserFormula( 'BITRSHIFT(13,2)', "AA2", ws ); ok( oParser.parse()); strictEqual( oParser.calculate().getValue(), 3 ); testArrayFormula2("BITRSHIFT", 2, 2); }); test( "Test: \"BITLSHIFT\"", function () { oParser = new parserFormula( 'BITLSHIFT(4,2)', "AA2", ws ); ok( oParser.parse()); strictEqual( oParser.calculate().getValue(), 16 ); testArrayFormula2("BITLSHIFT", 2, 2); }); function putDataForDatabase(){ ws.getRange2( "A1" ).setValue( "Tree" ); ws.getRange2( "A2" ).setValue( "Apple" ); ws.getRange2( "A3" ).setValue( "Pear" ); ws.getRange2( "A4" ).setValue( "Tree" ); ws.getRange2( "A5" ).setValue( "Apple" ); ws.getRange2( "A6" ).setValue( "Pear" ); ws.getRange2( "A7" ).setValue( "Cherry" ); ws.getRange2( "A8" ).setValue( "Apple" ); ws.getRange2( "A9" ).setValue( "Pear" ); ws.getRange2( "A10" ).setValue( "Apple" ); ws.getRange2( "B1" ).setValue( "Height" ); ws.getRange2( "B2" ).setValue( ">10" ); ws.getRange2( "B3" ).setValue( "" ); ws.getRange2( "B4" ).setValue( "Height" ); ws.getRange2( "B5" ).setValue( "18" ); ws.getRange2( "B6" ).setValue( "12" ); ws.getRange2( "B7" ).setValue( "13" ); ws.getRange2( "B8" ).setValue( "14" ); ws.getRange2( "B9" ).setValue( "9" ); ws.getRange2( "B10" ).setValue( "8" ); ws.getRange2( "C1" ).setValue( "Age" ); ws.getRange2( "C2" ).setValue( "" ); ws.getRange2( "C3" ).setValue( "" ); ws.getRange2( "C4" ).setValue( "Age" ); ws.getRange2( "C5" ).setValue( "20" ); ws.getRange2( "C6" ).setValue( "12" ); ws.getRange2( "C7" ).setValue( "14" ); ws.getRange2( "C8" ).setValue( "15" ); ws.getRange2( "C9" ).setValue( "8" ); ws.getRange2( "C10" ).setValue( "9" ); ws.getRange2( "C1" ).setValue( "Age" ); ws.getRange2( "C2" ).setValue( "" ); ws.getRange2( "C3" ).setValue( "" ); ws.getRange2( "C4" ).setValue( "Age" ); ws.getRange2( "C5" ).setValue( "20" ); ws.getRange2( "C6" ).setValue( "12" ); ws.getRange2( "C7" ).setValue( "14" ); ws.getRange2( "C8" ).setValue( "15" ); ws.getRange2( "C9" ).setValue( "8" ); ws.getRange2( "C10" ).setValue( "9" ); ws.getRange2( "D1" ).setValue( "Yield" ); ws.getRange2( "D2" ).setValue( "" ); ws.getRange2( "D3" ).setValue( "" ); ws.getRange2( "D4" ).setValue( "Yield" ); ws.getRange2( "D5" ).setValue( "14" ); ws.getRange2( "D6" ).setValue( "10" ); ws.getRange2( "D7" ).setValue( "9" ); ws.getRange2( "D8" ).setValue( "10" ); ws.getRange2( "D9" ).setValue( "8" ); ws.getRange2( "D10" ).setValue( "6" ); ws.getRange2( "E1" ).setValue( "Profit" ); ws.getRange2( "E2" ).setValue( "" ); ws.getRange2( "E3" ).setValue( "" ); ws.getRange2( "E4" ).setValue( "Profit" ); ws.getRange2( "E5" ).setValue( "105" ); ws.getRange2( "E6" ).setValue( "96" ); ws.getRange2( "E7" ).setValue( "105" ); ws.getRange2( "E8" ).setValue( "75" ); ws.getRange2( "E9" ).setValue( "76.8" ); ws.getRange2( "E10" ).setValue( "45" ); ws.getRange2( "F1" ).setValue( "Height" ); ws.getRange2( "F2" ).setValue( "<16" ); ws.getRange2( "F3" ).setValue( "" ); } //database formulas test( "Test: \"DAVERAGE\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DAVERAGE(A4:E10, "Yield", A1:B2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 12 ); oParser = new parserFormula( 'DAVERAGE(A4:E10, 3, A4:E10)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 13 ); }); test( "Test: \"DCOUNT\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DCOUNT(A4:E10, "Age", A1:F2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( 'DCOUNT(A4:E10,, A1:F2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( 'DCOUNT(A4:E10,"", A1:F2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); }); test( "Test: \"DCOUNTA\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DCOUNTA(A4:E10, "Profit", A1:F2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( 'DCOUNTA(A4:E10,, A1:F2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( 'DCOUNTA(A4:E10,"", A1:F2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); }); test( "Test: \"DGET\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DGET(A4:E10, "Yield", A1:A3)', "AA2", ws ); ok( oParser.parse(), 'DGET(A4:E10, "Yield", A1:A3)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'DGET(A4:E10, "Yield", A1:A3)' ); oParser = new parserFormula( 'DGET(A4:E10, "Yield", A1:F2)', "AA2", ws ); ok( oParser.parse(), 'DGET(A4:E10, "Yield", A1:F2)' ); strictEqual( oParser.calculate().getValue(), 10, 'DGET(A4:E10, "Yield", A1:F2)' ); }); test( "Test: \"DMAX\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DMAX(A4:E10, "Profit", A1:F3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 96 ); }); test( "Test: \"DMIN\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DMIN(A4:E10, "Profit", A1:F3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 75 ); }); test( "Test: \"DPRODUCT\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DPRODUCT(A4:E10, "Yield", A1:F3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 800 ); }); test( "Test: \"DSTDEV\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DSTDEV(A4:E10, "Yield", A1:F3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(4) - 0, 1.1547); }); test( "Test: \"DSTDEVP\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DSTDEVP(A4:E10, "Yield", A1:F3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.942809); }); test( "Test: \"STDEVPA\"", function () { ws.getRange2( "A103" ).setValue( "1345" ); ws.getRange2( "A104" ).setValue( "1301" ); ws.getRange2( "A105" ).setValue( "1368" ); ws.getRange2( "A106" ).setValue( "1322" ); ws.getRange2( "A107" ).setValue( "1310" ); ws.getRange2( "A108" ).setValue( "1370" ); ws.getRange2( "A109" ).setValue( "1318" ); ws.getRange2( "A110" ).setValue( "1350" ); ws.getRange2( "A111" ).setValue( "1303" ); ws.getRange2( "A112" ).setValue( "1299" ); oParser = new parserFormula( 'STDEVPA(A103:A112)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 26.05456); testArrayFormula2("STDEVPA", 1, 8, null, true); }); test( "Test: \"STDEVP\"", function () { ws.getRange2( "A103" ).setValue( "1345" ); ws.getRange2( "A104" ).setValue( "1301" ); ws.getRange2( "A105" ).setValue( "1368" ); ws.getRange2( "A106" ).setValue( "1322" ); ws.getRange2( "A107" ).setValue( "1310" ); ws.getRange2( "A108" ).setValue( "1370" ); ws.getRange2( "A109" ).setValue( "1318" ); ws.getRange2( "A110" ).setValue( "1350" ); ws.getRange2( "A111" ).setValue( "1303" ); ws.getRange2( "A112" ).setValue( "1299" ); oParser = new parserFormula( 'STDEVP(A103:A112)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 26.05456); testArrayFormula2("STDEVP", 1, 8, null, true); }); test( "Test: \"STDEV\"", function () { ws.getRange2( "A103" ).setValue( "1345" ); ws.getRange2( "A104" ).setValue( "1301" ); ws.getRange2( "A105" ).setValue( "1368" ); ws.getRange2( "A106" ).setValue( "1322" ); ws.getRange2( "A107" ).setValue( "1310" ); ws.getRange2( "A108" ).setValue( "1370" ); ws.getRange2( "A109" ).setValue( "1318" ); ws.getRange2( "A110" ).setValue( "1350" ); ws.getRange2( "A111" ).setValue( "1303" ); ws.getRange2( "A112" ).setValue( "1299" ); oParser = new parserFormula( 'STDEV(A103:A112)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 27.46392); testArrayFormula2("STDEV", 1, 8, null, true); }); test( "Test: \"DSUM\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DSUM(A4:E10,"Profit",A1:A2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 225); oParser = new parserFormula( 'DSUM(A4:E10,"Profit", A1:F3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 247.8); }); test( "Test: \"DVAR\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DVAR(A4:E10, "Yield", A1:A3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(1) - 0, 8.8); }); test( "Test: \"DVARP\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DVARP(A4:E10, "Yield", A1:A3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 7.04); }); test( "Test: \"UNICODE\"", function () { oParser = new parserFormula( 'UNICODE(" ")', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 32); oParser = new parserFormula( 'UNICODE("B")', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 66); oParser = new parserFormula( 'UNICODE(0)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 48); oParser = new parserFormula( 'UNICODE(1)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 49); oParser = new parserFormula( 'UNICODE("true")', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 116); oParser = new parserFormula( 'UNICODE(#N/A)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A"); }); test( "Test: \"UNICHAR\"", function () { oParser = new parserFormula( 'UNICHAR(66)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "B"); oParser = new parserFormula( 'UNICHAR(32)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), " "); oParser = new parserFormula( 'UNICHAR(0)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!"); oParser = new parserFormula( 'UNICHAR(48)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "0"); oParser = new parserFormula( 'UNICHAR(49)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "1"); }); test( "Test: \"UPPER\"", function () { ws.getRange2( "A2" ).setValue( "total" ); ws.getRange2( "A3" ).setValue( "Yield" ); oParser = new parserFormula( 'UPPER(A2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TOTAL"); oParser = new parserFormula( 'UPPER(A3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "YIELD"); testArrayFormula2("UPPER", 1, 1); }); test( "Test: \"UNIQUE \"", function () { ws.getRange2( "A101" ).setValue( "1" ); ws.getRange2( "A102" ).setValue( "2" ); ws.getRange2( "A103" ).setValue( "2" ); ws.getRange2( "A104" ).setValue( "-1" ); ws.getRange2( "A105" ).setValue( "-1" ); ws.getRange2( "A106" ).setValue( "ds" ); ws.getRange2( "A107" ).setValue( "ds" ); ws.getRange2( "A108" ).setValue( "#NUM!" ); ws.getRange2( "A109" ).setValue( "#NUM!" ); ws.getRange2( "B101" ).setValue( "1" ); ws.getRange2( "B102" ).setValue( "2" ); ws.getRange2( "B103" ).setValue( "2" ); ws.getRange2( "B104" ).setValue( "4" ); ws.getRange2( "B105" ).setValue( "5" ); ws.getRange2( "B106" ).setValue( "7" ); ws.getRange2( "B107" ).setValue( "7" ); ws.getRange2( "B108" ).setValue( "8" ); ws.getRange2( "B109" ).setValue( "8" ); ws.getRange2( "C101" ).setValue( "2" ); ws.getRange2( "C102" ).setValue( "2" ); ws.getRange2( "C103" ).setValue( "2" ); ws.getRange2( "C104" ).setValue( "1" ); ws.getRange2( "C105" ).setValue( "1" ); ws.getRange2( "C106" ).setValue( "2" ); ws.getRange2( "C107" ).setValue( "3" ); ws.getRange2( "C108" ).setValue( "8" ); ws.getRange2( "C109" ).setValue( "8" ); ws.getRange2( "D101" ).setValue( "2" ); ws.getRange2( "D102" ).setValue( "2" ); ws.getRange2( "D103" ).setValue( "2" ); ws.getRange2( "D104" ).setValue( "1" ); ws.getRange2( "D105" ).setValue( "1" ); ws.getRange2( "D106" ).setValue( "2" ); ws.getRange2( "D107" ).setValue( "3" ); ws.getRange2( "D108" ).setValue( "8" ); ws.getRange2( "D109" ).setValue( "8" ); oParser = new parserFormula( "UNIQUE(A101:A109)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 2 ); strictEqual( oParser.calculate().getElementRowCol(2,0).getValue(), -1 ); strictEqual( oParser.calculate().getElementRowCol(3,0).getValue(), "ds" ); strictEqual( oParser.calculate().getElementRowCol(4,0).getValue(), "#NUM!" ); oParser = new parserFormula( "UNIQUE(A101:A109)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 2 ); strictEqual( oParser.calculate().getElementRowCol(2,0).getValue(), -1 ); strictEqual( oParser.calculate().getElementRowCol(3,0).getValue(), "ds" ); strictEqual( oParser.calculate().getElementRowCol(4,0).getValue(), "#NUM!" ); oParser = new parserFormula( "UNIQUE(A101:D101)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(0,2).getValue(), 2 ); strictEqual( oParser.calculate().getElementRowCol(0,3).getValue(), 2 ); oParser = new parserFormula( "UNIQUE(A101:D101, true)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue(), 2 ); oParser = new parserFormula( "UNIQUE(A101:D101, true, true)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); ws.getRange2( "F102" ).setValue( "test" ); ws.getRange2( "F103" ).setValue( "#VALUE!" ); ws.getRange2( "F104" ).setValue( "test" ); ws.getRange2( "F105" ).setValue( "#VALUE!" ); ws.getRange2( "F106" ).setValue( "2" ); ws.getRange2( "F107" ).setValue( "-3" ); ws.getRange2( "G102" ).setValue( "2" ); ws.getRange2( "G103" ).setValue( "yyy" ); ws.getRange2( "G104" ).setValue( "4" ); ws.getRange2( "G105" ).setValue( "yyy" ); ws.getRange2( "G106" ).setValue( "asd" ); ws.getRange2( "G107" ).setValue( "7" ); ws.getRange2( "H102" ).setValue( "test" ); ws.getRange2( "H103" ).setValue( "#VALUE!" ); ws.getRange2( "H104" ).setValue( "test" ); ws.getRange2( "H105" ).setValue( "#VALUE!" ); ws.getRange2( "H106" ).setValue( "2" ); ws.getRange2( "H107" ).setValue( "-3" ); ws.getRange2( "I102" ).setValue( "2" ); ws.getRange2( "I103" ).setValue( "123" ); ws.getRange2( "I104" ).setValue( "4" ); ws.getRange2( "I105" ).setValue( "123" ); ws.getRange2( "I106" ).setValue( "6" ); ws.getRange2( "I107" ).setValue( "4" ); oParser = new parserFormula( "UNIQUE(F102:I107)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,2).getValue(), "test" ); strictEqual( oParser.calculate().getElementRowCol(1,2).getValue(), "#VALUE!" ); strictEqual( oParser.calculate().getElementRowCol(2,2).getValue(), "test" ); strictEqual( oParser.calculate().getElementRowCol(3,2).getValue(), 2 ); strictEqual( oParser.calculate().getElementRowCol(4,2).getValue(), -3 ); oParser = new parserFormula( "UNIQUE(F102:I107, true)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,2).getValue(), 2 ); strictEqual( oParser.calculate().getElementRowCol(1,2).getValue(), 123 ); strictEqual( oParser.calculate().getElementRowCol(2,2).getValue(), 4 ); strictEqual( oParser.calculate().getElementRowCol(3,2).getValue(), 123 ); strictEqual( oParser.calculate().getElementRowCol(4,2).getValue(), 6 ); strictEqual( oParser.calculate().getElementRowCol(5,2).getValue(), 4 ); oParser = new parserFormula( "UNIQUE(F102:I107, false, true)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), "test" ); strictEqual( oParser.calculate().getElementRowCol(1,1).getValue(), 4 ); strictEqual( oParser.calculate().getElementRowCol(2,2).getValue(), 2 ); strictEqual( oParser.calculate().getElementRowCol(3,3).getValue(), 4 ); oParser = new parserFormula( "UNIQUE(F102:I107, true, true)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue(), 2 ); strictEqual( oParser.calculate().getElementRowCol(1,1).getValue(), 123 ); strictEqual( oParser.calculate().getElementRowCol(2,1).getValue(), 4 ); strictEqual( oParser.calculate().getElementRowCol(3,1).getValue(), 123 ); strictEqual( oParser.calculate().getElementRowCol(4,1).getValue(), 6 ); strictEqual( oParser.calculate().getElementRowCol(5,1).getValue(), 4 ); } ); test( "Test: \"GROWTH\"", function () { ws.getRange2( "A102" ).setValue( "11" ); ws.getRange2( "A103" ).setValue( "12" ); ws.getRange2( "A104" ).setValue( "13" ); ws.getRange2( "A105" ).setValue( "14" ); ws.getRange2( "A106" ).setValue( "15" ); ws.getRange2( "A107" ).setValue( "16" ); ws.getRange2( "B102" ).setValue( "33100" ); ws.getRange2( "B103" ).setValue( "47300" ); ws.getRange2( "B104" ).setValue( "69000" ); ws.getRange2( "B105" ).setValue( "102000" ); ws.getRange2( "B106" ).setValue( "150000" ); ws.getRange2( "B107" ).setValue( "220000" ); ws.getRange2( "C102" ).setValue( "32618" ); ws.getRange2( "C103" ).setValue( "47729" ); ws.getRange2( "C104" ).setValue( "69841" ); ws.getRange2( "C105" ).setValue( "102197" ); ws.getRange2( "C106" ).setValue( "149542" ); ws.getRange2( "C107" ).setValue( "218822" ); ws.getRange2( "A109" ).setValue( "17" ); ws.getRange2( "A110" ).setValue( "18" ); oParser = new parserFormula( "GROWTH(B102:B107,A102:A107,A109:A110)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(4) - 0, 320196.7184); oParser = new parserFormula( "GROWTH(B102:B107,A102:A107)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(5) - 0, 32618.20377); oParser = new parserFormula( "GROWTH(A102:C102,A103:C104,A105:C106,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 11.00782679); oParser = new parserFormula( "GROWTH(A102:C102,A103:C104,A105:C106,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 11.00782679); oParser = new parserFormula( "GROWTH(A103:C103,A104:C105,A106:C107,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 12.00187209); oParser = new parserFormula( "GROWTH(A103:C103,A104:C105,A106:C107,10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 12.00187209); oParser = new parserFormula( "GROWTH(A103:C103,A104:C105,A106:C107,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.0017632); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(3) - 0, 12047829814.167); strictEqual( oParser.calculate().getElementRowCol(0,2).getValue().toFixed(3) - 0, 10705900594.962); oParser = new parserFormula( "GROWTH({1,2,3},A104:C105,A106:C107,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.00038318); oParser = new parserFormula( "GROWTH({1,2,3},A104:C105,A106:C107,A106:C107)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!"); oParser = new parserFormula( "GROWTH(A103:C103,A104:C105,A106:C107,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 12.00187209); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(3) - 0, 676231620.297); strictEqual( oParser.calculate().getElementRowCol(0,2).getValue().toFixed(3) - 0, 612512904.254) } ); test( "Test: \"LOGEST\"", function () { ws.getRange2( "A101" ).setValue( "1" ); ws.getRange2( "A102" ).setValue( "2" ); ws.getRange2( "A103" ).setValue( "3" ); ws.getRange2( "A104" ).setValue( "4" ); ws.getRange2( "A105" ).setValue( "5" ); ws.getRange2( "A106" ).setValue( "6" ); ws.getRange2( "A107" ).setValue( "7" ); ws.getRange2( "A108" ).setValue( "8" ); ws.getRange2( "A109" ).setValue( "9" ); ws.getRange2( "A110" ).setValue( "10" ); ws.getRange2( "A111" ).setValue( "11" ); ws.getRange2( "A112" ).setValue( "12" ); ws.getRange2( "B101" ).setValue( "133890" ); ws.getRange2( "B102" ).setValue( "135000" ); ws.getRange2( "B103" ).setValue( "135790" ); ws.getRange2( "B104" ).setValue( "137300" ); ws.getRange2( "B105" ).setValue( "138130" ); ws.getRange2( "B106" ).setValue( "139100" ); ws.getRange2( "B107" ).setValue( "139900" ); ws.getRange2( "B108" ).setValue( "141120" ); ws.getRange2( "B109" ).setValue( "141890" ); ws.getRange2( "B110" ).setValue( "143230" ); ws.getRange2( "B111" ).setValue( "144000" ); ws.getRange2( "B112" ).setValue( "145290" ); ws.getRange2( "A115" ).setValue( "13" ); ws.getRange2( "A116" ).setValue( "14" ); ws.getRange2( "A117" ).setValue( "15" ); ws.getRange2( "A118" ).setValue( "16" ); ws.getRange2( "A119" ).setValue( "17" ); oParser = new parserFormula( "LOGEST(B101:B112,A101:A112)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.00732561); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 133044.8167); oParser = new parserFormula( "LOGEST(B101:B112,A101:A112,,false)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.00732561); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 133044.8167); //todo необходимо перепроверить остальные значения в данном случае oParser = new parserFormula( "LOGEST(B101:B112,A101:A112,,true)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.00732561); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 133044.8167); oParser = new parserFormula( "LOGEST(B101:B112,A101:A112,true,true)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.00732561); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 133044.8167); //todo необходимо перепроверить остальные значения в данном случае oParser = new parserFormula( "LOGEST(B101:B112,A101:A112,false,true)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 4.15001464); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 1); oParser = new parserFormula( "LOGEST(A101:B105,A106:B110,FALSE,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.0000838); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 1); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue().toFixed(8) - 0, 0.00000264); strictEqual( oParser.calculate().getElementRowCol(2,0).getValue().toFixed(4) - 0, 0.9911); strictEqual( oParser.calculate().getElementRowCol(3,0).getValue().toFixed(4) - 0, 1005.3131); strictEqual( oParser.calculate().getElementRowCol(4,0).getValue().toFixed(4) - 0, 698.5684); oParser = new parserFormula( "LOGEST(A101:B105,A106:B110,,)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.00007701); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 2.6063); oParser = new parserFormula( "LOGEST(A101:B105,A106:B110,false,false)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.0000838); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 1); //todo необходимо перепроверить остальные значения в данном случае oParser = new parserFormula( "LOGEST(A101:B105,A106:B110,true,true)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.00007701); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 2.6063); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue().toFixed(8) - 0, 0.00000205); strictEqual( oParser.calculate().getElementRowCol(2,0).getValue().toFixed(4) - 0, 0.9944); strictEqual( oParser.calculate().getElementRowCol(3,0).getValue().toFixed(4) - 0, 1416.4887); strictEqual( oParser.calculate().getElementRowCol(4,0).getValue().toFixed(4) - 0, 294.9627); } ); test( "Test: \"PDURATION\"", function () { oParser = new parserFormula( "PDURATION(2.5%,2000,2200)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 3.86); oParser = new parserFormula( "PDURATION(0.025/12,1000,1200)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(1) - 0, 87.6); oParser = new parserFormula( "PDURATION(0.025,1000,1200)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 7.38); oParser = new parserFormula( "PDURATION(-0.025,1000,1200)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "PDURATION(0.025,-1000,1200)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "PDURATION(0.025,1000,-1200)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "PDURATION({0.025},{1000},{1200})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 7.38); oParser = new parserFormula( "PDURATION(\"TEST\",1000,-1200)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!"); testArrayFormula2("PDURATION", 3, 3); }); test( "Test: \"IFS\"", function () { oParser = new parserFormula( 'IFS(1,"TEST")', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TEST"); oParser = new parserFormula( 'IFS(0,"TEST",1,"TEST2")', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TEST2"); oParser = new parserFormula( 'IFS(2<1,">3")', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A"); oParser = new parserFormula( 'IFS(2<1,">3",2>1)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A"); oParser = new parserFormula( 'IFS(2<1,"TEST",2<1,2,4>3,"TEST2")', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TEST2"); testArrayFormulaEqualsValues("1,3.123,-4,#N/A;2,4,5,#N/A;#N/A,#N/A,#N/A,#N/A","IFS(A1:C2,A1:C2,A1:C2,A1:C2, A1:C2,A1:C2)"); }); test( "Test: \"IF\"", function () { oParser = new parserFormula('IF(1,"TEST")', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "TEST"); oParser = new parserFormula('IF(0,"TEST")', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "FALSE"); ws.getRange2( "A101" ).setValue( "1" ); oParser = new parserFormula('IF(A101=1,"Yes","No")', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "Yes"); oParser = new parserFormula('IF(A101=2,"Yes","No")', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "No"); //TODO нужна другая функция для тестирования //testArrayFormula2("IF", 2, 3); }); test( "Test: \"COLUMN\"", function () { oParser = new parserFormula('COLUMN(B6)', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); oParser = new parserFormula('COLUMN(C16)', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 3); oParser = new parserFormula('COLUMN()', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 1); oParser = new parserFormula('COLUMN()+COLUMN()', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); testArrayFormulaEqualsValues("5,6,7,8;5,6,7,8;5,6,7,8", "COLUMN()"); testArrayFormulaEqualsValues("1,2,3,#N/A;1,2,3,#N/A;1,2,3,#N/A", "COLUMN(A1:C2)"); testArrayFormulaEqualsValues("1,2,#N/A,#N/A;1,2,#N/A,#N/A;1,2,#N/A,#N/A", "COLUMN(A1:B1)"); testArrayFormulaEqualsValues("1,1,1,1;1,1,1,1;1,1,1,1", "COLUMN(A1)"); }); test( "Test: \"COLUMNS\"", function () { oParser = new parserFormula('COLUMNS(C1:E4)', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 3); oParser = new parserFormula('COLUMNS({1,2,3;4,5,6})', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 3); //TODO нужна другая функция для тестирования //testArrayFormula2("COLUMNS", 1, 1); }); test( "Test: \"ROW\"", function () { oParser = new parserFormula('ROW(B6)', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 6); oParser = new parserFormula('ROW(C16)', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 16); oParser = new parserFormula('ROW()', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 1); oParser = new parserFormula('ROW()+ROW()', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); testArrayFormulaEqualsValues("6,6,6,6;7,7,7,7;8,8,8,8", "ROW()"); testArrayFormulaEqualsValues("1,1,1,1;2,2,2,2;#N/A,#N/A,#N/A,#N/A", "ROW(A1:C2)"); testArrayFormulaEqualsValues("1,1,1,1;1,1,1,1;1,1,1,1", "ROW(A1:B1)"); testArrayFormulaEqualsValues("1,1,1,1;1,1,1,1;1,1,1,1", "ROW(A1)"); }); test( "Test: \"ROWS\"", function () { oParser = new parserFormula('ROWS(C1:E4)', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 4); oParser = new parserFormula('ROWS({1,2,3;4,5,6})', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); //TODO нужна другая функция для тестирования //testArrayFormula2("COLUMNS", 1, 1); }); test( "Test: \"SUBTOTAL\"", function () { ws.getRange2( "A102" ).setValue( "120" ); ws.getRange2( "A103" ).setValue( "10" ); ws.getRange2( "A104" ).setValue( "150" ); ws.getRange2( "A105" ).setValue( "23" ); oParser = new parserFormula( "SUBTOTAL(1,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(1,A102:A105)" ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 75.75, "SUBTOTAL(1,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(2,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(2,A102:A105)" ); strictEqual( oParser.calculate().getValue(), 4, "SUBTOTAL(2,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(3,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(3,A102:A105)" ); strictEqual( oParser.calculate().getValue(), 4, "SUBTOTAL(3,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(4,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(4,A102:A105)" ); strictEqual( oParser.calculate().getValue(), 150, "SUBTOTAL(4,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(5,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(5,A102:A105)" ); strictEqual( oParser.calculate().getValue(), 10, "SUBTOTAL(5,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(6,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(6,A102:A105)" ); strictEqual( oParser.calculate().getValue(), 4140000, "SUBTOTAL(6,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(7,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(7,A102:A105)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 69.70592992, "SUBTOTAL(7,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(8,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(8,A102:A105)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 60.36710611, "SUBTOTAL(8,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(9,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(9,A102:A105)" ); strictEqual( oParser.calculate().getValue(), 303, "SUBTOTAL(9,A102:A105)"); } ); test( "Test: \"MID\"", function () { ws.getRange2( "A101" ).setValue( "Fluid Flow" ); oParser = new parserFormula( "MID(A101,1,5)", "A2", ws ); ok( oParser.parse(), "MID(A101,1,5)" ); strictEqual( oParser.calculate().getValue(), "Fluid", "MID(A101,1,5)"); oParser = new parserFormula( "MID(A101,7,20)", "A2", ws ); ok( oParser.parse(), "MID(A101,7,20)" ); strictEqual( oParser.calculate().getValue(), "Flow", "MID(A101,7,20)"); oParser = new parserFormula( "MID(A101,20,5)", "A2", ws ); ok( oParser.parse(), "MID(A101,20,5)" ); strictEqual( oParser.calculate().getValue(), "", "MID(A101,20,5))"); oParser = new parserFormula( "MID(TRUE,2,5)", "A2", ws ); ok( oParser.parse(), "MID(TRUE,2,5)" ); strictEqual( oParser.calculate().getValue(), "RUE", "MID(TRUE,2,5)"); testArrayFormula2("MID", 3, 3); } ); test( "Test: \"MIDB\"", function () { ws.getRange2( "A101" ).setValue( "Fluid Flow" ); oParser = new parserFormula( "MIDB(A101,1,5)", "A2", ws ); ok( oParser.parse(), "MIDB(A101,1,5)" ); strictEqual( oParser.calculate().getValue(), "Fluid", "MIDB(A101,1,5)"); oParser = new parserFormula( "MIDB(A101,7,20)", "A2", ws ); ok( oParser.parse(), "MIDB(A101,7,20)" ); strictEqual( oParser.calculate().getValue(), "Flow", "MIDB(A101,7,20)"); oParser = new parserFormula( "MIDB(A101,20,5)", "A2", ws ); ok( oParser.parse(), "MIDB(A101,20,5)" ); strictEqual( oParser.calculate().getValue(), "", "MIDB(A101,20,5))"); oParser = new parserFormula( "MIDB(TRUE,2,5)", "A2", ws ); ok( oParser.parse(), "MIDB(TRUE,2,5)" ); strictEqual( oParser.calculate().getValue(), "RUE", "MIDB(TRUE,2,5)"); } ); test( "Test: \"MINUTE\"", function () { ws.getRange2( "A202" ).setValue( "12:45:00 PM" ); ws.getRange2( "A203" ).setValue( "7/18/2011 7:45" ); ws.getRange2( "A204" ).setValue( "4/21/2012" ); oParser = new parserFormula( "MINUTE(A202)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 45 ); oParser = new parserFormula( "MINUTE(A203)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 45 ); oParser = new parserFormula( "MINUTE(A204)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); ws.getRange2( "A205" ).setValue( "06/30/2020 20:00" ); ws.getRange2( "A206" ).setValue( "06/30/2020 21:15" ); ws.getRange2( "A207" ).setValue( "06/30/2020 23:15" ); oParser = new parserFormula( "MINUTE(A206-A205)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 15 ); oParser = new parserFormula( "MINUTE(A207-A205)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 15 ); oParser = new parserFormula( "MINUTE(A207-A206)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MINUTE(A207+A206)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30 ); oParser = new parserFormula( "MINUTE(123.1231231 - 1.12334343)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 59 ); oParser = new parserFormula( "MINUTE(1.12334343 - 123.1231231)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); } ); /*test( "Test: \"MINVERSE\"", function () { ws.getRange2( "A202" ).setValue( "4" ); ws.getRange2( "A203" ).setValue( "2" ); ws.getRange2( "B202" ).setValue( "-1" ); ws.getRange2( "B203" ).setValue( "0" ); oParser = new parserFormula( "MINVERSE({4,-1;2,0})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); } );*/ test( "Test: \"FIND\"", function () { ws.getRange2( "A101" ).setValue( "Miriam McGovern" ); oParser = new parserFormula( 'FIND("M",A101)', "A2", ws ); ok( oParser.parse(), 'FIND("M",A101)' ); strictEqual( oParser.calculate().getValue(), 1, 'FIND("M",A101)'); oParser = new parserFormula( 'FIND("m",A101)', "A2", ws ); ok( oParser.parse(), 'FIND("m",A101)' ); strictEqual( oParser.calculate().getValue(), 6, 'FIND("m",A101)'); oParser = new parserFormula( 'FIND("M",A101,3)', "A2", ws ); ok( oParser.parse(), 'FIND("M",A101,3)' ); strictEqual( oParser.calculate().getValue(), 8, 'FIND("M",A101,3)'); oParser = new parserFormula( 'FIND("U",TRUE)', "A2", ws ); ok( oParser.parse(), 'FIND("T",TRUE)' ); strictEqual( oParser.calculate().getValue(), 3, 'FIND("T",TRUE)'); testArrayFormula2("FIND", 2, 3); } ); test( "Test: \"FINDB\"", function () { ws.getRange2( "A101" ).setValue( "Miriam McGovern" ); oParser = new parserFormula( 'FINDB("M",A101)', "A2", ws ); ok( oParser.parse(), 'FINDB("M",A101)' ); strictEqual( oParser.calculate().getValue(), 1, 'FINDB("M",A101)'); oParser = new parserFormula( 'FINDB("m",A101)', "A2", ws ); ok( oParser.parse(), 'FINDB("m",A101)' ); strictEqual( oParser.calculate().getValue(), 6, 'FINDB("m",A101)'); oParser = new parserFormula( 'FINDB("M",A101,3)', "A2", ws ); ok( oParser.parse(), 'FINDB("M",A101,3)' ); strictEqual( oParser.calculate().getValue(), 8, 'FINDB("M",A101,3)'); oParser = new parserFormula( 'FINDB("U",TRUE)', "A2", ws ); ok( oParser.parse(), 'FINDB("T",TRUE)' ); strictEqual( oParser.calculate().getValue(), 3, 'FINDB("T",TRUE)'); } ); test( "Test: \">\"", function () { oParser = new parserFormula( '1.123>1.5', "A2", ws ); ok( oParser.parse(), '1.123>1.5' ); strictEqual( oParser.calculate().getValue(), "FALSE", '1.123>1.5'); oParser = new parserFormula( '1.555>1.5', "A2", ws ); ok( oParser.parse(), '1.555>1.5' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.555>1.5'); } ); test( "Test: \"<\"", function () { oParser = new parserFormula( '1.123<1.5', "A2", ws ); ok( oParser.parse(), '1.123<1.5' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.123<1.5'); oParser = new parserFormula( '1.555<1.5', "A2", ws ); ok( oParser.parse(), '1.555<1.5' ); strictEqual( oParser.calculate().getValue(), "FALSE", '1.555<1.5'); } ); test( "Test: \"=\"", function () { oParser = new parserFormula( '1.123=1.5', "A2", ws ); ok( oParser.parse(), '1.123=1.5' ); strictEqual( oParser.calculate().getValue(), "FALSE", '1.123=1.5'); oParser = new parserFormula( '1.555=1.555', "A2", ws ); ok( oParser.parse(), '1.555=1.555' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.555=1.555'); } ); test( "Test: \"<>\"", function () { oParser = new parserFormula( '1.123<>1.5', "A2", ws ); ok( oParser.parse(), '1.123<>1.5' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.123<>1.5'); oParser = new parserFormula( '1.555<>1.555', "A2", ws ); ok( oParser.parse(), '1.555<>1.555' ); strictEqual( oParser.calculate().getValue(), "FALSE", '1.555<>1.555'); } ); test( "Test: \">=\"", function () { oParser = new parserFormula( '1.123>=1.5', "A2", ws ); ok( oParser.parse(), '1.123>=1.5' ); strictEqual( oParser.calculate().getValue(), "FALSE", '1.123>=1.5'); oParser = new parserFormula( '1.555>=1.555', "A2", ws ); ok( oParser.parse(), '1.555>=1.555' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.555>=1.555'); oParser = new parserFormula( '1.557>=1.555', "A2", ws ); ok( oParser.parse(), '1.557>=1.555' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.557>=1.555'); } ); test( "Test: \"<=\"", function () { oParser = new parserFormula( '1.123<=1.5', "A2", ws ); ok( oParser.parse(), '1.123<=1.5' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.123<=1.5'); oParser = new parserFormula( '1.555<=1.555', "A2", ws ); ok( oParser.parse(), '1.555<=1.555' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.555<=1.555'); oParser = new parserFormula( '1.557<=1.555', "A2", ws ); ok( oParser.parse(), '1.557<=1.555' ); strictEqual( oParser.calculate().getValue(), "FALSE", '1.557<=1.555'); } ); test( "Test: \"ADDRESS\"", function () { oParser = new parserFormula( "ADDRESS(2,3,2)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,2)" ); strictEqual( oParser.calculate().getValue(), "C$2", "ADDRESS(2,3,2)"); oParser = new parserFormula( "ADDRESS(2,3,2,FALSE)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,2,FALSE)" ); strictEqual( oParser.calculate().getValue(), "R2C[3]", "ADDRESS(2,3,2,FALSE)"); oParser = new parserFormula( 'ADDRESS(2,3,1,FALSE,"[Book1]Sheet1")', "A2", ws ); ok( oParser.parse(), 'ADDRESS(2,3,1,FALSE,"[Book1]Sheet1")' ); strictEqual( oParser.calculate().getValue(), "'[Book1]Sheet1'!R2C3", 'ADDRESS(2,3,1,FALSE,"[Book1]Sheet1")'); oParser = new parserFormula( 'ADDRESS(2,3,1,FALSE,"EXCEL SHEET")', "A2", ws ); ok( oParser.parse(), 'ADDRESS(2,3,1,FALSE,"EXCEL SHEET")' ); strictEqual( oParser.calculate().getValue(), "'EXCEL SHEET'!R2C3", 'ADDRESS(2,3,1,FALSE,"EXCEL SHEET")'); ws.getRange2( "A101" ).setValue( "" ); oParser = new parserFormula( "ADDRESS(2,3,2,1,A101)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,2,1,A101" ); strictEqual( oParser.calculate().getValue(), "!C$2", "ADDRESS(2,3,2,1,A101"); ws.getRange2( "A101" ).setValue( "'" ); oParser = new parserFormula( "ADDRESS(2,3,2,1,A101)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,2,1,A101" ); strictEqual( oParser.calculate().getValue(), "!C$2", "ADDRESS(2,3,2,1,A101"); oParser = new parserFormula( 'ADDRESS(2,3,2,1,"")', "A2", ws ); ok( oParser.parse(), 'ADDRESS(2,3,2,1,"")' ); strictEqual( oParser.calculate().getValue(), "!C$2", 'ADDRESS(2,3,2,1,"")'); oParser = new parserFormula( "ADDRESS(2,3,2,1,\"'\")", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,2,1,\"'\")" ); strictEqual( oParser.calculate().getValue(), "''''!C$2", "ADDRESS(2,3,2,1,\"'\")"); oParser = new parserFormula( "ADDRESS(2,3,,,1)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,,,1)" ); strictEqual( oParser.calculate().getValue(), "'1'!$C$2", "ADDRESS(2,3,,,1)"); oParser = new parserFormula( "ADDRESS(2,3,1,,1)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,1,,1)" ); strictEqual( oParser.calculate().getValue(), "'1'!$C$2", "ADDRESS(2,3,1,,1)"); oParser = new parserFormula( "ADDRESS(2,3,2,,1)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,2,,1)" ); strictEqual( oParser.calculate().getValue(), "'1'!C$2", "ADDRESS(2,3,2,,1)"); oParser = new parserFormula( "ADDRESS(2,3,,TRUE,1)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,,TRUE,1)" ); strictEqual( oParser.calculate().getValue(), "'1'!$C$2", "ADDRESS(2,3,,TRUE,1)"); oParser = new parserFormula( "ADDRESS(2,3,,FALSE,1)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,,FALSE,1)" ); strictEqual( oParser.calculate().getValue(), "'1'!R2C3", "ADDRESS(2,3,,FALSE,1)"); oParser = new parserFormula( "ADDRESS(2,3,,FALSE,1)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,,FALSE,1)" ); strictEqual( oParser.calculate().getValue(), "'1'!R2C3", "ADDRESS(2,3,,FALSE,1)"); oParser = new parserFormula( "ADDRESS(1,7,,)", "A2", ws ); ok( oParser.parse(), "ADDRESS(1,7,,)" ); strictEqual( oParser.calculate().getValue(), "$G$1", "ADDRESS(1,7,,)"); oParser = new parserFormula( "ADDRESS(1,7,,,)", "A2", ws ); ok( oParser.parse(), "ADDRESS(1,7,,,)" ); strictEqual( oParser.calculate().getValue(), "$G$1", "ADDRESS(1,7,,,)"); oParser = new parserFormula( "ADDRESS(2.123,3.3213,2)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2.123,3.3213,2)" ); strictEqual( oParser.calculate().getValue(), "C$2", "ADDRESS(2.123,3.3213,2)"); testArrayFormula2("ADDRESS", 2, 5); } ); test( "Test: \"reference argument test\"", function () { ws.getRange2( "A1" ).setValue( "1" ); ws.getRange2( "A2" ).setValue( "2" ); ws.getRange2( "A3" ).setValue( "3" ); ws.getRange2( "A4" ).setValue( "4" ); ws.getRange2( "A5" ).setValue( "5" ); ws.getRange2( "A6" ).setValue( "6" ); ws.getRange2( "B1" ).setValue( "2" ); ws.getRange2( "B2" ).setValue( "" ); ws.getRange2( "B3" ).setValue( "3" ); ws.getRange2( "B4" ).setValue( "4" ); ws.getRange2( "B5" ).setValue( "5" ); ws.getRange2( "B6" ).setValue( "6" ); oParser = new parserFormula( 'IRR(SIN(A1:B4))', 'A2', ws ); ok( oParser.parse(),'IRR(SIN(A1:B4))' ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, -0.123554096,'IRR(SIN(A1:B4))'); oParser = new parserFormula( 'MIRR(SIN(A2:B4),1,1)', 'A2', ws ); ok( oParser.parse(),'MIRR(SIN(A2:B4),1,1)' ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 2.36894463,'MIRR(SIN(A2:B4),1,1)'); oParser = new parserFormula( 'COLUMN(INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'COLUMN(INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'COLUMN(INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'COLUMNS(SIN($A$1:$B$4))', 'A2', ws ); ok( oParser.parse(),'COLUMNS(SIN($A$1:$B$4))' ); strictEqual( oParser.calculate().getValue(),2,'COLUMNS(SIN($A$1:$B$4))'); oParser = new parserFormula( 'INDEX(SIN(A1:B3),1,1)', 'A2', ws ); ok( oParser.parse(),'INDEX(SIN(A1:B3),1,1)' ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0,0.841470985,'INDEX(SIN(A1:B3),1,1)'); /*oParser = new parserFormula( 'OFFSET(INDEX(A1:B3,1,1),1,1)', 'A2', ws ); ok( oParser.parse(),'OFFSET(INDEX(A1:B3,1,1),1,1)' ); strictEqual( oParser.calculate().getValue(),0,'OFFSET(INDEX(A1:B3,1,1),1,1)');*/ oParser = new parserFormula( 'ROW(INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'ROW(INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'ROW(INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'ROWS(SIN(A1:B3))', 'A2', ws ); ok( oParser.parse(),'ROWS(SIN(A1:B3))' ); strictEqual( oParser.calculate().getValue(),3,'ROWS(SIN(A1:B3))'); oParser = new parserFormula( 'SUBTOTAL(1,INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'SUBTOTAL(1,INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'SUBTOTAL(1,INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'SUMIF(INDEX(A1:B3,1,1),1,INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'SUMIF(INDEX(A1:B3,1,1),1,INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'SUMIF(INDEX(A1:B3,1,1),1,INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'SUMIFS(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'SUMIFS(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'SUMIFS(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'AVERAGEIF(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'AVERAGEIF(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'AVERAGEIF(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'COUNTBLANK(INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'COUNTBLANK(INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),0,'COUNTBLANK(INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'COUNTIF(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'COUNTIF(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'COUNTIF(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'COUNTIFS(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'COUNTIFS(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'COUNTIFS(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))'); ws.getRange2( "A2" ).setValue( "qq" ); ws.getRange2( "A3" ).setValue( "ww" ); ws.getRange2( "A4" ).setValue( "ee" ); ws.getRange2( "A5" ).setValue( "qq" ); ws.getRange2( "A6" ).setValue( "qq" ); ws.getRange2( "A7" ).setValue( "ww" ); ws.getRange2( "A8" ).setValue( "ww" ); ws.getRange2( "A9" ).setValue( "ww" ); ws.getRange2( "A10" ).setValue( "eee" ); ws.getRange2( "B1" ).setValue( "qqqq" ); ws.getRange2( "B2" ).setValue( "ee" ); var _f = 'IFERROR(INDEX($A$2:$A$10,MATCH(0,INDEX(COUNTIF($B$1:B1,$A$2:$A$10)+(COUNTIF($A$2:$A$10,$A$2:$A$10)<>1),0,0),0)),"")'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue().getValue(),"ee",_f); _f = 'IFERROR(INDEX($A$2:$A$10,MATCH(0,INDEX(COUNTIF($B$1:B2,$A$2:$A$10)+(COUNTIF($A$2:$A$10,$A$2:$A$10)<>1),0,0),0)),"")'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue().getValue(),"eee",_f); _f = 'INDEX($A$2:$A$10,MATCH(0,INDEX(COUNTIF($B$1:B1,$A$2:$A$10)+(COUNTIF($A$2:$A$10,$A$2:$A$10)<>1),0,0),0))'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue().getValue(),"ee",_f); _f = 'MATCH(0,INDEX({1;1;0;1;1;1;1;1;0},0,0))'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue(),"#N/A",_f); _f = 'INDEX($A$2:$A$10,MATCH(0,INDEX({1;1;0;1;1;1;1;1;0},0,0),0))'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue().getValue(),"ee",_f); _f = 'INDEX($A$2:$A$10,3)'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue().getValue(),"ee",_f); _f = 'INDEX($A$2:$A$10,MATCH(0,{1;1;0;1;1;1;1;1;0},0))'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue().getValue(),"ee",_f); _f = 'MATCH(0,INDEX(COUNTIF($B$1:B1,$A$2:$A$10)+(COUNTIF($A$2:$A$10,$A$2:$A$10)<>1),0,0),0)'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue(),3,_f); } ); wb.dependencyFormulas.unlockRecal(); } );
cell/.unit-tests/FormulaTests.js
/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ $( function () { var cDate = Asc.cDate; function toFixed( n ) { return n;//.toFixed( AscCommonExcel.cExcelSignificantDigits ) - 0; } function difBetween( a, b ) { return Math.abs( a - b ) < dif } function _getPMT( fZins, fZzr, fBw, fZw, nF ){ var fRmz; if( fZins == 0.0 ) fRmz = ( fBw + fZw ) / fZzr; else{ var fTerm = Math.pow( 1.0 + fZins, fZzr ); if( nF > 0 ) fRmz = ( fZw * fZins / ( fTerm - 1.0 ) + fBw * fZins / ( 1.0 - 1.0 / fTerm ) ) / ( 1.0 + fZins ); else fRmz = fZw * fZins / ( fTerm - 1.0 ) + fBw * fZins / ( 1.0 - 1.0 / fTerm ); } return -fRmz; } function _getFV( fZins, fZzr, fRmz, fBw, nF ){ var fZw; if( fZins == 0.0 ) fZw = fBw + fRmz * fZzr; else{ var fTerm = Math.pow( 1.0 + fZins, fZzr ); if( nF > 0 ) fZw = fBw * fTerm + fRmz * ( 1.0 + fZins ) * ( fTerm - 1.0 ) / fZins; else fZw = fBw * fTerm + fRmz * ( fTerm - 1.0 ) / fZins; } return -fZw; } function _getDDB( cost, salvage, life, period, factor ) { var ddb, ipmt, oldCost, newCost; ipmt = factor / life; if ( ipmt >= 1 ) { ipmt = 1; if ( period == 1 ) oldCost = cost; else oldCost = 0; } else oldCost = cost * Math.pow( 1 - ipmt, period - 1 ); newCost = cost * Math.pow( 1 - ipmt, period ); if ( newCost < salvage ) ddb = oldCost - salvage; else ddb = oldCost - newCost; if ( ddb < 0 ) ddb = 0; return ddb; } function _getIPMT(rate, per, pv, type, pmt) { var ipmt; if ( per == 1 ) { if ( type > 0 ) ipmt = 0; else ipmt = -pv; } else { if ( type > 0 ) ipmt = _getFV( rate, per - 2, pmt, pv, 1 ) - pmt; else ipmt = _getFV( rate, per - 1, pmt, pv, 0 ); } return ipmt * rate } function _diffDate(d1, d2, mode){ var date1 = d1.getDate(), month1 = d1.getMonth(), year1 = d1.getFullYear(), date2 = d2.getDate(), month2 = d2.getMonth(), year2 = d2.getFullYear(); switch ( mode ) { case 0: return Math.abs( GetDiffDate360( date1, month1, year1, date2, month2, year2, true ) ); case 1: var yc = Math.abs( year2 - year1 ), sd = year1 > year2 ? d2 : d1, yearAverage = sd.isLeapYear() ? 366 : 365, dayDiff = Math.abs( d2 - d1 ); for ( var i = 0; i < yc; i++ ) { sd.addYears( 1 ); yearAverage += sd.isLeapYear() ? 366 : 365; } yearAverage /= (yc + 1); dayDiff /= c_msPerDay; return dayDiff; case 2: var dayDiff = Math.abs( d2 - d1 ); dayDiff /= c_msPerDay; return dayDiff; case 3: var dayDiff = Math.abs( d2 - d1 ); dayDiff /= c_msPerDay; return dayDiff; case 4: return Math.abs( GetDiffDate360( date1, month1, year1, date2, month2, year2, false ) ); default: return "#NUM!"; } } function _yearFrac(d1, d2, mode) { var date1 = d1.getDate(), month1 = d1.getMonth()+1, year1 = d1.getFullYear(), date2 = d2.getDate(), month2 = d2.getMonth()+1, year2 = d2.getFullYear(); switch ( mode ) { case 0: return Math.abs( GetDiffDate360( date1, month1, year1, date2, month2, year2, true ) ) / 360; case 1: var yc = /*Math.abs*/( year2 - year1 ), sd = year1 > year2 ? new cDate(d2) : new cDate(d1), yearAverage = sd.isLeapYear() ? 366 : 365, dayDiff = /*Math.abs*/( d2 - d1 ); for ( var i = 0; i < yc; i++ ) { sd.addYears( 1 ); yearAverage += sd.isLeapYear() ? 366 : 365; } yearAverage /= (yc + 1); dayDiff /= (yearAverage * c_msPerDay); return dayDiff; case 2: var dayDiff = Math.abs( d2 - d1 ); dayDiff /= (360 * c_msPerDay); return dayDiff; case 3: var dayDiff = Math.abs( d2 - d1 ); dayDiff /= (365 * c_msPerDay); return dayDiff; case 4: return Math.abs( GetDiffDate360( date1, month1, year1, date2, month2, year2, false ) ) / 360; default: return "#NUM!"; } } function _lcl_GetCouppcd(settl, matur, freq){ matur.setFullYear( settl.getFullYear() ); if( matur < settl ) matur.addYears( 1 ); while( matur > settl ){ matur.addMonths( -12 / freq ); } } function _lcl_GetCoupncd( settl, matur, freq ){ matur.setFullYear( settl.getFullYear() ); if( matur > settl ) matur.addYears( -1 ); while( matur <= settl ){ matur.addMonths( 12 / freq ); } } function _getcoupdaybs( settl, matur, frequency, basis ) { _lcl_GetCouppcd( settl, matur, frequency ); return _diffDate( settl, matur, basis ); } function _getcoupdays( settl, matur, frequency, basis ) { _lcl_GetCouppcd( settl, matur, frequency ); var n = new cDate( matur ); n.addMonths( 12 / frequency ); return _diffDate( matur, n, basis ); } function _getdiffdate( d1,d2, nMode ){ var bNeg = d1 > d2; if( bNeg ) { var n = d2; d2 = d1; d1 = n; } var nRet,pOptDaysIn1stYear; var nD1 = d1.getDate(), nM1 = d1.getMonth(), nY1 = d1.getFullYear(), nD2 = d2.getDate(), nM2 = d2.getMonth(), nY2 = d2.getFullYear(); switch( nMode ) { case 0: // 0=USA (NASD) 30/360 case 4: // 4=Europe 30/360 { var bLeap = d1.isLeapYear(); var nDays, nMonths/*, nYears*/; nMonths = nM2 - nM1; nDays = nD2 - nD1; nMonths += ( nY2 - nY1 ) * 12; nRet = nMonths * 30 + nDays; if( nMode == 0 && nM1 == 2 && nM2 != 2 && nY1 == nY2 ) nRet -= bLeap? 1 : 2; pOptDaysIn1stYear = 360; } break; case 1: // 1=exact/exact pOptDaysIn1stYear = d1.isLeapYear() ? 366 : 365; nRet = d2 - d1; break; case 2: // 2=exact/360 nRet = d2 - d1; pOptDaysIn1stYear = 360; break; case 3: //3=exact/365 nRet = d2 - d1; pOptDaysIn1stYear = 365; break; } return (bNeg ? -nRet : nRet) / c_msPerDay / pOptDaysIn1stYear; } function _getprice( nSettle, nMat, fRate, fYield, fRedemp, nFreq, nBase ){ var fdays = AscCommonExcel.getcoupdays( new cDate(nSettle), new cDate(nMat), nFreq, nBase ), fdaybs = AscCommonExcel.getcoupdaybs( new cDate(nSettle), new cDate(nMat), nFreq, nBase ), fnum = AscCommonExcel.getcoupnum( new cDate(nSettle), (nMat), nFreq, nBase ), fdaysnc = ( fdays - fdaybs ) / fdays, fT1 = 100 * fRate / nFreq, fT2 = 1 + fYield / nFreq, res = fRedemp / ( Math.pow( 1 + fYield / nFreq, fnum - 1 + fdaysnc ) ); /*var fRet = fRedemp / ( Math.pow( 1.0 + fYield / nFreq, fnum - 1.0 + fdaysnc ) ); fRet -= 100.0 * fRate / nFreq * fdaybs / fdays; var fT1 = 100.0 * fRate / nFreq; var fT2 = 1.0 + fYield / nFreq; for( var fK = 0.0 ; fK < fnum ; fK++ ){ fRet += fT1 / Math.pow( fT2, fK + fdaysnc ); } return fRet;*/ if( fnum == 1){ return (fRedemp + fT1) / (1 + fdaysnc * fYield / nFreq) - 100 * fRate / nFreq * fdaybs / fdays; } res -= 100 * fRate / nFreq * fdaybs / fdays; for ( var i = 0; i < fnum; i++ ) { res += fT1 / Math.pow( fT2, i + fdaysnc ); } return res; } function _getYield( nSettle, nMat, fCoup, fPrice, fRedemp, nFreq, nBase ){ var fRate = fCoup, fPriceN = 0.0, fYield1 = 0.0, fYield2 = 1.0; var fPrice1 = _getprice( nSettle, nMat, fRate, fYield1, fRedemp, nFreq, nBase ); var fPrice2 = _getprice( nSettle, nMat, fRate, fYield2, fRedemp, nFreq, nBase ); var fYieldN = ( fYield2 - fYield1 ) * 0.5; for( var nIter = 0 ; nIter < 100 && fPriceN != fPrice ; nIter++ ) { fPriceN = _getprice( nSettle, nMat, fRate, fYieldN, fRedemp, nFreq, nBase ); if( fPrice == fPrice1 ) return fYield1; else if( fPrice == fPrice2 ) return fYield2; else if( fPrice == fPriceN ) return fYieldN; else if( fPrice < fPrice2 ) { fYield2 *= 2.0; fPrice2 = _getprice( nSettle, nMat, fRate, fYield2, fRedemp, nFreq, nBase ); fYieldN = ( fYield2 - fYield1 ) * 0.5; } else { if( fPrice < fPriceN ) { fYield1 = fYieldN; fPrice1 = fPriceN; } else { fYield2 = fYieldN; fPrice2 = fPriceN; } fYieldN = fYield2 - ( fYield2 - fYield1 ) * ( ( fPrice - fPrice2 ) / ( fPrice1 - fPrice2 ) ); } } if( Math.abs( fPrice - fPriceN ) > fPrice / 100.0 ) return "#NUM!"; // result not precise enough return fYieldN; } function _getyieldmat( nSettle, nMat, nIssue, fRate, fPrice, nBase ){ var fIssMat = _yearFrac( nIssue, nMat, nBase ); var fIssSet = _yearFrac( nIssue, nSettle, nBase ); var fSetMat = _yearFrac( nSettle, nMat, nBase ); var y = 1.0 + fIssMat * fRate; y /= fPrice / 100.0 + fIssSet * fRate; y--; y /= fSetMat; return y; } function _coupnum( settlement, maturity, frequency, basis ) { basis = ( basis !== undefined ? basis : 0 ); var n = new cDate(maturity); _lcl_GetCouppcd( settlement, n, frequency ); var nMonths = (maturity.getFullYear() - n.getFullYear()) * 12 + maturity.getMonth() - n.getMonth(); return nMonths * frequency / 12 ; } function _duration( settlement, maturity, coupon, yld, frequency, basis ){ var dbc = AscCommonExcel.getcoupdaybs(new cDate( settlement ),new cDate( maturity ),frequency,basis), coupD = AscCommonExcel.getcoupdays(new cDate( settlement ),new cDate( maturity ),frequency,basis), numCoup = AscCommonExcel.getcoupnum(new cDate( settlement ),new cDate( maturity ),frequency); if ( settlement >= maturity || basis < 0 || basis > 4 || ( frequency != 1 && frequency != 2 && frequency != 4 ) || yld < 0 || coupon < 0 ){ return "#NUM!"; } var duration = 0, p = 0; var dsc = coupD - dbc; var diff = dsc / coupD - 1; yld = yld / frequency + 1; coupon *= 100/frequency; for(var index = 1; index <= numCoup; index++ ){ var di = index + diff; var yldPOW = Math.pow( yld, di); duration += di * coupon / yldPOW; p += coupon / yldPOW; } duration += (diff + numCoup) * 100 / Math.pow( yld, diff + numCoup); p += 100 / Math.pow( yld, diff + numCoup); return duration / p / frequency ; } function numDivFact(num, fact){ var res = num / Math.fact(fact); res = res.toString(); return res; } function testArrayFormula(func, dNotSupportAreaArg) { var getValue = function(ref) { oParser = new parserFormula( func + "(" + ref + ")", "A2", ws ); ok( oParser.parse() ); return oParser.calculate().getValue(); }; //***array-formula*** ws.getRange2( "A100" ).setValue( "1" ); ws.getRange2( "B100" ).setValue( "3" ); ws.getRange2( "C100" ).setValue( "-4" ); ws.getRange2( "A101" ).setValue( "2" ); ws.getRange2( "B101" ).setValue( "4" ); ws.getRange2( "C101" ).setValue( "5" ); oParser = new parserFormula( func + "(A100:C101)", "A1", ws ); oParser.setArrayFormulaRef(ws.getRange2("E106:H107").bbox); ok( oParser.parse() ); var array = oParser.calculate(); if(AscCommonExcel.cElementType.array === array.type) { strictEqual( array.getElementRowCol(0,0).getValue(), getValue("A100")); strictEqual( array.getElementRowCol(0,1).getValue(), getValue("B100")); strictEqual( array.getElementRowCol(0,2).getValue(), getValue("C100")); strictEqual( array.getElementRowCol(1,0).getValue(), getValue("A101")); strictEqual( array.getElementRowCol(1,1).getValue(), getValue("B101")); strictEqual( array.getElementRowCol(1,2).getValue(), getValue("C101")); } else { if(!dNotSupportAreaArg) { strictEqual( false, true); } consoleLog("func: " + func + " don't return area array"); } oParser = new parserFormula( func + "({1,2,-3})", "A1", ws ); oParser.setArrayFormulaRef(ws.getRange2("E106:H107").bbox); ok( oParser.parse() ); array = oParser.calculate(); strictEqual( array.getElementRowCol(0,0).getValue(), getValue(1)); strictEqual( array.getElementRowCol(0,1).getValue(), getValue(2)); strictEqual( array.getElementRowCol(0,2).getValue(), getValue(-3)); } //returnOnlyValue - те функции, на вход которых всегда должны подаваться массивы и которые возвращают единственное значение function testArrayFormula2(func, minArgCount, maxArgCount, dNotSupportAreaArg, returnOnlyValue) { var getValue = function(ref, countArg) { var argStr = "("; for(var j = 1; j <= countArg; j++) { argStr += ref; if(i !== j) { argStr += ","; } else { argStr += ")"; } } oParser = new parserFormula( func + argStr, "A2", ws ); ok( oParser.parse() ); return oParser.calculate().getValue(); }; //***array-formula*** ws.getRange2( "A100" ).setValue( "1" ); ws.getRange2( "B100" ).setValue( "3" ); ws.getRange2( "C100" ).setValue( "-4" ); ws.getRange2( "A101" ).setValue( "2" ); ws.getRange2( "B101" ).setValue( "4" ); ws.getRange2( "C101" ).setValue( "5" ); //формируем массив значений var randomArray = []; var randomStrArray = "{"; var maxArg = 4; for(var i = 1; i <= maxArg; i++) { var randVal = Math.random(); randomArray.push(randVal); randomStrArray += randVal; if(i !== maxArg) { randomStrArray += ","; } else { randomStrArray += "}"; } } for(var i = minArgCount; i <= maxArgCount; i++) { var argStrArr = "("; var randomArgStrArr = "("; for(var j = 1; j <= i; j++) { argStrArr += "A100:C101"; randomArgStrArr += randomStrArray; if(i !== j) { argStrArr += ","; randomArgStrArr += ","; } else { argStrArr += ")"; randomArgStrArr += ")"; } } oParser = new parserFormula( func + argStrArr, "A1", ws ); oParser.setArrayFormulaRef(ws.getRange2("E106:H107").bbox); ok( oParser.parse() ); var array = oParser.calculate(); if(AscCommonExcel.cElementType.array === array.type) { strictEqual( array.getElementRowCol(0,0).getValue(), getValue("A100", i)); strictEqual( array.getElementRowCol(0,1).getValue(), getValue("B100", i)); strictEqual( array.getElementRowCol(0,2).getValue(), getValue("C100", i)); strictEqual( array.getElementRowCol(1,0).getValue(), getValue("A101", i)); strictEqual( array.getElementRowCol(1,1).getValue(), getValue("B101", i)); strictEqual( array.getElementRowCol(1,2).getValue(), getValue("C101", i)); } else { if(!(dNotSupportAreaArg || returnOnlyValue)) { strictEqual( false, true); } consoleLog("func: " + func + " don't return area array"); } oParser = new parserFormula( func + randomArgStrArr, "A1", ws ); oParser.setArrayFormulaRef(ws.getRange2("E106:H107").bbox); ok( oParser.parse() ); array = oParser.calculate(); if(AscCommonExcel.cElementType.array === array.type) { strictEqual( array.getElementRowCol(0,0).getValue(), getValue(randomArray[0], i)); strictEqual( array.getElementRowCol(0,1).getValue(), getValue(randomArray[1], i)); strictEqual( array.getElementRowCol(0,2).getValue(), getValue(randomArray[2], i)); } else { if(!returnOnlyValue) { strictEqual( false, true); } consoleLog("func: " + func + " don't return array"); } } } function testArrayFormulaEqualsValues(str, formula,isNotLowerCase) { //***array-formula*** ws.getRange2( "A1" ).setValue( "1" ); ws.getRange2( "B1" ).setValue( "3.123" ); ws.getRange2( "C1" ).setValue( "-4" ); ws.getRange2( "A2" ).setValue( "2" ); ws.getRange2( "B2" ).setValue( "4" ); ws.getRange2( "C2" ).setValue( "5" ); oParser = new parserFormula( formula, "A1", ws ); oParser.setArrayFormulaRef(ws.getRange2("E6:H8").bbox); ok( oParser.parse() ); var array = oParser.calculate(); var splitStr = str.split(";"); for(var i = 0; i < splitStr.length; i++) { var subSplitStr = splitStr[i].split(","); for(var j = 0; j < subSplitStr.length; j++) { var valMs = subSplitStr[j]; var element; if(array.getElementRowCol) { var row = 1 === array.array.length ? 0 : i; var col = 1 === array.array[0].length ? 0 : j; if(array.array[row] && array.array[row][col]) { element = array.getElementRowCol(row, col); } else { element = new window['AscCommonExcel'].cError(window['AscCommonExcel'].cErrorType.not_available); } } else { element = array; } var ourVal = element && undefined != element.value ? element.value.toString() : "#N/A"; if(!isNotLowerCase) { valMs = valMs.toLowerCase(); ourVal = ourVal.toLowerCase(); } strictEqual(valMs, ourVal, "formula: " + formula + " i: " + i + " j: " + j) } } } function consoleLog(val) { //console.log(val); } var newFormulaParser = false; var c_msPerDay = AscCommonExcel.c_msPerDay; var parserFormula = AscCommonExcel.parserFormula; var GetDiffDate360 = AscCommonExcel.GetDiffDate360; var fSortAscending = AscCommon.fSortAscending; var g_oIdCounter = AscCommon.g_oIdCounter; var oParser, wb, ws, dif = 1e-9, sData = AscCommon.getEmpty(), tmp; if ( AscCommon.c_oSerFormat.Signature === sData.substring( 0, AscCommon.c_oSerFormat.Signature.length ) ) { wb = new AscCommonExcel.Workbook( new AscCommonExcel.asc_CHandlersList(), {wb:{getWorksheet:function(){}}} ); AscCommon.History.init(wb); AscCommon.g_oTableId.init(); if ( this.User ) g_oIdCounter.Set_UserId(this.User.asc_getId()); AscCommonExcel.g_oUndoRedoCell = new AscCommonExcel.UndoRedoCell(wb); AscCommonExcel.g_oUndoRedoWorksheet = new AscCommonExcel.UndoRedoWoorksheet(wb); AscCommonExcel.g_oUndoRedoWorkbook = new AscCommonExcel.UndoRedoWorkbook(wb); AscCommonExcel.g_oUndoRedoCol = new AscCommonExcel.UndoRedoRowCol(wb, false); AscCommonExcel.g_oUndoRedoRow = new AscCommonExcel.UndoRedoRowCol(wb, true); AscCommonExcel.g_oUndoRedoComment = new AscCommonExcel.UndoRedoComment(wb); AscCommonExcel.g_oUndoRedoAutoFilters = new AscCommonExcel.UndoRedoAutoFilters(wb); AscCommonExcel.g_DefNameWorksheet = new AscCommonExcel.Worksheet(wb, -1); g_oIdCounter.Set_Load(false); var oBinaryFileReader = new AscCommonExcel.BinaryFileReader(); oBinaryFileReader.Read( sData, wb ); ws = wb.getWorksheet( wb.getActive() ); AscCommonExcel.getFormulasInfo(); } /*QUnit.log( function ( details ) { console.log( "Log: " + details.name + ", result - " + details.result ); } );*/ wb.dependencyFormulas.lockRecal(); module( "Formula" ); test( "Test: \"ABS\"", function () { ws.getRange2( "A22" ).setValue( "-4" ); oParser = new parserFormula( "ABS(2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "ABS(-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "ABS(A22)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); testArrayFormula("ABS"); } ); test( "Test: \"Absolute reference\"", function () { ws.getRange2( "A7" ).setValue( "1" ); ws.getRange2( "A8" ).setValue( "2" ); ws.getRange2( "A9" ).setValue( "3" ); oParser = new parserFormula( 'A$7+A8', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( 'A$7+A$8', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( '$A$7+$A$8', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( 'SUM($A$7:$A$9)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); } ); test( "Test: \"Asc\"", function () { oParser = new parserFormula( 'ASC("teSt")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "teSt" ); oParser = new parserFormula( 'ASC("デジタル")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "デジタル" ); oParser = new parserFormula( 'ASC("￯")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "" ); } ); test( "Test: \"Cross\"", function () { ws.getRange2( "A7" ).setValue( "1" ); ws.getRange2( "A8" ).setValue( "2" ); ws.getRange2( "A9" ).setValue( "3" ); oParser = new parserFormula( 'A7:A9', null, ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().cross(new Asc.Range(0, 5, 0, 5), ws.getId()).getValue(), "#VALUE!" ); strictEqual( oParser.calculate().cross(new Asc.Range(0, 6, 0, 6), ws.getId()).getValue(), 1 ); strictEqual( oParser.calculate().cross(new Asc.Range(0, 7, 0, 7), ws.getId()).getValue(), 2 ); strictEqual( oParser.calculate().cross(new Asc.Range(0, 8, 0, 8), ws.getId()).getValue(), 3 ); strictEqual( oParser.calculate().cross(new Asc.Range(0, 9, 0, 9), ws.getId()).getValue(), "#VALUE!" ); } ); test( "Test: \"Defined names cycle\"", function () { var newNameQ = new Asc.asc_CDefName("q", "SUM('"+ws.getName()+"'!A2)"); wb.editDefinesNames(null, newNameQ); ws.getRange2( "Q1" ).setValue( "=q" ); ws.getRange2( "Q2" ).setValue( "=q" ); ws.getRange2( "Q3" ).setValue( "1" ); strictEqual( ws.getRange2( "Q1" ).getValueWithFormat(), "1" ); strictEqual( ws.getRange2( "Q2" ).getValueWithFormat(), "1" ); var newNameW = new Asc.asc_CDefName("w", "'"+ws.getName()+"'!A1"); wb.editDefinesNames(null, newNameW); ws.getRange2( "Q4" ).setValue( "=w" ); strictEqual( ws.getRange2( "Q4" ).getValueWithFormat(), "#REF!" ); //clean up ws.getRange2( "Q1:Q4" ).cleanAll(); wb.delDefinesNames(newNameW); wb.delDefinesNames(newNameQ); }); test( "Test: \"Parse intersection\"", function () { ws.getRange2( "A7" ).setValue( "1" ); ws.getRange2( "A8" ).setValue( "2" ); ws.getRange2( "A9" ).setValue( "3" ); oParser = new parserFormula( '1 + ( A7 +A8 ) * 2', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.assemble(), "1+(A7+A8)*2" ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( 'sum A1:A5', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.assemble(), "sum A1:A5" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( 'sum( A1:A5 , B1:B5 ) ', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.assemble(), "SUM(A1:A5,B1:B5)" ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( 'sum( A1:A5 , B1:B5 , " 3 , 14 15 92 6 " ) ', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.assemble(), 'SUM(A1:A5,B1:B5," 3 , 14 15 92 6 ")' ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); } ); test( "Test: \"Arithmetical operations\"", function () { oParser = new parserFormula( '1+3', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( '(1+2)*4+3', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), (1 + 2) * 4 + 3 ); oParser = new parserFormula( '2^52', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.pow( 2, 52 ) ); oParser = new parserFormula( '-10', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -10 ); oParser = new parserFormula( '-10*2', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -20 ); oParser = new parserFormula( '-10+10', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( '12%', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0.12 ); oParser = new parserFormula( "2<>\"3\"", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE", "2<>\"3\"" ); oParser = new parserFormula( "2=\"3\"", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE", "2=\"3\"" ); oParser = new parserFormula( "2>\"3\"", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE", "2>\"3\"" ); oParser = new parserFormula( "\"f\">\"3\"", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( "\"f\"<\"3\"", "A1", ws ); ok( oParser.parse() ); strictEqual( "FALSE", oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( "FALSE>=FALSE", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( "\"TRUE\"&\"TRUE\"", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUETRUE" ); oParser = new parserFormula( "10*\"\"", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "-TRUE", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1 ); } ); test( "Test: \"ACOS\"", function () { oParser = new parserFormula( 'ACOS(-0.5)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 2.094395102 ); testArrayFormula("ACOS"); } ); test( "Test: \"ACOSH\"", function () { oParser = new parserFormula( 'ACOSH(1)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( 'ACOSH(10)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 2.9932228 ); testArrayFormula("ACOSH"); } ); test( "Test: \"ASIN\"", function () { oParser = new parserFormula( 'ASIN(-0.5)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, -0.523598776 ); testArrayFormula("ASIN"); } ); test( "Test: \"ASINH\"", function () { oParser = new parserFormula( 'ASINH(-2.5)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, -1.647231146 ); oParser = new parserFormula( 'ASINH(10)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 2.99822295 ); testArrayFormula("ASINH"); } ); test( "Test: \"SIN have wrong arguments count\"", function () { oParser = new parserFormula( 'SIN(3.1415926,3.1415926*2)', "A1", ws ); ok( !oParser.parse() ); } ); test( "Test: \"SIN(3.1415926)\"", function () { oParser = new parserFormula( 'SIN(3.1415926)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.sin( 3.1415926 ) ); testArrayFormula("SIN"); } ); test( "Test: \"SQRT\"", function () { ws.getRange2( "A202" ).setValue( "-16" ); oParser = new parserFormula( 'SQRT(16)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( 'SQRT(A202)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( 'SQRT(ABS(A202))', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); testArrayFormula("SQRT"); } ); test( "Test: \"SQRTPI\"", function () { oParser = new parserFormula( 'SQRTPI(1)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 1.772454 ); oParser = new parserFormula( 'SQRTPI(2)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 2.506628 ); testArrayFormula("SQRTPI", true); } ); test( "Test: \"COS(PI()/2)\"", function () { oParser = new parserFormula( 'COS(PI()/2)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.cos( Math.PI / 2 ) ); } ); test( "Test: \"ACOT(2)\"", function () { oParser = new parserFormula( 'ACOT(2)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.PI / 2 - Math.atan(2) ); } ); test( "Test: \"ACOTH(6)\"", function () { oParser = new parserFormula( 'ACOTH(6)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.atanh(1 / 6) ); testArrayFormula("ACOTH"); } ); test( "Test: \"COT\"", function () { oParser = new parserFormula( 'COT(30)', "A1", ws ); ok( oParser.parse(), 'COT(30)' ); strictEqual( oParser.calculate().getValue().toFixed(3) - 0, -0.156, 'COT(30)' ); oParser = new parserFormula( 'COT(0)', "A1", ws ); ok( oParser.parse(), 'COT(0)' ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", 'COT(0)' ); oParser = new parserFormula( 'COT(1000000000)', "A1", ws ); ok( oParser.parse(), 'COT(1000000000)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'COT(1000000000)' ); oParser = new parserFormula( 'COT(-1000000000)', "A1", ws ); ok( oParser.parse(), 'COT(-1000000000)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'COT(-1000000000)' ); oParser = new parserFormula( 'COT(test)', "A1", ws ); ok( oParser.parse(), 'COT(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'COT(test)' ); oParser = new parserFormula( 'COT("test")', "A1", ws ); ok( oParser.parse(), 'COT("test")' ); strictEqual( oParser.calculate().getValue(), "#VALUE!", 'COT("test")' ); testArrayFormula("COT"); } ); test( "Test: \"COTH\"", function () { oParser = new parserFormula( 'COTH(2)', "A1", ws ); ok( oParser.parse(), 'COTH(2)' ); strictEqual( oParser.calculate().getValue().toFixed(3) - 0, 1.037, 'COTH(2)' ); oParser = new parserFormula( 'COTH(0)', "A1", ws ); ok( oParser.parse(), 'COTH(0)' ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", 'COTH(0)' ); oParser = new parserFormula( 'COTH(1000000000)', "A1", ws ); ok( oParser.parse(), 'COTH(1000000000)' ); strictEqual( oParser.calculate().getValue(), 1, 'COTH(1000000000)' ); oParser = new parserFormula( 'COTH(-1000000000)', "A1", ws ); ok( oParser.parse(), 'COTH(-1000000000)' ); strictEqual( oParser.calculate().getValue(), -1, 'COTH(-1000000000)' ); oParser = new parserFormula( 'COTH(test)', "A1", ws ); ok( oParser.parse(), 'COTH(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'COTH(test)' ); oParser = new parserFormula( 'COTH("test")', "A1", ws ); ok( oParser.parse(), 'COTH("test")' ); strictEqual( oParser.calculate().getValue(), "#VALUE!", 'COTH("test")' ); testArrayFormula("COTH"); } ); test( "Test: \"CSC\"", function () { oParser = new parserFormula( 'CSC(15)', "A1", ws ); ok( oParser.parse(), 'CSC(15)' ); strictEqual( oParser.calculate().getValue().toFixed(3) - 0, 1.538, 'CSC(15)' ); oParser = new parserFormula( 'CSC(0)', "A1", ws ); ok( oParser.parse(), 'CSC(0)' ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", 'CSC(0)' ); oParser = new parserFormula( 'CSC(1000000000)', "A1", ws ); ok( oParser.parse(), 'CSC(1000000000)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'CSC(1000000000)' ); oParser = new parserFormula( 'CSC(-1000000000)', "A1", ws ); ok( oParser.parse(), 'CSC(-1000000000)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'CSC(-1000000000)' ); oParser = new parserFormula( 'CSC(test)', "A1", ws ); ok( oParser.parse(), 'CSC(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'CSC(test)' ); oParser = new parserFormula( 'CSC("test")', "A1", ws ); ok( oParser.parse(), 'CSC("test")' ); strictEqual( oParser.calculate().getValue(), "#VALUE!", 'CSC("test")' ); testArrayFormula("CSC"); } ); test( "Test: \"CSCH\"", function () { oParser = new parserFormula( 'CSCH(1.5)', "A1", ws ); ok( oParser.parse(), 'CSCH(1.5)' ); strictEqual( oParser.calculate().getValue().toFixed(4) - 0, 0.4696, 'CSCH(1.5)' ); oParser = new parserFormula( 'CSCH(0)', "A1", ws ); ok( oParser.parse(), 'CSCH(0)' ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", 'CSCH(0)' ); oParser = new parserFormula( 'CSCH(1000000000)', "A1", ws ); ok( oParser.parse(), 'CSCH(1000000000)' ); strictEqual( oParser.calculate().getValue(), 0, 'CSCH(1000000000)' ); oParser = new parserFormula( 'CSCH(-1000000000)', "A1", ws ); ok( oParser.parse(), 'CSCH(-1000000000)' ); strictEqual( oParser.calculate().getValue(), 0, 'CSCH(-1000000000)' ); oParser = new parserFormula( 'CSCH(test)', "A1", ws ); ok( oParser.parse(), 'CSCH(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'CSCH(test)' ); oParser = new parserFormula( 'CSCH("test")', "A1", ws ); ok( oParser.parse(), 'CSCH("test")' ); strictEqual( oParser.calculate().getValue(), "#VALUE!", 'CSCH("test")' ); testArrayFormula("CSCH"); } ); test( "Test: \"CLEAN\"", function () { ws.getRange2( "A202" ).setValue( '=CHAR(9)&"Monthly report"&CHAR(10)' ); oParser = new parserFormula( 'CLEAN(A202)', "A1", ws ); ok( oParser.parse()); strictEqual( oParser.calculate().getValue(), "Monthly report" ); testArrayFormula("CLEAN"); } ); test( "Test: \"DEGREES\"", function () { oParser = new parserFormula( 'DEGREES(PI())', "A1", ws ); ok( oParser.parse(), 'DEGREES(PI())' ); strictEqual( oParser.calculate().getValue(), 180, 'DEGREES(PI())' ); testArrayFormula("DEGREES"); } ); test( "Test: \"SEC\"", function () { oParser = new parserFormula( 'SEC(45)', "A1", ws ); ok( oParser.parse(), 'SEC(45)' ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 1.90359, 'SEC(45)' ); oParser = new parserFormula( 'SEC(30)', "A1", ws ); ok( oParser.parse(), 'SEC(30)' ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 6.48292, 'SEC(30)' ); oParser = new parserFormula( 'SEC(0)', "A1", ws ); ok( oParser.parse(), 'SEC(0)' ); strictEqual( oParser.calculate().getValue(), 1, 'SEC(0)' ); oParser = new parserFormula( 'SEC(1000000000)', "A1", ws ); ok( oParser.parse(), 'SEC(1000000000)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'SEC(1000000000)' ); oParser = new parserFormula( 'SEC(test)', "A1", ws ); ok( oParser.parse(), 'SEC(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'SEC(test)' ); oParser = new parserFormula( 'SEC("test")', "A1", ws ); ok( oParser.parse(), 'SEC("test")' ); strictEqual( oParser.calculate().getValue(), "#VALUE!", 'SEC("test")' ); testArrayFormula("SEC"); } ); test( "Test: \"SECH\"", function () { oParser = new parserFormula( 'SECH(5)', "A1", ws ); ok( oParser.parse(), 'SECH(5)' ); strictEqual( oParser.calculate().getValue().toFixed(3) - 0, 0.013, 'SECH(5)' ); oParser = new parserFormula( 'SECH(0)', "A1", ws ); ok( oParser.parse(), 'SECH(0)' ); strictEqual( oParser.calculate().getValue(), 1, 'SECH(0)' ); oParser = new parserFormula( 'SECH(1000000000)', "A1", ws ); ok( oParser.parse(), 'SECH(1000000000)' ); strictEqual( oParser.calculate().getValue(), 0, 'SECH(1000000000)' ); oParser = new parserFormula( 'SECH(test)', "A1", ws ); ok( oParser.parse(), 'SECH(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'SECH(test)' ); oParser = new parserFormula( 'SECH("test")', "A1", ws ); ok( oParser.parse(), 'SECH("test")' ); strictEqual( oParser.calculate().getValue(), "#VALUE!", 'SECH("test")' ); testArrayFormula("SECH"); } ); test( "Test: \"SECOND\"", function () { ws.getRange2( "A202" ).setValue( "12:45:03 PM" ); ws.getRange2( "A203" ).setValue( "4:48:18 PM" ); ws.getRange2( "A204" ).setValue( "4:48 PM" ); oParser = new parserFormula( "SECOND(A202)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "SECOND(A203)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 18 ); oParser = new parserFormula( "SECOND(A204)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); testArrayFormula2("SECOND",1,1); } ); test( "Test: \"FLOOR\"", function () { oParser = new parserFormula( 'FLOOR(3.7,2)', "A1", ws ); ok( oParser.parse(), 'FLOOR(3.7,2)' ); strictEqual( oParser.calculate().getValue(), 2, 'FLOOR(3.7,2)' ); oParser = new parserFormula( 'FLOOR(-2.5,-2)', "A1", ws ); ok( oParser.parse(), 'FLOOR(-2.5,-2)' ); strictEqual( oParser.calculate().getValue(), -2, 'FLOOR(-2.5,-2)' ); oParser = new parserFormula( 'FLOOR(2.5,-2)', "A1", ws ); ok( oParser.parse(), 'FLOOR(2.5,-2)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'FLOOR(2.5,-2)' ); oParser = new parserFormula( 'FLOOR(1.58,0.1)', "A1", ws ); ok( oParser.parse(), 'FLOOR(1.58,0.1)' ); strictEqual( oParser.calculate().getValue(), 1.5, 'FLOOR(1.58,0.1)' ); oParser = new parserFormula( 'FLOOR(0.234,0.01)', "A1", ws ); ok( oParser.parse(), 'FLOOR(0.234,0.01)' ); strictEqual( oParser.calculate().getValue(), 0.23, 'FLOOR(0.234,0.01)' ); testArrayFormula2("FLOOR", 2, 2); } ); test( "Test: \"FLOOR.PRECISE\"", function () { oParser = new parserFormula( 'FLOOR.PRECISE(-3.2, -1)', "A1", ws ); ok( oParser.parse(), 'FLOOR.PRECISE(-3.2, -1)' ); strictEqual( oParser.calculate().getValue(), -4, 'FLOOR.PRECISE(-3.2, -1)' ); oParser = new parserFormula( 'FLOOR.PRECISE(3.2, 1)', "A1", ws ); ok( oParser.parse(), 'FLOOR.PRECISE(3.2, 1)' ); strictEqual( oParser.calculate().getValue(), 3, 'FLOOR.PRECISE(3.2, 1)' ); oParser = new parserFormula( 'FLOOR.PRECISE(-3.2, 1)', "A1", ws ); ok( oParser.parse(), 'FLOOR.PRECISE(-3.2, 1)' ); strictEqual( oParser.calculate().getValue(), -4, 'FLOOR.PRECISE(-3.2, 1)' ); oParser = new parserFormula( 'FLOOR.PRECISE(3.2, -1)', "A1", ws ); ok( oParser.parse(), 'FLOOR.PRECISE(3.2, -1)' ); strictEqual( oParser.calculate().getValue(), 3, 'FLOOR.PRECISE(3.2, -1)' ); oParser = new parserFormula( 'FLOOR.PRECISE(3.2)', "A1", ws ); ok( oParser.parse(), 'FLOOR.PRECISE(3.2)' ); strictEqual( oParser.calculate().getValue(), 3, 'FLOOR.PRECISE(3.2)' ); oParser = new parserFormula( 'FLOOR.PRECISE(test)', "A1", ws ); ok( oParser.parse(), 'FLOOR.PRECISE(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'FLOOR.PRECISE(test)' ); testArrayFormula2("FLOOR.PRECISE", 1, 2); } ); test( "Test: \"FLOOR.MATH\"", function () { oParser = new parserFormula( 'FLOOR.MATH(24.3, 5)', "A1", ws ); ok( oParser.parse(), 'FLOOR.MATH(24.3, 5)' ); strictEqual( oParser.calculate().getValue(), 20, 'FLOOR.MATH(24.3, 5)' ); oParser = new parserFormula( 'FLOOR.MATH(6.7)', "A1", ws ); ok( oParser.parse(), 'FLOOR.MATH(6.7)' ); strictEqual( oParser.calculate().getValue(), 6, 'FLOOR.MATH(6.7)' ); oParser = new parserFormula( 'FLOOR.MATH(-8.1, 5)', "A1", ws ); ok( oParser.parse(), 'FLOOR.MATH(-8.1, 5)' ); strictEqual( oParser.calculate().getValue(), -10, 'FLOOR.MATH(-8.1, 5)' ); oParser = new parserFormula( 'FLOOR.MATH(-5.5, 2, -1)', "A1", ws ); ok( oParser.parse(), 'FLOOR.MATH(-5.5, 2, -1)' ); strictEqual( oParser.calculate().getValue(), -4, 'FLOOR.MATH(-5.5, 2, -1)' ); testArrayFormula2("FLOOR.MATH", 1, 3); } ); test( "Test: \"CEILING.MATH\"", function () { oParser = new parserFormula( 'CEILING.MATH(24.3, 5)', "A1", ws ); ok( oParser.parse(), 'CEILING.MATH(24.3, 5)' ); strictEqual( oParser.calculate().getValue(), 25, 'CEILING.MATH(24.3, 5)' ); oParser = new parserFormula( 'CEILING.MATH(6.7)', "A1", ws ); ok( oParser.parse(), 'CEILING.MATH(6.7)' ); strictEqual( oParser.calculate().getValue(), 7, 'CEILING.MATH(6.7)' ); oParser = new parserFormula( 'CEILING.MATH(-8.1, 2)', "A1", ws ); ok( oParser.parse(), 'CEILING.MATH(-8.1, 2)' ); strictEqual( oParser.calculate().getValue(), -8, 'CEILING.MATH(-8.1, 2)' ); oParser = new parserFormula( 'CEILING.MATH(-5.5, 2, -1)', "A1", ws ); ok( oParser.parse(), 'CEILING.MATH(-5.5, 2, -1)' ); strictEqual( oParser.calculate().getValue(), -6, 'CEILING.MATH(-5.5, 2, -1)' ); testArrayFormula2("CEILING.MATH", 1, 3); } ); test( "Test: \"CEILING.PRECISE\"", function () { oParser = new parserFormula( 'CEILING.PRECISE(4.3)', "A1", ws ); ok( oParser.parse(), 'CEILING.PRECISE(4.3)' ); strictEqual( oParser.calculate().getValue(), 5, 'CEILING.PRECISE(4.3)' ); oParser = new parserFormula( 'CEILING.PRECISE(-4.3)', "A1", ws ); ok( oParser.parse(), 'CEILING.PRECISE(-4.3)' ); strictEqual( oParser.calculate().getValue(), -4, 'CEILING.PRECISE(-4.3)' ); oParser = new parserFormula( 'CEILING.PRECISE(4.3, 2)', "A1", ws ); ok( oParser.parse(), 'CEILING.PRECISE(4.3, 2)' ); strictEqual( oParser.calculate().getValue(), 6, 'CEILING.PRECISE(4.3, 2)' ); oParser = new parserFormula( 'CEILING.PRECISE(4.3,-2)', "A1", ws ); ok( oParser.parse(), 'CEILING.PRECISE(4.3,-2)' ); strictEqual( oParser.calculate().getValue(), 6, 'CEILING.PRECISE(4.3,-2)' ); oParser = new parserFormula( 'CEILING.PRECISE(-4.3,2)', "A1", ws ); ok( oParser.parse(), 'CEILING.PRECISE(-4.3,2)' ); strictEqual( oParser.calculate().getValue(), -4, 'CEILING.PRECISE(-4.3,2)' ); oParser = new parserFormula( 'CEILING.PRECISE(-4.3,-2)', "A1", ws ); ok( oParser.parse(), 'CEILING.PRECISE(-4.3,-2)' ); strictEqual( oParser.calculate().getValue(), -4, 'CEILING.PRECISE(-4.3,-2)' ); oParser = new parserFormula( 'CEILING.PRECISE(test)', "A1", ws ); ok( oParser.parse(), 'CEILING.PRECISE(test)' ); strictEqual( oParser.calculate().getValue(), "#NAME?", 'CEILING.PRECISE(test)' ); testArrayFormula2("CEILING.PRECISE", 1, 2); } ); test( "Test: \"ISO.CEILING\"", function () { oParser = new parserFormula( 'ISO.CEILING(4.3)', "A1", ws ); ok( oParser.parse(), 'ISO.CEILING(4.3)' ); strictEqual( oParser.calculate().getValue(), 5, 'ISO.CEILING(4.3)' ); oParser = new parserFormula( 'ISO.CEILING(-4.3)', "A1", ws ); ok( oParser.parse(), 'ISO.CEILING(-4.3)' ); strictEqual( oParser.calculate().getValue(), -4, 'ISO.CEILING(-4.3)' ); oParser = new parserFormula( 'ISO.CEILING(4.3, 2)', "A1", ws ); ok( oParser.parse(), 'ISO.CEILING(4.3, 2)' ); strictEqual( oParser.calculate().getValue(), 6, 'ISO.CEILING(4.3, 2)' ); oParser = new parserFormula( 'ISO.CEILING(4.3,-2)', "A1", ws ); ok( oParser.parse(), 'ISO.CEILING(4.3,-2)' ); strictEqual( oParser.calculate().getValue(), 6, 'ISO.CEILING(4.3,-2)' ); oParser = new parserFormula( 'ISO.CEILING(-4.3,2)', "A1", ws ); ok( oParser.parse(), 'ISO.CEILING(-4.3,2)' ); strictEqual( oParser.calculate().getValue(), -4, 'ISO.CEILING(-4.3,2)' ); oParser = new parserFormula( 'ISO.CEILING(-4.3,-2)', "A1", ws ); ok( oParser.parse(), 'ISO.CEILING(-4.3,-2)' ); strictEqual( oParser.calculate().getValue(), -4, 'ISO.CEILING(-4.3,-2)' ); testArrayFormula2("ISO.CEILING", 1, 2); } ); test( "Test: \"ISBLANK\"", function () { ws.getRange2( "A202" ).setValue( "" ); ws.getRange2( "A203" ).setValue( "test" ); oParser = new parserFormula( 'ISBLANK(A202)', "A1", ws ); ok( oParser.parse(), 'ISBLANK(A202)' ); strictEqual( oParser.calculate().getValue(), "TRUE", 'ISBLANK(A202)' ); oParser = new parserFormula( 'ISBLANK(A203)', "A1", ws ); ok( oParser.parse(), 'ISBLANK(A203)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISBLANK(A203)' ); testArrayFormula2("ISBLANK", 1, 1); } ); test( "Test: \"ISERROR\"", function () { ws.getRange2( "A202" ).setValue( "" ); ws.getRange2( "A203" ).setValue( "#N/A" ); oParser = new parserFormula( 'ISERROR(A202)', "A1", ws ); ok( oParser.parse(), 'ISERROR(A202)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISERROR(A202)' ); oParser = new parserFormula( 'ISERROR(A203)', "A1", ws ); ok( oParser.parse(), 'ISERROR(A203)' ); strictEqual( oParser.calculate().getValue(), "TRUE", 'ISERROR(A203)' ); testArrayFormula2("ISERROR", 1, 1); } ); test( "Test: \"ISERR\"", function () { ws.getRange2( "A202" ).setValue( "" ); ws.getRange2( "A203" ).setValue( "#N/A" ); ws.getRange2( "A204" ).setValue( "#VALUE!" ); oParser = new parserFormula( 'ISERR(A202)', "A1", ws ); ok( oParser.parse(), 'ISERR(A202)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISERR(A202)' ); oParser = new parserFormula( 'ISERR(A203)', "A1", ws ); ok( oParser.parse(), 'ISERR(A203)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISERR(A203)' ); oParser = new parserFormula( 'ISERR(A203)', "A1", ws ); ok( oParser.parse(), 'ISERR(A203)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISERR(A203)' ); testArrayFormula2("ISERR", 1, 1); } ); test( "Test: \"ISEVEN\"", function () { oParser = new parserFormula( 'ISEVEN(-1)', "A1", ws ); ok( oParser.parse(), 'ISEVEN(-1)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISEVEN(-1)' ); oParser = new parserFormula( 'ISEVEN(2.5)', "A1", ws ); ok( oParser.parse(), 'ISEVEN(2.5)' ); strictEqual( oParser.calculate().getValue(), "TRUE", 'ISEVEN(2.5)' ); oParser = new parserFormula( 'ISEVEN(5)', "A1", ws ); ok( oParser.parse(), 'ISEVEN(5)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISEVEN(5)' ); oParser = new parserFormula( 'ISEVEN(0)', "A1", ws ); ok( oParser.parse(), 'ISEVEN(0)' ); strictEqual( oParser.calculate().getValue(), "TRUE", 'ISEVEN(0)' ); oParser = new parserFormula( 'ISEVEN(12/23/2011)', "A1", ws ); ok( oParser.parse(), 'ISEVEN(12/23/2011)' ); strictEqual( oParser.calculate().getValue(), "TRUE", 'ISEVEN(12/23/2011)' ); testArrayFormula2("ISEVEN", 1, 1, true); } ); test( "Test: \"ISLOGICAL\"", function () { oParser = new parserFormula( 'ISLOGICAL(TRUE)', "A1", ws ); ok( oParser.parse(), 'ISLOGICAL(TRUE)' ); strictEqual( oParser.calculate().getValue(), "TRUE", 'ISLOGICAL(TRUE)' ); oParser = new parserFormula( 'ISLOGICAL("TRUE")', "A1", ws ); ok( oParser.parse(), 'ISLOGICAL("TRUE")' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'ISLOGICAL("TRUE")' ); testArrayFormula2("ISLOGICAL", 1, 1); } ); test( "Test: \"CEILING\"", function () { oParser = new parserFormula( 'CEILING(2.5, 1)', "A1", ws ); ok( oParser.parse(), 'CEILING(2.5, 1)' ); strictEqual( oParser.calculate().getValue(), 3, 'CEILING(2.5, 1)' ); oParser = new parserFormula( 'CEILING(-2.5, -2)', "A1", ws ); ok( oParser.parse(), 'CEILING(-2.5, -2)' ); strictEqual( oParser.calculate().getValue(), -4, 'CEILING(-2.5, -2)' ); oParser = new parserFormula( 'CEILING(-2.5, 2)', "A1", ws ); ok( oParser.parse(), 'CEILING(-2.5, 2)' ); strictEqual( oParser.calculate().getValue(), -2, 'CEILING(-2.5, 2)' ); oParser = new parserFormula( 'CEILING(1.5, 0.1)', "A1", ws ); ok( oParser.parse(), 'CEILING(1.5, 0.1)' ); strictEqual( oParser.calculate().getValue(), 1.5, 'CEILING(1.5, 0.1)' ); oParser = new parserFormula( 'CEILING(0.234, 0.01)', "A1", ws ); ok( oParser.parse(), 'CEILING(0.234, 0.01)' ); strictEqual( oParser.calculate().getValue(), 0.24, 'CEILING(0.234, 0.01)' ); testArrayFormula2("CEILING", 2, 2); } ); test( "Test: \"ECMA.CEILING\"", function () { oParser = new parserFormula( 'ECMA.CEILING(2.5, 1)', "A1", ws ); ok( oParser.parse(), 'ECMA.CEILING(2.5, 1)' ); strictEqual( oParser.calculate().getValue(), 3, 'ECMA.CEILING(2.5, 1)' ); oParser = new parserFormula( 'ECMA.CEILING(-2.5, -2)', "A1", ws ); ok( oParser.parse(), 'ECMA.CEILING(-2.5, -2)' ); strictEqual( oParser.calculate().getValue(), -4, 'ECMA.CEILING(-2.5, -2)' ); oParser = new parserFormula( 'ECMA.CEILING(-2.5, 2)', "A1", ws ); ok( oParser.parse(), 'ECMA.CEILING(-2.5, 2)' ); strictEqual( oParser.calculate().getValue(), -2, 'ECMA.CEILING(-2.5, 2)' ); oParser = new parserFormula( 'ECMA.CEILING(1.5, 0.1)', "A1", ws ); ok( oParser.parse(), 'ECMA.CEILING(1.5, 0.1)' ); strictEqual( oParser.calculate().getValue(), 1.5, 'ECMA.CEILING(1.5, 0.1)' ); oParser = new parserFormula( 'ECMA.CEILING(0.234, 0.01)', "A1", ws ); ok( oParser.parse(), 'ECMA.CEILING(0.234, 0.01)' ); strictEqual( oParser.calculate().getValue(), 0.24, 'ECMA.CEILING(0.234, 0.01)' ); } ); test( "Test: \"COMBINA\"", function () { oParser = new parserFormula( 'COMBINA(4,3)', "A1", ws ); ok( oParser.parse(), 'COMBINA(4,3)' ); strictEqual( oParser.calculate().getValue(), 20, 'COMBINA(4,3)' ); oParser = new parserFormula( 'COMBINA(10,3)', "A1", ws ); ok( oParser.parse(), 'COMBINA(10,3)' ); strictEqual( oParser.calculate().getValue(), 220, 'COMBINA(10,3)' ); oParser = new parserFormula( 'COMBINA(3,10)', "A1", ws ); ok( oParser.parse(), 'COMBINA(3,10)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'COMBINA(10,3)' ); oParser = new parserFormula( 'COMBINA(10,-3)', "A1", ws ); ok( oParser.parse(), 'COMBINA(10,-3)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'COMBINA(10,-3)' ); testArrayFormula2("COMBINA", 2, 2) } ); test( "Test: \"DECIMAL\"", function () { oParser = new parserFormula( 'DECIMAL("FF",16)', "A1", ws ); ok( oParser.parse(), 'DECIMAL("FF",16)' ); strictEqual( oParser.calculate().getValue(), 255, 'DECIMAL("FF",16)' ); oParser = new parserFormula( 'DECIMAL(111,2)', "A1", ws ); ok( oParser.parse(), 'DECIMAL(111,2)' ); strictEqual( oParser.calculate().getValue(), 7, 'DECIMAL(111,2)' ); oParser = new parserFormula( 'DECIMAL("zap",36)', "A1", ws ); ok( oParser.parse(), 'DECIMAL("zap",36)' ); strictEqual( oParser.calculate().getValue(), 45745, 'DECIMAL("zap",36)' ); oParser = new parserFormula( 'DECIMAL("00FF",16)', "A1", ws ); ok( oParser.parse(), 'DECIMAL("00FF",16)' ); strictEqual( oParser.calculate().getValue(), 255, 'DECIMAL("00FF",16)' ); oParser = new parserFormula( 'DECIMAL("101b",2)', "A1", ws ); ok( oParser.parse(), 'DECIMAL("101b",2)' ); strictEqual( oParser.calculate().getValue(), 5, 'DECIMAL("101b",2)' ); testArrayFormula2("DECIMAL", 2, 2); } ); test( "Test: \"BASE\"", function () { oParser = new parserFormula( 'BASE(7,2)', "A1", ws ); ok( oParser.parse(), 'BASE(7,2)' ); strictEqual( oParser.calculate().getValue(), "111", 'BASE(7,2)' ); oParser = new parserFormula( 'BASE(100,16)', "A1", ws ); ok( oParser.parse(), 'BASE(100,16)' ); strictEqual( oParser.calculate().getValue(), "64", 'BASE(100,16)' ); oParser = new parserFormula( 'BASE(15,2,10)', "A1", ws ); ok( oParser.parse(), 'BASE(15,2,10)' ); strictEqual( oParser.calculate().getValue(), "0000001111", 'BASE(15,2,10)' ); testArrayFormula2("BASE", 2, 3); } ); test( "Test: \"ARABIC('LVII')\"", function () { oParser = new parserFormula( 'ARABIC("LVII")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 57 ); } ); test( "Test: \"TDIST\"", function () { oParser = new parserFormula( "TDIST(60,1,2)", "A1", ws ); ok( oParser.parse(), "TDIST(60,1,2)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.010609347, "TDIST(60,1,2)" ); oParser = new parserFormula( "TDIST(8,3,1)", "A1", ws ); ok( oParser.parse(), "TDIST(8,3,1)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.002038289, "TDIST(8,3,1)" ); ws.getRange2( "A2" ).setValue( "1.959999998" ); ws.getRange2( "A3" ).setValue( "60" ); oParser = new parserFormula( "TDIST(A2,A3,2)", "A1", ws ); ok( oParser.parse(), "TDIST(A2,A3,2)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.054644930, "TDIST(A2,A3,2)" ); oParser = new parserFormula( "TDIST(A2,A3,1)", "A1", ws ); ok( oParser.parse(), "TDIST(A2,A3,1)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.027322465, "TDIST(A2,A3,1)" ); testArrayFormula2("TDIST", 3, 3); } ); test( "Test: \"T.DIST\"", function () { oParser = new parserFormula( "T.DIST(60,1,TRUE)", "A1", ws ); ok( oParser.parse(), "T.DIST(60,1,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.99469533, "T.DIST(60,1,TRUE)" ); oParser = new parserFormula( "T.DIST(8,3,FALSE)", "A1", ws ); ok( oParser.parse(), "T.DIST(8,3,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.00073691, "T.DIST(8,3,FALSE)" ); testArrayFormula2("T.DIST", 3, 3); } ); test( "Test: \"T.DIST.2T\"", function () { ws.getRange2( "A2" ).setValue( "1.959999998" ); ws.getRange2( "A3" ).setValue( "60" ); oParser = new parserFormula( "T.DIST.2T(A2,A3)", "A1", ws ); ok( oParser.parse(), "T.DIST.2T(A2,A3)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.054644930, "T.DIST.2T(A2,A3)" ); testArrayFormula2("T.DIST.2T", 2, 2) } ); test( "Test: \"T.DIST.RT\"", function () { ws.getRange2( "A2" ).setValue( "1.959999998" ); ws.getRange2( "A3" ).setValue( "60" ); oParser = new parserFormula( "T.DIST.RT(A2,A3)", "A1", ws ); ok( oParser.parse(), "T.DIST.RT(A2,A3)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.027322, "T.DIST.RT(A2,A3)" ); testArrayFormula2("T.DIST.RT", 2, 2); } ); test( "Test: \"TTEST\"", function () { ws.getRange2( "A2" ).setValue( "3" ); ws.getRange2( "A3" ).setValue( "4" ); ws.getRange2( "A4" ).setValue( "5" ); ws.getRange2( "A5" ).setValue( "8" ); ws.getRange2( "A6" ).setValue( "9" ); ws.getRange2( "A7" ).setValue( "1" ); ws.getRange2( "A8" ).setValue( "2" ); ws.getRange2( "A9" ).setValue( "4" ); ws.getRange2( "A10" ).setValue( "5" ); ws.getRange2( "B2" ).setValue( "6" ); ws.getRange2( "B3" ).setValue( "19" ); ws.getRange2( "B4" ).setValue( "3" ); ws.getRange2( "B5" ).setValue( "2" ); ws.getRange2( "B6" ).setValue( "14" ); ws.getRange2( "B7" ).setValue( "4" ); ws.getRange2( "B8" ).setValue( "5" ); ws.getRange2( "B9" ).setValue( "17" ); ws.getRange2( "B10" ).setValue( "1" ); oParser = new parserFormula( "TTEST(A2:A10,B2:B10,2,1)", "A1", ws ); ok( oParser.parse(), "TTEST(A2:A10,B2:B10,2,1)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.196016, "TTEST(A2:A10,B2:B10,2,1)" ); //TODO нужна другая функция для тестирования //testArrayFormula2("TTEST", 4, 4, null, true); } ); test( "Test: \"T.TEST\"", function () { ws.getRange2( "A2" ).setValue( "3" ); ws.getRange2( "A3" ).setValue( "4" ); ws.getRange2( "A4" ).setValue( "5" ); ws.getRange2( "A5" ).setValue( "8" ); ws.getRange2( "A6" ).setValue( "9" ); ws.getRange2( "A7" ).setValue( "1" ); ws.getRange2( "A8" ).setValue( "2" ); ws.getRange2( "A9" ).setValue( "4" ); ws.getRange2( "A10" ).setValue( "5" ); ws.getRange2( "B2" ).setValue( "6" ); ws.getRange2( "B3" ).setValue( "19" ); ws.getRange2( "B4" ).setValue( "3" ); ws.getRange2( "B5" ).setValue( "2" ); ws.getRange2( "B6" ).setValue( "14" ); ws.getRange2( "B7" ).setValue( "4" ); ws.getRange2( "B8" ).setValue( "5" ); ws.getRange2( "B9" ).setValue( "17" ); ws.getRange2( "B10" ).setValue( "1" ); oParser = new parserFormula( "T.TEST(A2:A10,B2:B10,2,1)", "A1", ws ); ok( oParser.parse(), "T.TEST(A2:A10,B2:B10,2,1)" ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 0.19602, "T.TEST(A2:A10,B2:B10,2,1)" ); } ); test( "Test: \"ZTEST\"", function () { ws.getRange2( "A2" ).setValue( "3" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "7" ); ws.getRange2( "A5" ).setValue( "8" ); ws.getRange2( "A6" ).setValue( "6" ); ws.getRange2( "A7" ).setValue( "5" ); ws.getRange2( "A8" ).setValue( "4" ); ws.getRange2( "A9" ).setValue( "2" ); ws.getRange2( "A10" ).setValue( "1" ); ws.getRange2( "A11" ).setValue( "9" ); oParser = new parserFormula( "ZTEST(A2:A11,4)", "A1", ws ); ok( oParser.parse(), "ZTEST(A2:A11,4)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.090574, "ZTEST(A2:A11,4)" ); oParser = new parserFormula( "2 * MIN(ZTEST(A2:A11,4), 1 - ZTEST(A2:A11,4))", "A1", ws ); ok( oParser.parse(), "2 * MIN(ZTEST(A2:A11,4), 1 - ZTEST(A2:A11,4))" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.181148, "2 * MIN(ZTEST(A2:A11,4), 1 - ZTEST(A2:A11,4))" ); oParser = new parserFormula( "ZTEST(A2:A11,6)", "A1", ws ); ok( oParser.parse(), "ZTEST(A2:A11,6)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.863043, "ZTEST(A2:A11,6)" ); oParser = new parserFormula( "2 * MIN(ZTEST(A2:A11,6), 1 - ZTEST(A2:A11,6))", "A1", ws ); ok( oParser.parse(), "2 * MIN(ZTEST(A2:A11,6), 1 - ZTEST(A2:A11,6))" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.273913, "2 * MIN(ZTEST(A2:A11,6), 1 - ZTEST(A2:A11,6))" ); //TODO нужна другая функция для тестирования //testArrayFormula2("Z.TEST", 2, 3, null, true); } ); test( "Test: \"Z.TEST\"", function () { ws.getRange2( "A2" ).setValue( "3" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "7" ); ws.getRange2( "A5" ).setValue( "8" ); ws.getRange2( "A6" ).setValue( "6" ); ws.getRange2( "A7" ).setValue( "5" ); ws.getRange2( "A8" ).setValue( "4" ); ws.getRange2( "A9" ).setValue( "2" ); ws.getRange2( "A10" ).setValue( "1" ); ws.getRange2( "A11" ).setValue( "9" ); oParser = new parserFormula( "Z.TEST(A2:A11,4)", "A1", ws ); ok( oParser.parse(), "Z.TEST(A2:A11,4)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.090574, "Z.TEST(A2:A11,4)" ); oParser = new parserFormula( "2 * MIN(Z.TEST(A2:A11,4), 1 - Z.TEST(A2:A11,4))", "A1", ws ); ok( oParser.parse(), "2 * MIN(Z.TEST(A2:A11,4), 1 - Z.TEST(A2:A11,4))" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.181148, "2 * MIN(Z.TEST(A2:A11,4), 1 - Z.TEST(A2:A11,4))" ); oParser = new parserFormula( "Z.TEST(A2:A11,6)", "A1", ws ); ok( oParser.parse(), "Z.TEST(A2:A11,6)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.863043, "Z.TEST(A2:A11,6)" ); oParser = new parserFormula( "2 * MIN(Z.TEST(A2:A11,6), 1 - Z.TEST(A2:A11,6))", "A1", ws ); ok( oParser.parse(), "2 * MIN(Z.TEST(A2:A11,6), 1 - Z.TEST(A2:A11,6))" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.273913, "2 * MIN(Z.TEST(A2:A11,6), 1 - Z.TEST(A2:A11,6))" ); //TODO нужна другая функция для тестирования //testArrayFormula2("Z.TEST", 2, 3, null, true); } ); test( "Test: \"F.DIST\"", function () { ws.getRange2( "A2" ).setValue( "15.2069" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "4" ); oParser = new parserFormula( "F.DIST(A2,A3,A4,TRUE)", "A1", ws ); ok( oParser.parse(), "F.DIST(A2,A3,A4,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.99, "F.DIST(A2,A3,A4,TRUE)" ); oParser = new parserFormula( "F.DIST(A2,A3,A4,FALSE)", "A1", ws ); ok( oParser.parse(), "F.DIST(A2,A3,A4,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0012238, "F.DIST(A2,A3,A4,FALSE)" ); testArrayFormula2("F.DIST", 4, 4); } ); test( "Test: \"F.DIST.RT\"", function () { ws.getRange2( "A2" ).setValue( "15.2069" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "4" ); oParser = new parserFormula( "F.DIST.RT(A2,A3,A4)", "A1", ws ); ok( oParser.parse(), "F.DIST.RT(A2,A3,A4)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.01, "F.DIST.RT(A2,A3,A4)" ); testArrayFormula2("F.DIST.RT", 3, 3); } ); test( "Test: \"FDIST\"", function () { ws.getRange2( "A2" ).setValue( "15.2069" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "4" ); oParser = new parserFormula( "FDIST(A2,A3,A4)", "A1", ws ); ok( oParser.parse(), "FDIST(A2,A3,A4)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.01, "FDIST(A2,A3,A4)" ); } ); test( "Test: \"FINV\"", function () { ws.getRange2( "A2" ).setValue( "0.01" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "4" ); oParser = new parserFormula( "FINV(A2,A3,A4)", "A1", ws ); ok( oParser.parse(), "FINV(A2,A3,A4)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 15.206865, "FINV(A2,A3,A4)" ); testArrayFormula2("FINV", 3, 3); } ); test( "Test: \"F.INV\"", function () { ws.getRange2( "A2" ).setValue( "0.01" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "4" ); oParser = new parserFormula( "F.INV(A2,A3,A4)", "A1", ws ); ok( oParser.parse(), "F.INV(A2,A3,A4)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.10930991, "F.INV(A2,A3,A4)" ); testArrayFormula2("F.INV", 3, 3); } ); test( "Test: \"F.INV.RT\"", function () { ws.getRange2( "A2" ).setValue( "0.01" ); ws.getRange2( "A3" ).setValue( "6" ); ws.getRange2( "A4" ).setValue( "4" ); oParser = new parserFormula( "F.INV.RT(A2,A3,A4)", "A1", ws ); ok( oParser.parse(), "F.INV.RT(A2,A3,A4)" ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 15.20686, "F.INV.RT(A2,A3,A4)" ); } ); function fTestFormulaTest(){ ws.getRange2( "A2" ).setValue( "6" ); ws.getRange2( "A3" ).setValue( "7" ); ws.getRange2( "A4" ).setValue( "9" ); ws.getRange2( "A5" ).setValue( "15" ); ws.getRange2( "A6" ).setValue( "21" ); ws.getRange2( "B2" ).setValue( "20" ); ws.getRange2( "B3" ).setValue( "28" ); ws.getRange2( "B4" ).setValue( "31" ); ws.getRange2( "B5" ).setValue( "38" ); ws.getRange2( "B6" ).setValue( "40" ); oParser = new parserFormula( "FTEST(A2:A6,B2:B6)", "A1", ws ); ok( oParser.parse(), "FTEST(A2:A6,B2:B6)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.64831785, "FTEST(A2:A6,B2:B6)" ); oParser = new parserFormula( "FTEST(A2,B2:B6)", "A1", ws ); ok( oParser.parse(), "FTEST(A2,B2:B6)" ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", "FTEST(A2,B2:B6)" ); oParser = new parserFormula( "FTEST(1,B2:B6)", "A1", ws ); ok( oParser.parse(), "FTEST(1,B2:B6)" ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", "FTEST(1,B2:B6)" ); oParser = new parserFormula( "FTEST({1,2,3},{2,3,4,5})", "A1", ws ); ok( oParser.parse(), "FTEST({1,2,3},{2,3,4,5})" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.792636779, "FTEST({1,2,3},{2,3,4,5})" ); oParser = new parserFormula( "FTEST({1,\"test\",\"test\"},{2,3,4,5})", "A1", ws ); ok( oParser.parse(), "FTEST({1,\"test\",\"test\"},{2,3,4,5})" ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", "FTEST({1,\"test\",\"test\"},{2,3,4,5})" ); } test( "Test: \"FTEST\"", function () { fTestFormulaTest(); testArrayFormula2("FTEST", 2, 2, null, true); } ); test( "Test: \"F.TEST\"", function () { fTestFormulaTest(); testArrayFormula2("F.TEST", 2, 2, null, true); } ); test( "Test: \"T.INV\"", function () { oParser = new parserFormula( "T.INV(0.75,2)", "A1", ws ); ok( oParser.parse(), "T.INV(0.75,2)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.8164966, "T.INV(0.75,2)" ); testArrayFormula2("T.INV", 2, 2); } ); test( "Test: \"T.INV.2T\"", function () { ws.getRange2( "A2" ).setValue( "0.546449" ); ws.getRange2( "A3" ).setValue( "60" ); oParser = new parserFormula( "T.INV.2T(A2,A3)", "A1", ws ); ok( oParser.parse(), "T.INV.2T(A2,A3)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.606533, "T.INV.2T(A2,A3)" ); testArrayFormula2("T.INV.2T", 2, 2); } ); test( "Test: \"RANK\"", function () { ws.getRange2( "A2" ).setValue( "7" ); ws.getRange2( "A3" ).setValue( "3.5" ); ws.getRange2( "A4" ).setValue( "3.5" ); ws.getRange2( "A5" ).setValue( "1" ); ws.getRange2( "A6" ).setValue( "2" ); oParser = new parserFormula( "RANK(A3,A2:A6,1)", "A1", ws ); ok( oParser.parse(), "RANK(A3,A2:A6,1)" ); strictEqual( oParser.calculate().getValue(), 3, "RANK(A3,A2:A6,1)" ); oParser = new parserFormula( "RANK(A2,A2:A6,1)", "A1", ws ); ok( oParser.parse(), "RANK(A2,A2:A6,1)" ); strictEqual( oParser.calculate().getValue(), 5, "RANK(A2,A2:A6,1)" ); } ); test( "Test: \"RANK.EQ\"", function () { ws.getRange2( "A2" ).setValue( "7" ); ws.getRange2( "A3" ).setValue( "3.5" ); ws.getRange2( "A4" ).setValue( "3.5" ); ws.getRange2( "A5" ).setValue( "1" ); ws.getRange2( "A6" ).setValue( "2" ); oParser = new parserFormula( "RANK.EQ(A2,A2:A6,1)", "A1", ws ); ok( oParser.parse(), "RANK.EQ(A2,A2:A6,1)" ); strictEqual( oParser.calculate().getValue(), 5, "RANK.EQ(A2,A2:A6,1)" ); oParser = new parserFormula( "RANK.EQ(A6,A2:A6)", "A1", ws ); ok( oParser.parse(), "RANK.EQ(A6,A2:A6)" ); strictEqual( oParser.calculate().getValue(), 4, "RANK.EQ(A6,A2:A6)" ); oParser = new parserFormula( "RANK.EQ(A3,A2:A6,1)", "A1", ws ); ok( oParser.parse(), "RANK.EQ(A3,A2:A6,1)" ); strictEqual( oParser.calculate().getValue(), 3, "RANK.EQ(A3,A2:A6,1)" ); } ); test( "Test: \"RANK.AVG\"", function () { ws.getRange2( "A2" ).setValue( "89" ); ws.getRange2( "A3" ).setValue( "88" ); ws.getRange2( "A4" ).setValue( "92" ); ws.getRange2( "A5" ).setValue( "101" ); ws.getRange2( "A6" ).setValue( "94" ); ws.getRange2( "A7" ).setValue( "97" ); ws.getRange2( "A8" ).setValue( "95" ); oParser = new parserFormula( "RANK.AVG(94,A2:A8)", "A1", ws ); ok( oParser.parse(), "RANK.AVG(94,A2:A8)" ); strictEqual( oParser.calculate().getValue(), 4, "RANK.AVG(94,A2:A8)" ); } ); test( "Test: \"RADIANS\"", function () { oParser = new parserFormula( "RADIANS(270)", "A1", ws ); ok( oParser.parse(), "RADIANS(270)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 4.712389 ); testArrayFormula("RADIANS"); } ); test( "Test: \"LOG\"", function () { oParser = new parserFormula( "LOG(10)", "A1", ws ); ok( oParser.parse(), "LOG(10)" ); strictEqual( oParser.calculate().getValue(), 1, "LOG(10)" ); oParser = new parserFormula( "LOG(8,2)", "A1", ws ); ok( oParser.parse(), "LOG(8,2)" ); strictEqual( oParser.calculate().getValue(), 3, "LOG(8,2)" ); oParser = new parserFormula( "LOG(86, 2.7182818)", "A1", ws ); ok( oParser.parse(), "LOG(86, 2.7182818)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 4.4543473, "LOG(86, 2.7182818)" ); oParser = new parserFormula( "LOG(8,1)", "A1", ws ); ok( oParser.parse(), "LOG(8,1)" ); strictEqual( oParser.calculate().getValue(), "#DIV/0!", "LOG(8,1)" ); testArrayFormula("LOG", 1, 2); } ); test( "Test: \"LOGNORM.DIST\"", function () { ws.getRange2( "A2" ).setValue( "4" ); ws.getRange2( "A3" ).setValue( "3.5" ); ws.getRange2( "A4" ).setValue( "1.2" ); oParser = new parserFormula( "LOGNORM.DIST(A2,A3,A4,TRUE)", "A1", ws ); ok( oParser.parse(), "LOGNORM.DIST(A2,A3,A4,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0390836, "LOGNORM.DIST(A2,A3,A4,TRUE)" ); oParser = new parserFormula( "LOGNORM.DIST(A2,A3,A4,FALSE)", "A1", ws ); ok( oParser.parse(), "LOGNORM.DIST(A2,A3,A4,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0176176, "LOGNORM.DIST(A2,A3,A4,FALSE)" ); testArrayFormula2("LOGNORM.DIST", 4, 4); } ); test( "Test: \"LOGNORM.INV\"", function () { ws.getRange2( "A2" ).setValue( "0.039084" ); ws.getRange2( "A3" ).setValue( "3.5" ); ws.getRange2( "A4" ).setValue( "1.2" ); oParser = new parserFormula( "LOGNORM.INV(A2, A3, A4)", "A1", ws ); ok( oParser.parse(), "LOGNORM.INV(A2, A3, A4)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 4.0000252, "LOGNORM.INV(A2, A3, A4)" ); testArrayFormula2("LOGNORM.INV", 3, 3); } ); test( "Test: \"LOGNORMDIST\"", function () { ws.getRange2( "A2" ).setValue( "4" ); ws.getRange2( "A3" ).setValue( "3.5" ); ws.getRange2( "A4" ).setValue( "1.2" ); oParser = new parserFormula( "LOGNORMDIST(A2, A3, A4)", "A1", ws ); ok( oParser.parse(), "LOGNORMDIST(A2, A3, A4)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0390836, "LOGNORMDIST(A2, A3, A4)" ); testArrayFormula2("LOGNORMDIST", 3, 3); } ); test( "Test: \"LOWER\"", function () { ws.getRange2( "A2" ).setValue( "E. E. Cummings" ); ws.getRange2( "A3" ).setValue( "Apt. 2B" ); oParser = new parserFormula( "LOWER(A2)", "A1", ws ); ok( oParser.parse(), "LOWER(A2)" ); strictEqual( oParser.calculate().getValue(), "e. e. cummings", "LOWER(A2)" ); oParser = new parserFormula( "LOWER(A3)", "A1", ws ); ok( oParser.parse(), "LOWER(A3)" ); strictEqual( oParser.calculate().getValue(), "apt. 2b", "LOWER(A3)" ); testArrayFormula2("LOWER", 1, 1); } ); test( "Test: \"EXPON.DIST\"", function () { ws.getRange2( "A2" ).setValue( "0.2" ); ws.getRange2( "A3" ).setValue( "10" ); oParser = new parserFormula( "EXPON.DIST(A2,A3,TRUE)", "A1", ws ); ok( oParser.parse(), "EXPON.DIST(A2,A3,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.86466472, "EXPON.DIST(A2,A3,TRUE)" ); oParser = new parserFormula( "EXPON.DIST(0.2,10,FALSE)", "A1", ws ); ok( oParser.parse(), "EXPON.DIST(0.2,10,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 1.35335283, "EXPON.DIST(0.2,10,FALSE)" ); testArrayFormula2("EXPON.DIST", 3, 3); } ); test( "Test: \"GAMMA.DIST\"", function () { ws.getRange2( "A2" ).setValue( "10.00001131" ); ws.getRange2( "A3" ).setValue( "9" ); ws.getRange2( "A4" ).setValue( "2" ); oParser = new parserFormula( "GAMMA.DIST(A2,A3,A4,FALSE)", "A1", ws ); ok( oParser.parse(), "GAMMA.DIST(A2,A3,A4,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.032639, "GAMMA.DIST(A2,A3,A4,FALSE)" ); oParser = new parserFormula( "GAMMA.DIST(A2,A3,A4,TRUE)", "A1", ws ); ok( oParser.parse(), "GAMMA.DIST(A2,A3,A4,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.068094, "GAMMA.DIST(A2,A3,A4,TRUE)" ); testArrayFormula2("GAMMA.DIST", 4, 4); } ); test( "Test: \"GAMMADIST\"", function () { ws.getRange2( "A2" ).setValue( "10.00001131" ); ws.getRange2( "A3" ).setValue( "9" ); ws.getRange2( "A4" ).setValue( "2" ); oParser = new parserFormula( "GAMMADIST(A2,A3,A4,FALSE)", "A1", ws ); ok( oParser.parse(), "GAMMADIST(A2,A3,A4,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.032639, "GAMMADIST(A2,A3,A4,FALSE)" ); oParser = new parserFormula( "GAMMADIST(A2,A3,A4,TRUE)", "A1", ws ); ok( oParser.parse(), "GAMMADIST(A2,A3,A4,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.068094, "GAMMADIST(A2,A3,A4,TRUE)" ); } ); test( "Test: \"GAMMADIST\"", function () { oParser = new parserFormula( "GAMMADIST(A2,A3,A4,FALSE)", "A1", ws ); ok( oParser.parse(), "GAMMADIST(A2,A3,A4,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.032639, "GAMMADIST(A2,A3,A4,FALSE)" ); oParser = new parserFormula( "GAMMADIST(A2,A3,A4,TRUE)", "A1", ws ); ok( oParser.parse(), "GAMMADIST(A2,A3,A4,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.068094, "GAMMADIST(A2,A3,A4,TRUE)" ); } ); test( "Test: \"GAMMA\"", function () { oParser = new parserFormula( "GAMMA(2.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(3), "1.329" ); oParser = new parserFormula( "GAMMA(-3.75)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(3), "0.268" ); oParser = new parserFormula( "GAMMA(0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "GAMMA(-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("GAMMA", 1, 1); } ); test( "Test: \"CHITEST\"", function () { ws.getRange2( "A2" ).setValue( "58" ); ws.getRange2( "A3" ).setValue( "11" ); ws.getRange2( "A4" ).setValue( "10" ); ws.getRange2( "A5" ).setValue( "x" ); ws.getRange2( "A6" ).setValue( "45.35" ); ws.getRange2( "A7" ).setValue( "17.56" ); ws.getRange2( "A8" ).setValue( "16.09" ); ws.getRange2( "B2" ).setValue( "35" ); ws.getRange2( "B3" ).setValue( "25" ); ws.getRange2( "B4" ).setValue( "23" ); ws.getRange2( "B5" ).setValue( "x" ); ws.getRange2( "B6" ).setValue( "47.65" ); ws.getRange2( "B7" ).setValue( "18.44" ); ws.getRange2( "B8" ).setValue( "16.91" ); oParser = new parserFormula( "CHITEST(A2:B4,A6:B8)", "A1", ws ); ok( oParser.parse(), "CHITEST(A2:B4,A6:B8)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0003082, "CHITEST(A2:B4,A6:B8)" ); testArrayFormula2("CHITEST", 2, 2, null, true); } ); test( "Test: \"CHISQ.TEST\"", function () { ws.getRange2( "A2" ).setValue( "58" ); ws.getRange2( "A3" ).setValue( "11" ); ws.getRange2( "A4" ).setValue( "10" ); ws.getRange2( "A5" ).setValue( "x" ); ws.getRange2( "A6" ).setValue( "45.35" ); ws.getRange2( "A7" ).setValue( "17.56" ); ws.getRange2( "A8" ).setValue( "16.09" ); ws.getRange2( "B2" ).setValue( "35" ); ws.getRange2( "B3" ).setValue( "25" ); ws.getRange2( "B4" ).setValue( "23" ); ws.getRange2( "B5" ).setValue( "x" ); ws.getRange2( "B6" ).setValue( "47.65" ); ws.getRange2( "B7" ).setValue( "18.44" ); ws.getRange2( "B8" ).setValue( "16.91" ); oParser = new parserFormula( "CHISQ.TEST(A2:B4,A6:B8)", "A1", ws ); ok( oParser.parse(), "CHISQ.TEST(A2:B4,A6:B8)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0003082, "CHISQ.TEST(A2:B4,A6:B8)" ); } ); test( "Test: \"CHITEST\"", function () { ws.getRange2( "A2" ).setValue( "18.307" ); ws.getRange2( "A3" ).setValue( "10" ); oParser = new parserFormula( "CHIDIST(A2,A3)", "A1", ws ); ok( oParser.parse(), "CHIDIST(A2,A3)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0500006, "CHIDIST(A2,A3)" ); testArrayFormula2("CHIDIST", 2, 2); } ); test( "Test: \"GAUSS\"", function () { oParser = new parserFormula( "GAUSS(2)", "A1", ws ); ok( oParser.parse(), "GAUSS(2)" ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 0.47725, "GAUSS(2)" ); testArrayFormula2("GAUSS", 1, 1); } ); test( "Test: \"CHISQ.DIST.RT\"", function () { ws.getRange2( "A2" ).setValue( "18.307" ); ws.getRange2( "A3" ).setValue( "10" ); oParser = new parserFormula( "CHISQ.DIST.RT(A2,A3)", "A1", ws ); ok( oParser.parse(), "CHISQ.DIST.RT(A2,A3)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0500006, "CHISQ.DIST.RT(A2,A3)" ); testArrayFormula2("CHISQ.INV.RT", 2, 2); } ); test( "Test: \"CHISQ.INV\"", function () { oParser = new parserFormula( "CHISQ.INV(0.93,1)", "A1", ws ); ok( oParser.parse(), "CHISQ.INV(0.93,1)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 3.283020287, "CHISQ.INV(0.93,1)" ); oParser = new parserFormula( "CHISQ.INV(0.6,2)", "A1", ws ); ok( oParser.parse(), "CHISQ.INV(0.6,2)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 1.832581464, "CHISQ.INV(0.6,2)" ); testArrayFormula2("CHISQ.INV", 2, 2); } ); test( "Test: \"CHISQ.DIST\"", function () { oParser = new parserFormula( "CHISQ.DIST(0.5,1,TRUE)", "A1", ws ); ok( oParser.parse(), "CHISQ.DIST(0.5,1,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.52049988, "CHISQ.DIST(0.5,1,TRUE)" ); oParser = new parserFormula( "CHISQ.DIST(2,3,FALSE)", "A1", ws ); ok( oParser.parse(), "CHISQ.DIST(2,3,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.20755375, "CHISQ.DIST(2,3,FALSE)" ); testArrayFormula2("CHISQ.DIST", 3, 3); } ); test( "Test: \"CHIINV\"", function () { ws.getRange2( "A2" ).setValue( "0.050001" ); ws.getRange2( "A3" ).setValue( "10" ); oParser = new parserFormula( "CHIINV(A2,A3)", "A1", ws ); ok( oParser.parse(), "CHIINV(A2,A3)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 18.306973, "CHIINV(A2,A3)" ); testArrayFormula2("CHIINV", 2, 2); } ); test( "Test: \"CHISQ.INV.RT\"", function () { ws.getRange2( "A2" ).setValue( "0.050001" ); ws.getRange2( "A3" ).setValue( "10" ); oParser = new parserFormula( "CHISQ.INV.RT(A2,A3)", "A1", ws ); ok( oParser.parse(), "CHISQ.INV.RT(A2,A3)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 18.306973, "CHISQ.INV.RT(A2,A3)" ); testArrayFormula2("CHISQ.INV.RT", 2, 2); } ); test( "Test: \"CHOOSE\"", function () { ws.getRange2( "A2" ).setValue( "st" ); ws.getRange2( "A3" ).setValue( "2nd" ); ws.getRange2( "A4" ).setValue( "3rd" ); ws.getRange2( "A5" ).setValue( "Finished" ); ws.getRange2( "B2" ).setValue( "Nails" ); ws.getRange2( "B3" ).setValue( "Screws" ); ws.getRange2( "B4" ).setValue( "Nuts" ); ws.getRange2( "B5" ).setValue( "Bolts" ); oParser = new parserFormula( "CHOOSE(2,A2,A3,A4,A5)", "A1", ws ); ok( oParser.parse(), "CHOOSE(2,A2,A3,A4,A5)" ); strictEqual( oParser.calculate().getValue().getValue(), "2nd", "CHOOSE(2,A2,A3,A4,A5)" ); oParser = new parserFormula( "CHOOSE(4,B2,B3,B4,B5)", "A1", ws ); ok( oParser.parse(), "CHOOSE(4,B2,B3,B4,B5)" ); strictEqual( oParser.calculate().getValue().getValue(), "Bolts", "CHOOSE(4,B2,B3,B4,B5))" ); oParser = new parserFormula( 'CHOOSE(3,"Wide",115,"world",8)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "world" ); //функция возвращает ref //testArrayFormula2("CHOOSE", 2, 9); } ); test( "Test: \"BETA.INV\"", function () { ws.getRange2( "A2" ).setValue( "0.685470581" ); ws.getRange2( "A3" ).setValue( "8" ); ws.getRange2( "A4" ).setValue( "10" ); ws.getRange2( "A5" ).setValue( "1" ); ws.getRange2( "A6" ).setValue( "3" ); oParser = new parserFormula( "BETA.INV(A2,A3,A4,A5,A6)", "A1", ws ); ok( oParser.parse(), "BETA.INV(A2,A3,A4,A5,A6)" ); strictEqual( oParser.calculate().getValue().toFixed(1) - 0, 2, "BETA.INV(A2,A3,A4,A5,A6)" ); testArrayFormula2("BETA.INV", 3, 5); } ); test( "Test: \"BETAINV\"", function () { ws.getRange2( "A2" ).setValue( "0.685470581" ); ws.getRange2( "A3" ).setValue( "8" ); ws.getRange2( "A4" ).setValue( "10" ); ws.getRange2( "A5" ).setValue( "1" ); ws.getRange2( "A6" ).setValue( "3" ); oParser = new parserFormula( "BETAINV(A2,A3,A4,A5,A6)", "A1", ws ); ok( oParser.parse(), "BETAINV(A2,A3,A4,A5,A6)" ); strictEqual( oParser.calculate().getValue().toFixed(1) - 0, 2, "BETAINV(A2,A3,A4,A5,A6)" ); testArrayFormula2("BETAINV", 3, 5); } ); test( "Test: \"BETA.DIST\"", function () { ws.getRange2( "A2" ).setValue( "2" ); ws.getRange2( "A3" ).setValue( "8" ); ws.getRange2( "A4" ).setValue( "10" ); ws.getRange2( "A5" ).setValue( "1" ); ws.getRange2( "A6" ).setValue( "3" ); oParser = new parserFormula( "BETA.DIST(A2,A3,A4,TRUE,A5,A6)", "A1", ws ); ok( oParser.parse(), "BETA.DIST(A2,A3,A4,TRUE,A5,A6)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.6854706, "BETA.DIST(A2,A3,A4,TRUE,A5,A6)" ); oParser = new parserFormula( "BETA.DIST(A2,A3,A4,FALSE,A5,A6)", "A1", ws ); ok( oParser.parse(), "BETA.DIST(A2,A3,A4,FALSE,A5,A6)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 1.4837646, "BETA.DIST(A2,A3,A4,FALSE,A5,A6)" ); testArrayFormula2("BETA.DIST", 4, 6); } ); test( "Test: \"BETADIST\"", function () { ws.getRange2( "A2" ).setValue( "2" ); ws.getRange2( "A3" ).setValue( "8" ); ws.getRange2( "A4" ).setValue( "10" ); ws.getRange2( "A5" ).setValue( "1" ); ws.getRange2( "A6" ).setValue( "3" ); oParser = new parserFormula( "BETADIST(A2,A3,A4,A5,A6)", "A1", ws ); ok( oParser.parse(), "BETADIST(A2,A3,A4,A5,A6)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.6854706, "BETADIST(A2,A3,A4,A5,A6)" ); oParser = new parserFormula( "BETADIST(1,2,3,1,6)", "A1", ws ); ok( oParser.parse(), "BETADIST(1,2,3,1,6)" ); strictEqual( oParser.calculate().getValue(), 0, "BETADIST(1,2,3,1,6)" ); oParser = new parserFormula( "BETADIST(6,2,3,1,6)", "A1", ws ); ok( oParser.parse(), "BETADIST(6,2,3,1,6)" ); strictEqual( oParser.calculate().getValue(), 1, "BETADIST(6,2,3,1,6)" ); testArrayFormula2("BETADIST", 3, 5); } ); test( "Test: \"BESSELJ\"", function () { oParser = new parserFormula( "BESSELJ(1.9, 2)", "A1", ws ); ok( oParser.parse(), "BESSELJ(1.9, 2)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.329925728, "BESSELJ(1.9, 2)" ); oParser = new parserFormula( "BESSELJ(1.9, 2.4)", "A1", ws ); ok( oParser.parse(), "BESSELJ(1.9, 2.4)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.329925728, "BESSELJ(1.9, 2.4)" ); oParser = new parserFormula( "BESSELJ(-1.9, 2.4)", "A1", ws ); ok( oParser.parse(), "BESSELJ(-1.9, 2.4)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.329925728, "BESSELJ(-1.9, 2.4)" ); oParser = new parserFormula( "BESSELJ(-1.9, -2.4)", "A1", ws ); ok( oParser.parse(), "BESSELJ(-1.9, -2.4)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("BESSELJ", 2, 2, true); } ); test( "Test: \"BESSELK\"", function () { oParser = new parserFormula( "BESSELK(1.5, 1)", "A1", ws ); ok( oParser.parse(), "BESSELK(1.5, 1)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.277387804, "BESSELK(1.5, 1)" ); oParser = new parserFormula( "BESSELK(1, 3)", "A1", ws ); ok( oParser.parse(), "BESSELK(1, 3)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 7.10126281, "BESSELK(1, 3)" ); oParser = new parserFormula( "BESSELK(-1.123,2)", "A1", ws ); ok( oParser.parse(), "BESSELK(-1.123,2)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BESSELK(1,-2)", "A1", ws ); ok( oParser.parse(), "BESSELK(1,-2)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("BESSELK", 2, 2, true); } ); test( "Test: \"BESSELY\"", function () { oParser = new parserFormula( "BESSELY(2.5, 1)", "A1", ws ); ok( oParser.parse(), "BESSELY(2.5, 1)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.1459181, "BESSELY(2.5, 1)" ); oParser = new parserFormula( "BESSELY(1,-2)", "A1", ws ); ok( oParser.parse(), "BESSELY(1,-2)" ); strictEqual( oParser.calculate().getValue(), "#NUM!", "BESSELY(1,-2)" ); oParser = new parserFormula( "BESSELY(-1,2)", "A1", ws ); ok( oParser.parse(), "BESSELY(-1,2)" ); strictEqual( oParser.calculate().getValue(), "#NUM!", "BESSELY(-1,2)" ); testArrayFormula2("BESSELY", 2, 2, true) } ); test( "Test: \"BESSELI\"", function () { //есть различия excel в некоторых формулах(неточности в 7 цифре после точки) oParser = new parserFormula( "BESSELI(1.5, 1)", "A1", ws ); ok( oParser.parse(), "BESSELI(1.5, 1)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.981666, "BESSELI(1.5, 1)" ); oParser = new parserFormula( "BESSELI(1,2)", "A1", ws ); ok( oParser.parse(), "BESSELI(1,2)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.135748, "BESSELI(1,2)" ); oParser = new parserFormula( "BESSELI(1,-2)", "A1", ws ); ok( oParser.parse(), "BESSELI(1,-2)" ); strictEqual( oParser.calculate().getValue(), "#NUM!", "BESSELI(1,-2)" ); oParser = new parserFormula( "BESSELI(-1,2)", "A1", ws ); ok( oParser.parse(), "BESSELI(-1,2)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.135748, "BESSELI(-1,2)" ); testArrayFormula2("BESSELI", 2, 2, true) } ); test( "Test: \"GAMMA.INV\"", function () { ws.getRange2( "A2" ).setValue( "0.068094" ); ws.getRange2( "A3" ).setValue( "9" ); ws.getRange2( "A4" ).setValue( "2" ); oParser = new parserFormula( "GAMMA.INV(A2,A3,A4)", "A1", ws ); ok( oParser.parse(), "GAMMA.INV(A2,A3,A4)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 10.0000112, "GAMMA.INV(A2,A3,A4)" ); testArrayFormula2("GAMMA.INV", 3, 3); } ); test( "Test: \"GAMMAINV\"", function () { ws.getRange2( "A2" ).setValue( "0.068094" ); ws.getRange2( "A3" ).setValue( "9" ); ws.getRange2( "A4" ).setValue( "2" ); oParser = new parserFormula( "GAMMAINV(A2,A3,A4)", "A1", ws ); ok( oParser.parse(), "GAMMAINV(A2,A3,A4)" ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 10.0000112, "GAMMAINV(A2,A3,A4)" ); } ); test( "Test: \"SUM(1,2,3)\"", function () { oParser = new parserFormula( 'SUM(1,2,3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 + 2 + 3 ); testArrayFormula2("SUM", 1, 8, null, true); } ); test( "Test: \"\"s\"&5\"", function () { oParser = new parserFormula( "\"s\"&5", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "s5" ); } ); test( "Test: \"String+Number\"", function () { oParser = new parserFormula( "1+\"099\"", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 100 ); ws.getRange2( "A1469" ).setValue( "'099" ); ws.getRange2( "A1470" ).setValue( "\"099\"" ); oParser = new parserFormula( "1+A1469", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 100 ); oParser = new parserFormula( "1+A1470", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); } ); test( "Test: \"POWER(2,8)\"", function () { oParser = new parserFormula( "POWER(2,8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.pow( 2, 8 ) ); } ); test( "Test: \"POWER(0,-3)\"", function () { oParser = new parserFormula( "POWER(0,-3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); testArrayFormula2("POWER", 2, 2); } ); test( "Test: \"ISNA(A1)\"", function () { ws.getRange2( "A1" ).setValue( "#N/A" ); oParser = new parserFormula( "ISNA(A1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); testArrayFormula2("ISNA",1,1); } ); test( "Test: \"ISNONTEXT\"", function () { oParser = new parserFormula( 'ISNONTEXT("123")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE" ); testArrayFormula2("ISNONTEXT",1,1); } ); test( "Test: \"ISNUMBER\"", function () { ws.getRange2( "A1" ).setValue( "123" ); oParser = new parserFormula( 'ISNUMBER(4)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( 'ISNUMBER(A1)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); testArrayFormula2("ISNUMBER",1,1); } ); test( "Test: \"ISODD\"", function () { oParser = new parserFormula( 'ISODD(-1)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( 'ISODD(2.5)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( 'ISODD(5)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); testArrayFormula2("ISODD",1,1,true); } ); test( "Test: \"ROUND\"", function () { oParser = new parserFormula( "ROUND(2.15, 1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2.2 ); oParser = new parserFormula( "ROUND(2.149, 1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2.1 ); oParser = new parserFormula( "ROUND(-1.475, 2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1.48 ); oParser = new parserFormula( "ROUND(21.5, -1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 20 ); oParser = new parserFormula( "ROUND(626.3,-3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1000 ); oParser = new parserFormula( "ROUND(1.98,-1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "ROUND(-50.55,-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -100 ); testArrayFormula2("ROUND", 2, 2) } ); test( "Test: \"ROUNDUP(31415.92654,-2)\"", function () { oParser = new parserFormula( "ROUNDUP(31415.92654,-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 31500 ); } ); test( "Test: \"ROUNDUP(3.2,0)\"", function () { oParser = new parserFormula( "ROUNDUP(3.2,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); } ); test( "Test: \"ROUNDUP(-3.14159,1)\"", function () { oParser = new parserFormula( "ROUNDUP(-3.14159,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -3.2 ); } ); test( "Test: \"ROUNDUP(3.14159,3)\"", function () { oParser = new parserFormula( "ROUNDUP(3.14159,3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3.142 ); testArrayFormula2("ROUNDUP", 2, 2) } ); test( "Test: \"ROUNDUP\"", function () { oParser = new parserFormula( "ROUNDUP(2.1123,4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(4) - 0, 2.1123 ); oParser = new parserFormula( "ROUNDUP(2,4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "ROUNDUP(2,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "ROUNDUP(2.1123,-1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( "ROUNDUP(2.1123,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); } ); test( "Test: \"ROUNDDOWN(31415.92654,-2)\"", function () { oParser = new parserFormula( "ROUNDDOWN(31415.92654,-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 31400 ); } ); test( "Test: \"ROUNDDOWN(-3.14159,1)\"", function () { oParser = new parserFormula( "ROUNDDOWN(-3.14159,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -3.1 ); } ); test( "Test: \"ROUNDDOWN(3.14159,3)\"", function () { oParser = new parserFormula( "ROUNDDOWN(3.14159,3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3.141 ); } ); test( "Test: \"ROUNDDOWN(3.2,0)\"", function () { oParser = new parserFormula( "ROUNDDOWN(3.2,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); testArrayFormula2("ROUNDDOWN", 2, 2) } ); test( "Test: \"MROUND\"", function () { var multiple;//должен равняться значению второго аргумента function mroundHelper( num ) { var multiplier = Math.pow( 10, Math.floor( Math.log( Math.abs( num ) ) / Math.log( 10 ) ) - AscCommonExcel.cExcelSignificantDigits + 1 ); var nolpiat = 0.5 * (num > 0 ? 1 : num < 0 ? -1 : 0) * multiplier; var y = (num + nolpiat) / multiplier; y = y / Math.abs( y ) * Math.floor( Math.abs( y ) ) var x = y * multiplier / multiple // var x = number / multiple; var nolpiat = 5 * (x / Math.abs( x )) * Math.pow( 10, Math.floor( Math.log( Math.abs( x ) ) / Math.log( 10 ) ) - AscCommonExcel.cExcelSignificantDigits ); x = x + nolpiat; x = x | x; return x * multiple; } oParser = new parserFormula( "MROUND(10,3)", "A1", ws ); ok( oParser.parse() ); multiple = 3; strictEqual( oParser.calculate().getValue(), mroundHelper( 10 + 3 / 2 ) ); oParser = new parserFormula( "MROUND(-10,-3)", "A1", ws ); ok( oParser.parse() ); multiple = -3; strictEqual( oParser.calculate().getValue(), mroundHelper( -10 + -3 / 2 ) ); oParser = new parserFormula( "MROUND(1.3,0.2)", "A1", ws ); ok( oParser.parse() ); multiple = 0.2; strictEqual( oParser.calculate().getValue(), mroundHelper( 1.3 + 0.2 / 2 ) ); testArrayFormula2("MROUND", 2, 2, true); } ); test( "Test: \"T(\"HELLO\")\"", function () { oParser = new parserFormula( "T(\"HELLO\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "HELLO" ); } ); test( "Test: \"MMULT\"", function () { ws.getRange2( "AAA102" ).setValue( "4" ); ws.getRange2( "AAA103" ).setValue( "5" ); ws.getRange2( "AAA104" ).setValue( "6" ); ws.getRange2( "AAA105" ).setValue( "7" ); ws.getRange2( "AAB102" ).setValue( "1" ); ws.getRange2( "AAB103" ).setValue( "2" ); ws.getRange2( "AAB104" ).setValue( "3" ); ws.getRange2( "AAB105" ).setValue( "2" ); ws.getRange2( "AAC102" ).setValue( "4" ); ws.getRange2( "AAC103" ).setValue( "5" ); ws.getRange2( "AAC104" ).setValue( "6" ); ws.getRange2( "AAC105" ).setValue( "3" ); ws.getRange2( "AAD102" ).setValue( "7" ); ws.getRange2( "AAD103" ).setValue( "8" ); ws.getRange2( "AAD104" ).setValue( "9" ); ws.getRange2( "AAD105" ).setValue( "4" ); ws.getRange2( "AAF102" ).setValue( "1" ); ws.getRange2( "AAF103" ).setValue( "2" ); ws.getRange2( "AAF104" ).setValue( "3" ); ws.getRange2( "AAF105" ).setValue( "6" ); ws.getRange2( "AAG102" ).setValue( "2" ); ws.getRange2( "AAG103" ).setValue( "3" ); ws.getRange2( "AAG104" ).setValue( "4" ); ws.getRange2( "AAG105" ).setValue( "5" ); oParser = new parserFormula( "MMULT(AAC102,AAF104)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 12 ); oParser = new parserFormula( "MMULT(AAA102:AAD105,AAF104)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "MMULT(AAC102,AAF104)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 12 ); oParser = new parserFormula( "MMULT(AAA102:AAD105,AAF102:AAG105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 60 ); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue(), 62 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 72 ); strictEqual( oParser.calculate().getElementRowCol(1,1).getValue(), 76 ); oParser = new parserFormula( "MMULT(AAA102:AAD105,AAF102:AAF105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 60 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 72 ); oParser = new parserFormula( "MMULT(AAA102:AAD105,AAF102:AAF105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 60 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 72 ); oParser = new parserFormula( "MMULT(AAA102:AAD105,AAF102:AAF104)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "MMULT(AAA102:AAD105,AAK110:AAN110)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "MMULT(AAA102:AAD105,AAA102:AAD105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 94 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 116 ); strictEqual( oParser.calculate().getElementRowCol(2,0).getValue(), 138 ); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue(), 32 ); strictEqual( oParser.calculate().getElementRowCol(1,1).getValue(), 40 ); strictEqual( oParser.calculate().getElementRowCol(2,1).getValue(), 48 ); oParser = new parserFormula( "MMULT(AAF102:AAF105,AAG102:AAG105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "MMULT(AAF102:AAF105,AAA102:AAD102)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 4 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 8 ); strictEqual( oParser.calculate().getElementRowCol(2,0).getValue(), 12 ); } ); test( "Test: \"T(123)\"", function () { oParser = new parserFormula( "T(123)", "A1", ws ); ok( oParser.parse() ); ok( !oParser.calculate().getValue(), "123" ); } ); test( "Test: YEAR", function () { oParser = new parserFormula( "YEAR(2013)", "A1", ws ); ok( oParser.parse() ); if ( AscCommon.bDate1904 ) strictEqual( oParser.calculate().getValue(), 1909 ); else strictEqual( oParser.calculate().getValue(), 1905 ); testArrayFormula2("YEAR",1,1); } ); test( "Test: DAY", function () { oParser = new parserFormula( "DAY(2013)", "A1", ws ); ok( oParser.parse() ); if ( AscCommon.bDate1904 ) strictEqual( oParser.calculate().getValue(), 6 ); else strictEqual( oParser.calculate().getValue(), 5 ); testArrayFormula2("DAY", 1, 1); } ); test( "Test: DAYS", function () { ws.getRange2( "A2" ).setValue( "12/31/2011" ); ws.getRange2( "A3" ).setValue( "1/1/2011" ); oParser = new parserFormula( 'DAYS("3/15/11","2/1/11")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 42 ); oParser = new parserFormula( "DAYS(A2,A3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 364 ); oParser = new parserFormula( "DAYS(A2,A3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 364 ); oParser = new parserFormula( 'DAYS("2008-03-03","2008-03-01")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( 'DAYS("2008-03-01","2008-03-03")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -2 ); testArrayFormula2("DAYS", 2, 2); } ); test( "Test: DAY 2", function () { oParser = new parserFormula( "DAY(\"20 may 2045\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 20 ); } ); test( "Test: MONTH #1", function () { oParser = new parserFormula( "MONTH(2013)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); } ); test( "Test: MONTH #2", function () { oParser = new parserFormula( "MONTH(DATE(2013,2,2))", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); } ); test( "Test: MONTH #3", function () { oParser = new parserFormula( "MONTH(NOW())", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), new cDate().getUTCMonth() + 1 ); testArrayFormula2("MONTH",1,1); } ); test( "Test: \"10-3\"", function () { oParser = new parserFormula( "10-3", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); } ); test( "Test: \"SUM\"", function () { ws.getRange2( "S5" ).setValue( "1" ); ws.getRange2( "S6" ).setValue( numDivFact(-1, 2) ); ws.getRange2( "S7" ).setValue( numDivFact(1, 4) ); ws.getRange2( "S8" ).setValue( numDivFact(-1, 6) ); oParser = new parserFormula( "SUM(S5:S8)", "A1", ws ); ok( oParser.parse() ); // strictEqual( oParser.calculate().getValue(), 1-1/Math.fact(2)+1/Math.fact(4)-1/Math.fact(6) ); ok( Math.abs( oParser.calculate().getValue() - (1 - 1 / Math.fact( 2 ) + 1 / Math.fact( 4 ) - 1 / Math.fact( 6 )) ) < dif ); } ); test( "Test: \"MAX\"", function () { ws.getRange2( "S5" ).setValue( "1" ); ws.getRange2( "S6" ).setValue( numDivFact(-1, 2) ); ws.getRange2( "S7" ).setValue( numDivFact(1, 4) ); ws.getRange2( "S8" ).setValue( numDivFact(-1, 6) ); oParser = new parserFormula( "MAX(S5:S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); ws.getRange2( "S5" ).setValue( "#DIV/0!" ); ws.getRange2( "S6" ).setValue( "TRUE" ); ws.getRange2( "S7" ).setValue( "qwe" ); ws.getRange2( "S8" ).setValue( "" ); ws.getRange2( "S9" ).setValue( "-1" ); oParser = new parserFormula( "MAX(S5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MAX(S6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MAX(S7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MAX(S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MAX(S5:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MAX(S6:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1 ); oParser = new parserFormula( "MAX(-1, TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); testArrayFormula2("MAX", 1, 8, null, true); } ); test( "Test: \"MAXA\"", function () { ws.getRange2( "S5" ).setValue( "1" ); ws.getRange2( "S6" ).setValue( numDivFact(-1, 2) ); ws.getRange2( "S7" ).setValue( numDivFact(1, 4) ); ws.getRange2( "S8" ).setValue( numDivFact(-1, 6) ); oParser = new parserFormula( "MAXA(S5:S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); ws.getRange2( "S5" ).setValue( "#DIV/0!" ); ws.getRange2( "S6" ).setValue( "TRUE" ); ws.getRange2( "S7" ).setValue( "qwe" ); ws.getRange2( "S8" ).setValue( "" ); ws.getRange2( "S9" ).setValue( "-1" ); oParser = new parserFormula( "MAXA(S5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MAXA(S6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "MAXA(S7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MAXA(S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MAXA(S5:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MAXA(S6:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "MAXA(-1, TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); testArrayFormula2("MAXA", 1, 8, null, true); } ); test( "Test: \"MIN\"", function () { ws.getRange2( "S5" ).setValue( "1" ); ws.getRange2( "S6" ).setValue( numDivFact(-1, 2) ); ws.getRange2( "S7" ).setValue( numDivFact(1, 4) ); ws.getRange2( "S8" ).setValue( numDivFact(-1, 6) ); oParser = new parserFormula( "MIN(S5:S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1 / Math.fact( 2 ) ); ws.getRange2( "S5" ).setValue( "#DIV/0!" ); ws.getRange2( "S6" ).setValue( "TRUE" ); ws.getRange2( "S7" ).setValue( "qwe" ); ws.getRange2( "S8" ).setValue( "" ); ws.getRange2( "S9" ).setValue( "2" ); oParser = new parserFormula( "MIN(S5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MIN(S6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MIN(S7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MIN(S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MIN(S5:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MIN(S6:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "MIN(2, TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); testArrayFormula2("min", 1, 8, null, true); } ); test( "Test: \"MINA\"", function () { ws.getRange2( "S5" ).setValue( "1" ); ws.getRange2( "S6" ).setValue( numDivFact(-1, 2) ); ws.getRange2( "S7" ).setValue( numDivFact(1, 4) ); ws.getRange2( "S8" ).setValue( numDivFact(-1, 6) ); oParser = new parserFormula( "MINA(S5:S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1 / Math.fact( 2 ) ); ws.getRange2( "S5" ).setValue( "#DIV/0!" ); ws.getRange2( "S6" ).setValue( "TRUE" ); ws.getRange2( "S7" ).setValue( "qwe" ); ws.getRange2( "S8" ).setValue( "" ); ws.getRange2( "S9" ).setValue( "2" ); oParser = new parserFormula( "MINA(S5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MINA(S6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "MINA(S7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MINA(S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MINA(S5:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "MINA(S6:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MINA(2, TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); testArrayFormula2("mina", 1, 8, null, true); } ); test( "Test: SUM(S7:S9,{1,2,3})", function () { ws.getRange2( "S7" ).setValue( "1" ); ws.getRange2( "S8" ).setValue( "2" ); ws.getRange2( "S9" ).setValue( "3" ); oParser = new parserFormula( "SUM(S7:S9,{1,2,3})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 12 ); } ); test( "Test: ISREF", function () { oParser = new parserFormula( "ISREF(G0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE" ); testArrayFormula2("ISREF",1,1,null,true); } ); test( "Test: ISTEXT", function () { ws.getRange2( "S7" ).setValue( "test" ); oParser = new parserFormula( "ISTEXT(S7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); testArrayFormula2("ISTEXT",1,1); } ); test( "Test: MOD", function () { oParser = new parserFormula( "MOD(7,3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "MOD(-10,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MOD(-9,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "MOD(-8,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "MOD(-7,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "MOD(-6,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "MOD(-5,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MOD(10,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MOD(9,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "MOD(8,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "MOD(15,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MOD(15,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); testArrayFormula2("MOD", 2, 2); } ); test( "Test: rename sheet #1", function () { wb.dependencyFormulas.unlockRecal(); ws.getRange2( "S95" ).setValue( "2" ); ws.getRange2( "S100" ).setValue( "=" + wb.getWorksheet( 0 ).getName() + "!S95" ); ws.setName( "SheetTmp" ); strictEqual( ws.getCell2( "S100" ).getFormula(), ws.getName() + "!S95" ); wb.dependencyFormulas.lockRecal(); } ); test( "Test: wrong ref", function () { oParser = new parserFormula( "1+XXX1", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NAME?" ); } ); test( "Test: \"CODE\"", function () { oParser = new parserFormula( "CODE(\"abc\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 97 ); oParser = new parserFormula( "CODE(TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 84 ); testArrayFormula2("CODE", 1, 1); } ); test( "Test: \"CHAR\"", function () { oParser = new parserFormula( "CHAR(97)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "a" ); testArrayFormula2("CHAR", 1, 1); } ); test( "Test: \"CHAR(CODE())\"", function () { oParser = new parserFormula( "CHAR(CODE(\"A\"))", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "A" ); } ); test( "Test: \"PROPER\"", function () { oParser = new parserFormula( "PROPER(\"2-cent's worth\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "2-Cent'S Worth" ); oParser = new parserFormula( "PROPER(\"76BudGet\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "76Budget" ); oParser = new parserFormula( "PROPER(\"this is a TITLE\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "This Is A Title" ); oParser = new parserFormula( 'PROPER(TRUE)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "True" ); testArrayFormula2("PROPER", 1, 1); } ); test( "Test: \"GCD\"", function () { oParser = new parserFormula( "GCD(10,100,50)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( "GCD(24.6,36.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 12 ); oParser = new parserFormula( "GCD(-1,39,52)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("GCD", 1, 8, null, true); } ); test( "Test: \"FIXED\"", function () { oParser = new parserFormula( "FIXED(1234567,-3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "1,235,000" ); oParser = new parserFormula( "FIXED(.555555,10)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "0.5555550000" ); oParser = new parserFormula( "FIXED(1234567.555555,4,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "1234567.5556" ); oParser = new parserFormula( "FIXED(1234567)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "1,234,567.00" ); testArrayFormula2("FIXED", 2, 3); } ); test( "Test: \"REPLACE\"", function () { oParser = new parserFormula( "REPLACE(\"abcdefghijk\",3,4,\"XY\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "abXYghijk" ); oParser = new parserFormula( "REPLACE(\"abcdefghijk\",3,1,\"12345\")", "B2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "ab12345defghijk" ); oParser = new parserFormula( "REPLACE(\"abcdefghijk\",15,4,\"XY\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "abcdefghijkXY" ); testArrayFormula2("REPLACE", 4, 4); } ); test( "Test: \"SEARCH\"", function () { oParser = new parserFormula( "SEARCH(\"~*\",\"abc*dEF\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "SEARCH(\"~\",\"abc~dEF\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "SEARCH(\"de\",\"abcdEF\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "SEARCH(\"?c*e\",\"abcdEF\")", "B2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "SEARCH(\"de\",\"dEFabcdEF\",3)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( "SEARCH(\"de\",\"dEFabcdEF\",30)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("SEARCH", 2, 3); } ); test( "Test: \"SUBSTITUTE\"", function () { oParser = new parserFormula( "SUBSTITUTE(\"abcaAabca\",\"a\",\"xx\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "xxbcxxAxxbcxx" ); oParser = new parserFormula( "SUBSTITUTE(\"abcaaabca\",\"a\",\"xx\")", "B2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "xxbcxxxxxxbcxx" ); oParser = new parserFormula( "SUBSTITUTE(\"abcaaabca\",\"a\",\"\",10)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "bcbc" ); oParser = new parserFormula( "SUBSTITUTE(\"abcaaabca\",\"a\",\"xx\",3)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "abcaxxabca" ); testArrayFormula2("SUBSTITUTE", 3, 4); } ); test( "Test: \"SHEET\"", function () { oParser = new parserFormula( "SHEET(Hi_Temps)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NAME?" ); testArrayFormula2("SHEET", 1, 1, null, true); } ); test( "Test: \"SHEETS\"", function () { oParser = new parserFormula( "SHEETS(Hi_Temps)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NAME?" ); oParser = new parserFormula( "SHEETS()", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); testArrayFormula2("SHEETS", 1, 1, null, true); } ); test( "Test: \"TRIM\"", function () { oParser = new parserFormula( "TRIM(\" abc def \")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "abc def" ); oParser = new parserFormula( "TRIM(\" First Quarter Earnings \")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "First Quarter Earnings" ); testArrayFormula2("TRIM", 1, 1); } ); test( "Test: \"TRIMMEAN\"", function () { ws.getRange2( "A2" ).setValue( "4" ); ws.getRange2( "A3" ).setValue( "5" ); ws.getRange2( "A4" ).setValue( "6" ); ws.getRange2( "A5" ).setValue( "7" ); ws.getRange2( "A6" ).setValue( "2" ); ws.getRange2( "A7" ).setValue( "3" ); ws.getRange2( "A8" ).setValue( "4" ); ws.getRange2( "A9" ).setValue( "5" ); ws.getRange2( "A10" ).setValue( "1" ); ws.getRange2( "A11" ).setValue( "2" ); ws.getRange2( "A12" ).setValue( "3" ); oParser = new parserFormula( "TRIMMEAN(A2:A12,0.2)", "A1", ws ); ok( oParser.parse(), "TRIMMEAN(A2:A12,0.2)" ); strictEqual( oParser.calculate().getValue().toFixed(3) - 0, 3.778, "TRIMMEAN(A2:A12,0.2)" ); //TODO нужна другая функция для тестирования //testArrayFormula2("TRIMMEAN", 2, 2) } ); test( "Test: \"DOLLAR\"", function () { oParser = new parserFormula( "DOLLAR(1234.567)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "$1,234.57" ); oParser = new parserFormula( "DOLLAR(1234.567,-2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "$1,200" ); oParser = new parserFormula( "DOLLAR(-1234.567,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "($1,234.5670)" ); testArrayFormula2("DOLLAR", 2, 2); } ); test( "Test: \"EXACT\"", function () { ws.getRange2( "A2" ).setValue( "word" ); ws.getRange2( "A3" ).setValue( "Word" ); ws.getRange2( "A4" ).setValue( "w ord" ); ws.getRange2( "B2" ).setValue( "word" ); ws.getRange2( "B3" ).setValue( "word" ); ws.getRange2( "B4" ).setValue( "word" ); oParser = new parserFormula( "EXACT(A2,B2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( "EXACT(A3,B3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( "EXACT(A4,B4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( "EXACT(TRUE,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( 'EXACT("TRUE",TRUE)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( 'EXACT("TRUE","TRUE")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( 'EXACT("true",TRUE)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE" ); testArrayFormula2("EXACT", 2, 2); } ); test( "Test: \"LEFT\"", function () { ws.getRange2( "A2" ).setValue( "Sale Price" ); ws.getRange2( "A3" ).setValue( "Sweden" ); oParser = new parserFormula( "LEFT(A2,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Sale" ); oParser = new parserFormula( "LEFT(A3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "S" ); testArrayFormula2("LEFT", 1, 2); } ); test( "Test: \"LEN\"", function () { ws.getRange2( "A201" ).setValue( "Phoenix, AZ" ); ws.getRange2( "A202" ).setValue( "" ); ws.getRange2( "A203" ).setValue( " One " ); oParser = new parserFormula( "LEN(A201)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 11 ); oParser = new parserFormula( "LEN(A202)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "LEN(A203)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 11 ); oParser = new parserFormula( 'LEN(TRUE)', "A2", ws ); ok( oParser.parse(), 'LEN(TRUE)' ); strictEqual( oParser.calculate().getValue(), 4, 'LEN(TRUE)'); testArrayFormula2("LEN", 1, 1); } ); test( "Test: \"REPT\"", function () { oParser = new parserFormula( 'REPT("*-", 3)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "*-*-*-" ); oParser = new parserFormula( 'REPT("-",10)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "----------" ); testArrayFormula2("REPT", 2, 2); } ); test( "Test: \"RIGHT\"", function () { ws.getRange2( "A2" ).setValue( "Sale Price" ); ws.getRange2( "A3" ).setValue( "Stock Number" ); oParser = new parserFormula( "RIGHT(A2,5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Price" ); oParser = new parserFormula( "RIGHT(A3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "r" ); testArrayFormula2("RIGHT", 1, 2); } ); test( "Test: \"VALUE\"", function () { oParser = new parserFormula( "VALUE(\"123.456\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 123.456 ); oParser = new parserFormula( "VALUE(\"$1,000\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1000 ); oParser = new parserFormula( "VALUE(\"23-Mar-2002\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 37338 ); oParser = new parserFormula( "VALUE(\"03-26-2006\")", "A2", ws ); ok( oParser.parse() ); if ( AscCommon.bDate1904 ) strictEqual( oParser.calculate().getValue(), 37340 ); else strictEqual( oParser.calculate().getValue(), 38802 ); oParser = new parserFormula( "VALUE(\"16:48:00\")-VALUE(\"12:17:12\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), AscCommon.g_oFormatParser.parse( "16:48:00" ).value - AscCommon.g_oFormatParser.parse( "12:17:12" ).value ); testArrayFormula2("value", 1, 1); } ); test( "Test: \"DATE\"", function () { testArrayFormula2("DATE", 3, 3); } ); test( "Test: \"DATEVALUE\"", function () { oParser = new parserFormula( "DATEVALUE(\"10-10-2010 10:26\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 40461 ); oParser = new parserFormula( "DATEVALUE(\"10-10-2010 10:26\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 40461 ); tmp = ws.getRange2( "A7" ); tmp.setNumFormat('@'); tmp.setValue( "3-Mar" ); oParser = new parserFormula( "DATEVALUE(A7)", "A2", ws ); ok( oParser.parse() ); var d = new cDate(); d.setUTCMonth(2); d.setUTCDate(3); strictEqual( oParser.calculate().getValue(), d.getExcelDate() ); oParser = new parserFormula( "DATEVALUE(\"$1,000\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "DATEVALUE(\"23-Mar-2002\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 37338 ); oParser = new parserFormula( "DATEVALUE(\"03-26-2006\")", "A2", ws ); ok( oParser.parse() ); if ( AscCommon.bDate1904 ) strictEqual( oParser.calculate().getValue(), 37340 ); else strictEqual( oParser.calculate().getValue(), 38802 ); testArrayFormula("DATEVALUE"); } ); test( "Test: \"EDATE\"", function () { if ( !AscCommon.bDate1904 ) { oParser = new parserFormula( "EDATE(DATE(2006,1,31),5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38898 ); oParser = new parserFormula( "EDATE(DATE(2004,2,29),12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38411 ); ws.getRange2( "A7" ).setValue( "02-28-2004" ); oParser = new parserFormula( "EDATE(A7,12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38411 ); oParser = new parserFormula( "EDATE(DATE(2004,1,15),-23)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 37302 ); } else { oParser = new parserFormula( "EDATE(DATE(2006,1,31),5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 37436 ); oParser = new parserFormula( "EDATE(DATE(2004,2,29),12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 36949 ); ws.getRange2( "A7" ).setValue( "02-28-2004" ); oParser = new parserFormula( "EDATE(A7,12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 36949 ); oParser = new parserFormula( "EDATE(DATE(2004,1,15),-23)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 35840 ); } testArrayFormula2("EDATE", 2, 2, true); } ); test( "Test: \"EOMONTH\"", function () { if ( !AscCommon.bDate1904 ) { oParser = new parserFormula( "EOMONTH(DATE(2006,1,31),5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38898 ); oParser = new parserFormula( "EOMONTH(DATE(2004,2,29),12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38411 ); ws.getRange2( "A7" ).setValue( "02-28-2004" ); oParser = new parserFormula( "EOMONTH(A7,12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38411 ); oParser = new parserFormula( "EOMONTH(DATE(2004,1,15),-23)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 37315 ); } else { oParser = new parserFormula( "EOMONTH(DATE(2006,1,31),5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 37436 ); oParser = new parserFormula( "EOMONTH(DATE(2004,2,29),12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 36949 ); ws.getRange2( "A7" ).setValue( "02-28-2004" ); oParser = new parserFormula( "EOMONTH(A7,12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 36949 ); oParser = new parserFormula( "EOMONTH(DATE(2004,1,15),-23)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 35853 ); } testArrayFormula2("EOMONTH", 2, 2, true); } ); test( "Test: \"EVEN\"", function () { oParser = new parserFormula( "EVEN(1.5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "EVEN(3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "EVEN(2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "EVEN(-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -2 ); testArrayFormula("EVEN"); } ); test( "Test: \"NETWORKDAYS\"", function () { oParser = new parserFormula( "NETWORKDAYS(DATE(2006,1,1),DATE(2006,1,31))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 22 ); oParser = new parserFormula( "NETWORKDAYS(DATE(2006,1,31),DATE(2006,1,1))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -22 ); oParser = new parserFormula( "NETWORKDAYS(DATE(2006,1,1),DATE(2006,2,1),{\"01-02-2006\",\"01-16-2006\"})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 21 ); testArrayFormula2("NETWORKDAYS", 2, 3, true); } ); test( "Test: \"NETWORKDAYS.INTL\"", function () { var formulaStr = "NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,1,31))"; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), 22, formulaStr ); formulaStr = "NETWORKDAYS.INTL(DATE(2006,2,28),DATE(2006,1,31))"; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), -21, formulaStr ); formulaStr = 'NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,2,1),7,{"1/2/2006","1/16/2006"})'; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), 22, formulaStr ); formulaStr = 'NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,2,1),17,{"1/2/2006","1/16/2006"})'; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), 26, formulaStr ); formulaStr = 'NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,2,1),"1111111",{"1/2/2006","1/16/2006"})'; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), 0, formulaStr ); formulaStr = 'NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,2,1),"0010001",{"1/2/2006","1/16/2006"})'; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), 20, formulaStr ); formulaStr = 'NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,2,1),"0000000",{"1/2/2006","1/16/2006"})'; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), 30, formulaStr ); formulaStr = 'NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,2,1),"19",{"1/2/2006","1/16/2006"})'; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), "#VALUE!", formulaStr ); formulaStr = 'NETWORKDAYS.INTL(DATE(2006,1,1),DATE(2006,2,1),19,{"1/2/2006","1/16/2006"})'; oParser = new parserFormula( formulaStr, "A2", ws ); ok( oParser.parse(), formulaStr ); strictEqual( oParser.calculate().getValue(), "#NUM!", formulaStr ); } ); test( "Test: \"N\"", function () { ws.getRange2( "A2" ).setValue( "7" ); ws.getRange2( "A3" ).setValue( "Even" ); ws.getRange2( "A4" ).setValue( "TRUE" ); ws.getRange2( "A5" ).setValue( "4/17/2011" ); oParser = new parserFormula( "N(A2)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( "N(A3)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "N(A4)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "N(A5)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 40650 ); oParser = new parserFormula( 'N("7")', "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); //TODO нужна другая функция для тестирования //testArrayFormula2("N", 1, 1); } ); test( "Test: \"SUMIF\"", function () { ws.getRange2( "A2" ).setValue( "100000" ); ws.getRange2( "A3" ).setValue( "200000" ); ws.getRange2( "A4" ).setValue( "300000" ); ws.getRange2( "A5" ).setValue( "400000" ); ws.getRange2( "B2" ).setValue( "7000" ); ws.getRange2( "B3" ).setValue( "14000" ); ws.getRange2( "B4" ).setValue( "21000" ); ws.getRange2( "B5" ).setValue( "28000" ); ws.getRange2( "C2" ).setValue( "250000" ); oParser = new parserFormula( "SUMIF(A2:A5,\">160000\",B2:B5)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 63000 ); oParser = new parserFormula( "SUMIF(A2:A5,\">160000\")", "A8", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 900000 ); oParser = new parserFormula( "SUMIF(A2:A5,300000,B2:B5)", "A9", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 21000 ); oParser = new parserFormula( "SUMIF(A2:A5,\">\" & C2,B2:B5)", "A10", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 49000 ); oParser = new parserFormula( "SUMIF(A2,\">160000\",B2:B5)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "SUMIF(A3,\">160000\",B2:B5)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7000 ); oParser = new parserFormula( "SUMIF(A4,\">160000\",B4:B5)", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 21000 ); oParser = new parserFormula( "SUMIF(A4,\">160000\")", "A7", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 300000); ws.getRange2( "A12" ).setValue( "Vegetables" ); ws.getRange2( "A13" ).setValue( "Vegetables" ); ws.getRange2( "A14" ).setValue( "Fruits" ); ws.getRange2( "A15" ).setValue( "" ); ws.getRange2( "A16" ).setValue( "Vegetables" ); ws.getRange2( "A17" ).setValue( "Fruits" ); ws.getRange2( "B12" ).setValue( "Tomatoes" ); ws.getRange2( "B13" ).setValue( "Celery" ); ws.getRange2( "B14" ).setValue( "Oranges" ); ws.getRange2( "B15" ).setValue( "Butter" ); ws.getRange2( "B16" ).setValue( "Carrots" ); ws.getRange2( "B17" ).setValue( "Apples" ); ws.getRange2( "C12" ).setValue( "2300" ); ws.getRange2( "C13" ).setValue( "5500" ); ws.getRange2( "C14" ).setValue( "800" ); ws.getRange2( "C15" ).setValue( "400" ); ws.getRange2( "C16" ).setValue( "4200" ); ws.getRange2( "C17" ).setValue( "1200" ); oParser = new parserFormula( "SUMIF(A12:A17,\"Fruits\",C12:C17)", "A19", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2000 ); oParser = new parserFormula( "SUMIF(A12:A17,\"Vegetables\",C12:C17)", "A20", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 12000 ); oParser = new parserFormula( "SUMIF(B12:B17,\"*es\",C12:C17)", "A21", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4300 ); oParser = new parserFormula( "SUMIF(A12:A17,\"\",C12:C17)", "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 400 ); } ); test( "Test: \"SUMIFS\"", function () { ws.getRange2( "A2" ).setValue( "5" ); ws.getRange2( "A3" ).setValue( "4" ); ws.getRange2( "A4" ).setValue( "15" ); ws.getRange2( "A5" ).setValue( "3" ); ws.getRange2( "A6" ).setValue( "22" ); ws.getRange2( "A7" ).setValue( "12" ); ws.getRange2( "A8" ).setValue( "10" ); ws.getRange2( "A9" ).setValue( "33" ); ws.getRange2( "B2" ).setValue( "Apples" ); ws.getRange2( "B3" ).setValue( "Apples" ); ws.getRange2( "B4" ).setValue( "Artichokes" ); ws.getRange2( "B5" ).setValue( "Artichokes" ); ws.getRange2( "B6" ).setValue( "Bananas" ); ws.getRange2( "B7" ).setValue( "Bananas" ); ws.getRange2( "B8" ).setValue( "Carrots" ); ws.getRange2( "B9" ).setValue( "Carrots" ); ws.getRange2( "C2" ).setValue( "Tom" ); ws.getRange2( "C3" ).setValue( "Sarah" ); ws.getRange2( "C4" ).setValue( "Tom" ); ws.getRange2( "C5" ).setValue( "Sarah" ); ws.getRange2( "C6" ).setValue( "Tom" ); ws.getRange2( "C7" ).setValue( "Sarah" ); ws.getRange2( "C8" ).setValue( "Tom" ); ws.getRange2( "C9" ).setValue( "Sarah" ); oParser = new parserFormula( "SUMIFS(A2:A9, B2:B9, \"=A*\", C2:C9, \"Tom\")", "A10", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 20 ); oParser = new parserFormula( "SUMIFS(A2:A9, B2:B9, \"<>Bananas\", C2:C9, \"Tom\")", "A11", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30 ); oParser = new parserFormula( "SUMIFS(D:D,E:E,$H2)", "A11", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "SUMIFS(C:D,E:E,$H2)", "A11", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); } ); test( "Test: \"MAXIFS\"", function () { ws.getRange2( "AAA2" ).setValue( "10" ); ws.getRange2( "AAA3" ).setValue( "1" ); ws.getRange2( "AAA4" ).setValue( "100" ); ws.getRange2( "AAA5" ).setValue( "1" ); ws.getRange2( "AAA6" ).setValue( "1" ); ws.getRange2( "AAA7" ).setValue( "50" ); ws.getRange2( "BBB2" ).setValue( "b" ); ws.getRange2( "BBB3" ).setValue( "a" ); ws.getRange2( "BBB4" ).setValue( "a" ); ws.getRange2( "BBB5" ).setValue( "b" ); ws.getRange2( "BBB6" ).setValue( "a" ); ws.getRange2( "BBB7" ).setValue( "b" ); ws.getRange2( "DDD2" ).setValue( "100" ); ws.getRange2( "DDD3" ).setValue( "100" ); ws.getRange2( "DDD4" ).setValue( "200" ); ws.getRange2( "DDD5" ).setValue( "300" ); ws.getRange2( "DDD6" ).setValue( "100" ); ws.getRange2( "DDD7" ).setValue( "400" ); oParser = new parserFormula( 'MAXIFS(AAA2:AAA7,BBB2:BBB7,"b",DDD2:DDD7,">100")', "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 50 ); oParser = new parserFormula( 'MAXIFS(AAA2:AAA6,BBB2:BBB6,"a",DDD2:DDD6,">200")', "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); testArrayFormulaEqualsValues("1,3.123,-4,#N/A;2,4,5,#N/A;#N/A,#N/A,#N/A,#N/A","MAXIFS(A1:C2,A1:C2,A1:C2,A1:C2, A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,0,0,#N/A;0,0,0,#N/A;#N/A,#N/A,#N/A,#N/A","MAXIFS(A1:C2,A1:C2,A1:A1,A1:C2,A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,0,0,#N/A;2,0,0,#N/A;#N/A,#N/A,#N/A,#N/A","MAXIFS(A1:C2,A1:C2,A1:A2,A1:C2,A1:C2,A1:C2,A1:C2)"); } ); test( "Test: \"MINIFS\"", function () { ws.getRange2( "AAA2" ).setValue( "10" ); ws.getRange2( "AAA3" ).setValue( "1" ); ws.getRange2( "AAA4" ).setValue( "100" ); ws.getRange2( "AAA5" ).setValue( "1" ); ws.getRange2( "AAA6" ).setValue( "1" ); ws.getRange2( "AAA7" ).setValue( "50" ); ws.getRange2( "BBB2" ).setValue( "b" ); ws.getRange2( "BBB3" ).setValue( "a" ); ws.getRange2( "BBB4" ).setValue( "a" ); ws.getRange2( "BBB5" ).setValue( "b" ); ws.getRange2( "BBB6" ).setValue( "a" ); ws.getRange2( "BBB7" ).setValue( "b" ); ws.getRange2( "DDD2" ).setValue( "100" ); ws.getRange2( "DDD3" ).setValue( "100" ); ws.getRange2( "DDD4" ).setValue( "200" ); ws.getRange2( "DDD5" ).setValue( "300" ); ws.getRange2( "DDD6" ).setValue( "100" ); ws.getRange2( "DDD7" ).setValue( "400" ); oParser = new parserFormula( 'MINIFS(AAA2:AAA7,BBB2:BBB7,"b",DDD2:DDD7,">100")', "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( 'MINIFS(AAA2:AAA6,BBB2:BBB6,"a",DDD2:DDD6,">200")', "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); testArrayFormulaEqualsValues("1,3.123,-4,#N/A;2,4,5,#N/A;#N/A,#N/A,#N/A,#N/A","MINIFS(A1:C2,A1:C2,A1:C2,A1:C2, A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,0,0,#N/A;0,0,0,#N/A;#N/A,#N/A,#N/A,#N/A","MINIFS(A1:C2,A1:C2,A1:A1,A1:C2,A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,0,0,#N/A;2,0,0,#N/A;#N/A,#N/A,#N/A,#N/A","MINIFS(A1:C2,A1:C2,A1:A2,A1:C2,A1:C2,A1:C2,A1:C2)"); } ); test( "Test: \"TEXT\"", function () { var culturelciddefault = AscCommon.g_oDefaultCultureInfo.LCID; oParser = new parserFormula( "TEXT(1234.567,\"$0.00\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "$1234.57" ); oParser = new parserFormula( "TEXT(0.125,\"0.0%\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "12.5%" ); testArrayFormula2("TEXT", 2, 2); //___________________________________ru______________________________________________ AscCommon.setCurrentCultureInfo(1049); oParser = new parserFormula( "TEXT(123,\"гг-мм-дд\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"чч:мм:сс\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); oParser = new parserFormula( "TEXT(123,\"основной\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "General" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //____________________________________en_____________________________________________ AscCommon.setCurrentCultureInfo(1025); oParser = new parserFormula( "TEXT(123,\"yy-mm-dd\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"hh:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); oParser = new parserFormula( "TEXT(123,\"general\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "General" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //__________________________________es________________________________________________ AscCommon.setCurrentCultureInfo(3082); oParser = new parserFormula( "TEXT(123,\"aa-mm-dd\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"hh:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); oParser = new parserFormula( "TEXT(123,\"estándar\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "General" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //__________________________________fi________________________________________________ AscCommon.setCurrentCultureInfo(1035); oParser = new parserFormula( "TEXT(123,\"vv-mm-pp\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"tt:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); oParser = new parserFormula( "TEXT(123,\"yleinen\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "General" ); oParser = new parserFormula( "TEXT(123,\"\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //__________________________________fy________________________________________________ AscCommon.setCurrentCultureInfo(1043); oParser = new parserFormula( "TEXT(123,\"jj-mm-dd\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"uu:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //__________________________________fr________________________________________________ AscCommon.setCurrentCultureInfo(1036); oParser = new parserFormula( "TEXT(123,\"jj-mm-aa\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"hh:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //_______________________________de___________________________________________________ AscCommon.setCurrentCultureInfo(1031); oParser = new parserFormula( "TEXT(123,\"jj-mm-tt\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"hh:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //_______________________________da____________________________________________________ AscCommon.setCurrentCultureInfo(1053); oParser = new parserFormula( "TEXT(123,\"åå-mm-dd\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"tt:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); AscCommon.setCurrentCultureInfo(culturelciddefault); //_____________________________special________________________________________________ AscCommon.setCurrentCultureInfo(1032); oParser = new parserFormula( "TEXT(123,\"εε-μμ-ηη\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"ωω:λλ:δδ\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); AscCommon.setCurrentCultureInfo(culturelciddefault); AscCommon.setCurrentCultureInfo(1029); oParser = new parserFormula( "TEXT(123,\"rr-mm-dd\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00-05-02" ); oParser = new parserFormula( "TEXT(123,\"hh:mm:ss\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "00:00:00" ); AscCommon.setCurrentCultureInfo(culturelciddefault); AscCommon.setCurrentCultureInfo(1041); oParser = new parserFormula( "TEXT(123,\"G/標準\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "General" ); AscCommon.setCurrentCultureInfo(culturelciddefault); } ); test( "Test: \"TEXTJOIN\"", function () { ws.getRange2( "A2" ).setValue( "Tulsa" ); ws.getRange2( "A3" ).setValue( "Seattle" ); ws.getRange2( "A4" ).setValue( "Iselin" ); ws.getRange2( "A5" ).setValue( "Fort Lauderdale" ); ws.getRange2( "A6" ).setValue( "Tempe" ); ws.getRange2( "A7" ).setValue( "end" ); ws.getRange2( "B2" ).setValue( "OK" ); ws.getRange2( "B3" ).setValue( "WA" ); ws.getRange2( "B4" ).setValue( "NJ" ); ws.getRange2( "B5" ).setValue( "FL" ); ws.getRange2( "B6" ).setValue( "AZ" ); ws.getRange2( "B7" ).setValue( "" ); ws.getRange2( "C2" ).setValue( "74133" ); ws.getRange2( "C3" ).setValue( "98109" ); ws.getRange2( "C4" ).setValue( "8830" ); ws.getRange2( "C5" ).setValue( "33309" ); ws.getRange2( "C6" ).setValue( "85285" ); ws.getRange2( "C7" ).setValue( "" ); ws.getRange2( "D2" ).setValue( "US" ); ws.getRange2( "D3" ).setValue( "US" ); ws.getRange2( "D4" ).setValue( "US" ); ws.getRange2( "D5" ).setValue( "US" ); ws.getRange2( "D6" ).setValue( "US" ); ws.getRange2( "D7" ).setValue( "" ); ws.getRange2( "A9" ).setValue( "," ); ws.getRange2( "B9" ).setValue( "," ); ws.getRange2( "C9" ).setValue( "," ); ws.getRange2( "D9" ).setValue( ";" ); oParser = new parserFormula( "TEXTJOIN(A9:D9, TRUE, A2:D7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Tulsa,OK,74133,US;Seattle,WA,98109,US;Iselin,NJ,8830,US;Fort Lauderdale,FL,33309,US;Tempe,AZ,85285,US;end" ); oParser = new parserFormula( "TEXTJOIN(A9:D9, FALSE, A2:D7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Tulsa,OK,74133,US;Seattle,WA,98109,US;Iselin,NJ,8830,US;Fort Lauderdale,FL,33309,US;Tempe,AZ,85285,US;end,,," ); oParser = new parserFormula( "TEXTJOIN(A2:D5, 1, B6:D6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "AZTulsa85285OKUS" ); testArrayFormulaEqualsValues("113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,#N/A;113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,#N/A;#N/A,#N/A,#N/A,#N/A", "TEXTJOIN(A1:C2,A1:C2,A1:C2,A1:C2, A1:C2)"); testArrayFormulaEqualsValues("113.1232-41224152113.1232-4122415,113.1232-41224152113.1232-4122415,113.1232-41224152113.1232-4122415,#N/A;113.1232-41224152113.1232-4122415,113.1232-41224152113.1232-4122415,113.1232-41224152113.1232-4122415,#N/A;#N/A,#N/A,#N/A,#N/A", "TEXTJOIN(A1:A2,A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445;113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445,113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-4224455113.1233.123-4-422445;#N/A,#N/A,#N/A,#N/A", "TEXTJOIN(A1:C2,A1:A2,A1:C2,A1:C2,A1:C2,A1:C2)"); } ); test("Test: \"WORKDAY\"", function () { oParser = new parserFormula("WORKDAY(DATE(2006,1,1),0)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 38718); oParser = new parserFormula("WORKDAY(DATE(2006,1,1),10)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 38730); oParser = new parserFormula("WORKDAY(DATE(2006,1,1),-10)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 38705); oParser = new parserFormula("WORKDAY(DATE(2006,1,1),20,{\"1-2-2006\",\"1-16-2006\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 38748); oParser = new parserFormula("WORKDAY(DATE(2017,10,6),1,DATE(2017,10,9))", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43018); oParser = new parserFormula("WORKDAY(DATE(2017,10,7),1,DATE(2017,10,9))", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43018); oParser = new parserFormula("WORKDAY(DATE(2017,9,25),-1,DATE(2017,9,10))", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43000); oParser = new parserFormula("WORKDAY(DATE(2017,9,25),-1,DATE(2017,9,10))", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43000); oParser = new parserFormula("WORKDAY(DATE(2017,9,20),-1,DATE(2017,9,10))", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 42997); oParser = new parserFormula("WORKDAY(DATE(2017,10,2),-1)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43007); oParser = new parserFormula("WORKDAY(DATE(2017,10,2),-1)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43007); oParser = new parserFormula("WORKDAY(DATE(2017,10,3),-3)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43006); oParser = new parserFormula("WORKDAY(DATE(2017,10,4),-2)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43010); oParser = new parserFormula("WORKDAY(DATE(2018,4,30),1,{\"5-1-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43222); oParser = new parserFormula("WORKDAY(DATE(2018,4,30),2,{\"5-1-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43224); oParser = new parserFormula("WORKDAY(DATE(2018,4,30),3,{\"5-1-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43227); oParser = new parserFormula("WORKDAY(DATE(2018,4,30),1,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43224); oParser = new parserFormula("WORKDAY(DATE(2018,4,30),3,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43228); oParser = new parserFormula("WORKDAY(DATE(2018,4,29),1,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43220); oParser = new parserFormula("WORKDAY(DATE(2018,4,29),2,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43224); oParser = new parserFormula("WORKDAY(DATE(2018,4,29),3,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43227); oParser = new parserFormula("WORKDAY(DATE(2018,4,29),-1,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43217); oParser = new parserFormula("WORKDAY(DATE(2018,4,29),-2,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43216); oParser = new parserFormula("WORKDAY(DATE(2018,4,29),0,{\"5-1-2018\", \"5-2-2018\",\"5-3-2018\"})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 43219); oParser = new parserFormula("WORKDAY({1,2,3},{1,2})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); oParser = new parserFormula("WORKDAY({1,2,3},1)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); oParser = new parserFormula("WORKDAY(1,{1,2})", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); oParser = new parserFormula("WORKDAY({1,2,3},1.123)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); oParser = new parserFormula("WORKDAY({1,2,3},-1.123)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula("WORKDAY({1,2,3},5)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 6); oParser = new parserFormula("WORKDAY(1,15)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 20); /*oParser = new parserFormula("WORKDAY(1,50)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 69); oParser = new parserFormula("WORKDAY(1,60)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 83); oParser = new parserFormula("WORKDAY(1,61)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 86);*/ //todo ms выдаёт ошибки /*ws.getRange2( "A101" ).setValue( "1" ); ws.getRange2( "B101" ).setValue( "3.123" ); ws.getRange2( "C101" ).setValue( "-4" ); oParser = new parserFormula("WORKDAY(A101:B101,A101:B101)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "#VALUE!"); oParser = new parserFormula("WORKDAY(A101,A101:B101)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "#VALUE!"); oParser = new parserFormula("WORKDAY(A101:B101,A101)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "#VALUE!"); oParser = new parserFormula("WORKDAY(A101,A101)", "A2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2);*/ }); test( "Test: \"WORKDAY.INTL\"", function () { oParser = new parserFormula( "WORKDAY.INTL(DATE(2012,1,1),30,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "WORKDAY.INTL(DATE(2012,1,1),90,11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 41013 ); oParser = new parserFormula( 'TEXT(WORKDAY.INTL(DATE(2012,1,1),30,17),"m/dd/yyyy")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "2/05/2012" ); oParser = new parserFormula( 'WORKDAY.INTL(151,8,"0000000")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 159 ); oParser = new parserFormula( 'WORKDAY.INTL(151,8,"0000000")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 159 ); oParser = new parserFormula( 'WORKDAY.INTL(159,8,"0011100")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 171 ); oParser = new parserFormula( 'WORKDAY.INTL(151,-18,"0000000")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 133 ); oParser = new parserFormula( 'WORKDAY.INTL(151,8,"1111111")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( 'WORKDAY.INTL(DATE(2006,1,1),20,1,{"1/2/2006","1/16/2006"})', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38748 ); oParser = new parserFormula( 'WORKDAY.INTL(DATE(2006,1,1),20,{"1/2/2006","1/16/2006"})', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( 'WORKDAY.INTL(DATE(2006,1,1),-20,1,{"1/2/2006",,"1/16/2006"})', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 38691 ); } ); test( "Test: \"TIME\"", function () { ws.getRange2( "A2" ).setValue( "12" ); ws.getRange2( "A3" ).setValue( "16" ); ws.getRange2( "B2" ).setValue( "0" ); ws.getRange2( "B3" ).setValue( "48" ); ws.getRange2( "C2" ).setValue( "0" ); ws.getRange2( "C3" ).setValue( "10" ); oParser = new parserFormula( "TIME(A2,B2,C2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0.5 ); oParser = new parserFormula( "TIME(A3,B3,C3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.7001157 ); oParser = new parserFormula( "TIME(1,1,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0423727 ); oParser = new parserFormula( "TIME(1.34,1,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0423727 ); oParser = new parserFormula( "TIME(1.34,1.456,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0423727 ); oParser = new parserFormula( "TIME(1.34,1.456,1.9)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0423727 ); oParser = new parserFormula( "TIME(-1.34,1.456,1.9)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("TIME", 3, 3); } ); test( "Test: \"TIMEVALUE\"", function () { oParser = new parserFormula( "timevalue(\"10:02:34\")", "A2", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - 0.4184490740740740 ) < dif ); oParser = new parserFormula( "timevalue(\"02-01-2006 10:15:29 AM\")", "A2", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - 0.4274189814823330 ) < dif ); oParser = new parserFormula( "timevalue(\"22:02\")", "A2", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - 0.9180555555555560 ) < dif ); testArrayFormula("TIMEVALUE"); } ); test( "Test: \"TYPE\"", function () { ws.getRange2( "A2" ).setValue( "Smith" ); oParser = new parserFormula( "TYPE(A2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( 'TYPE("Mr. "&A2)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( 'TYPE(2+A2)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 16 ); oParser = new parserFormula( '(2+A2)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( 'TYPE({1,2;3,4})', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 64 ); //TODO нужна другая функция для тестирования //testArrayFormula2("TYPE", 1, 1); } ); test( "Test: \"DAYS360\"", function () { oParser = new parserFormula( "DAYS360(DATE(2002,2,3),DATE(2005,5,31))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1198 ); oParser = new parserFormula( "DAYS360(DATE(2005,5,31),DATE(2002,2,3))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1197 ); oParser = new parserFormula( "DAYS360(DATE(2002,2,3),DATE(2005,5,31),FALSE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1198 ); oParser = new parserFormula( "DAYS360(DATE(2002,2,3),DATE(2005,5,31),TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1197 ); testArrayFormula2("DAYS360", 2, 3); } ); test( "Test: \"WEEKNUM\"", function () { oParser = new parserFormula( "WEEKNUM(DATE(2006,1,1))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2006,1,1),17)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2006,1,1),1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2006,1,1),21)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 52 ); oParser = new parserFormula( "WEEKNUM(DATE(2006,2,1),1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "WEEKNUM(DATE(2006,2,1),2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( "WEEKNUM(DATE(2006,2,1),11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( "WEEKNUM(DATE(2007,1,1),15)", "A2", ws );//понед ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2008,1,1),15)", "A2", ws );//втор ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2003,1,1),15)", "A2", ws );//сред ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2009,1,1),15)", "A2", ws );//чет ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2010,1,1),15)", "A2", ws );//пят ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2011,1,1),15)", "A2", ws );//суб ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2012,1,1),11)", "A2", ws );//вск ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2008,1,4),11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2008,1,10),11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "WEEKNUM(DATE(2008,1,11),11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "WEEKNUM(DATE(2008,1,17),11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "WEEKNUM(DATE(2008,1,18),11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "WEEKNUM(DATE(2008,1,24),11)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "WEEKNUM(DATE(2013,1,1),21)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "WEEKNUM(DATE(2013,1,7))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); testArrayFormula2("WEEKNUM", 1, 2, true); } ); test( "Test: \"ISOWEEKNUM\"", function () { ws.getRange2( "A2" ).setValue( "3/9/2012" ); oParser = new parserFormula( "ISOWEEKNUM(A2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( "ISOWEEKNUM(123)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 18 ); oParser = new parserFormula( "ISOWEEKNUM(120003)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30 ); oParser = new parserFormula( "ISOWEEKNUM(120003)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30 ); oParser = new parserFormula( "ISOWEEKNUM(-100)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "ISOWEEKNUM(1203)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 16 ); testArrayFormula2("ISOWEEKNUM",1,1); } ); test( "Test: \"WEEKDAY\"", function () { ws.getRange2( "A2" ).setValue( "2/14/2008" ); oParser = new parserFormula( "WEEKDAY(A2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "WEEKDAY(A2, 2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "WEEKDAY(A2, 3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); testArrayFormula2("WEEKDAY", 1, 2); } ); test( "Test: \"WEIBULL\"", function () { ws.getRange2( "A2" ).setValue( "105" ); ws.getRange2( "A3" ).setValue( "20" ); ws.getRange2( "A4" ).setValue( "100" ); oParser = new parserFormula( "WEIBULL(A2,A3,A4,TRUE)", "A20", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.929581 ); oParser = new parserFormula( "WEIBULL(A2,A3,A4,FALSE)", "A20", ws ); ok( oParser.parse(), "WEIBULL(A2,A3,A4,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.035589 ); testArrayFormula2("WEIBULL", 4, 4); } ); test( "Test: \"WEIBULL.DIST\"", function () { ws.getRange2( "A2" ).setValue( "105" ); ws.getRange2( "A3" ).setValue( "20" ); ws.getRange2( "A4" ).setValue( "100" ); oParser = new parserFormula( "WEIBULL.DIST(A2,A3,A4,TRUE)", "A20", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.929581 ); oParser = new parserFormula( "WEIBULL.DIST(A2,A3,A4,FALSE)", "A20", ws ); ok( oParser.parse(), "WEIBULL.DIST(A2,A3,A4,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.035589 ); testArrayFormula2("WEIBULL.DIST", 4, 4); } ); test( "Test: \"YEARFRAC\"", function () { function okWrapper( a, b ) { ok( Math.abs( a - b ) < dif ); } oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2006,3,26))", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.236111111 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,3,26),DATE(2006,1,1))", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.236111111 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2006,7,1))", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.5 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2007,9,1))", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 1.666666667 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2006,7,1),0)", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.5 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2006,7,1),1)", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.495890411 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2006,7,1),2)", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.502777778 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2006,7,1),3)", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.495890411 ); oParser = new parserFormula( "YEARFRAC(DATE(2006,1,1),DATE(2006,7,1),4)", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 0.5 ); oParser = new parserFormula( "YEARFRAC(DATE(2004,3,1),DATE(2006,3,1),1)", "A2", ws ); ok( oParser.parse() ); okWrapper( oParser.calculate().getValue(), 1.998175182481752 ); testArrayFormula2("YEARFRAC", 2, 3, true); } ); test( "Test: \"DATEDIF\"", function () { oParser = new parserFormula( "DATEDIF(DATE(2001,1,1),DATE(2003,1,1),\"Y\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "DATEDIF(DATE(2001,6,1),DATE(2002,8,15),\"D\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 440 ); oParser = new parserFormula( "DATEDIF(DATE(2001,6,1),DATE(2002,8,15),\"YD\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 75 ); oParser = new parserFormula( "DATEDIF(DATE(2001,6,1),DATE(2002,8,15),\"MD\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 14 ); testArrayFormula2("DATEDIF", 3, 3); } ); test( "Test: \"PRODUCT\"", function () { ws.getRange2( "A2" ).setValue( "5" ); ws.getRange2( "A3" ).setValue( "15" ); ws.getRange2( "A4" ).setValue( "30" ); oParser = new parserFormula( "PRODUCT(A2:A4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2250 ); oParser = new parserFormula( "PRODUCT(A2:A4, 2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4500 ); testArrayFormula2("PRODUCT", 1, 8, null, true); } ); test( "Test: \"SUMPRODUCT\"", function () { oParser = new parserFormula( "SUMPRODUCT({2,3})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "SUMPRODUCT({2,3},{4,5})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 23 ); oParser = new parserFormula( "SUMPRODUCT({2,3},{4,5},{2,2})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 46 ); oParser = new parserFormula( "SUMPRODUCT({2,3;4,5},{2,2;3,4})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 42 ); ws.getRange2( "N44" ).setValue( "1" ); ws.getRange2( "N45" ).setValue( "2" ); ws.getRange2( "N46" ).setValue( "3" ); ws.getRange2( "N47" ).setValue( "4" ); ws.getRange2( "O44" ).setValue( "5" ); ws.getRange2( "O45" ).setValue( "6" ); ws.getRange2( "O46" ).setValue( "7" ); ws.getRange2( "O47" ).setValue( "8" ); ws.getRange2( "P44" ).setValue( "9" ); ws.getRange2( "P45" ).setValue( "10" ); ws.getRange2( "P46" ).setValue( "11" ); ws.getRange2( "P47" ).setValue( "12" ); ws.getRange2( "P48" ).setValue( "" ); ws.getRange2( "P49" ).setValue( "" ); ws.getRange2( "N48" ).setValue( "0.456" ); ws.getRange2( "O48" ).setValue( "0.123212" ); oParser = new parserFormula( "SUMPRODUCT(N44:N47,O44:O47,P44:P47)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 780 ); oParser = new parserFormula( "SUMPRODUCT(N44:N47*O44:O47)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 70 ); oParser = new parserFormula( "SUMPRODUCT(SUM(N44:N47*O44:O47))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 70 ); oParser = new parserFormula( "SUMPRODUCT({1,2,TRUE,3})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( "SUMPRODUCT({1,2,FALSE,3})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( "SUMPRODUCT({TRUE,TRUE,FALSE,3})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "SUMPRODUCT(P48)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "SUMPRODUCT(P48, P44:P47)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "SUMPRODUCT(P48:P49)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "SUM(SUMPRODUCT(N44:N47*O44:O47))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 70 ); oParser = new parserFormula( "SUMPRODUCT(N44:O47*P44:P47)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 388 ); oParser = new parserFormula( "SUM(SUMPRODUCT(N44:O47*P44:P47))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 388 ); oParser = new parserFormula( "SUM(SUMPRODUCT(N44:O47))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUM(SUMPRODUCT(N44:O47))" ); strictEqual( oParser.calculate().getValue(), 36 ); oParser = new parserFormula( "SUMPRODUCT(YEAR(N45:O47))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 11400 ); oParser = new parserFormula( "SUMPRODUCT(MONTH(N45:O47))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( "SUMPRODUCT(DAY(N45:O47))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30 ); oParser = new parserFormula( "SUMPRODUCT(HOUR(N45:P48))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 12 ); oParser = new parserFormula( "SUMPRODUCT(MINUTE(N45:P48))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 113 ); oParser = new parserFormula( "SUMPRODUCT(SECOND(N45:P48))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 64 ); oParser = new parserFormula( "SUMPRODUCT(DAY(N44:P49))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 78 ); oParser = new parserFormula( "SUMPRODUCT(MONTH(N44:P49))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 18 ); oParser = new parserFormula( "SUMPRODUCT(YEAR(N44:P49))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 34200 ); oParser = new parserFormula( "SUMPRODUCT(({1,2,3})*({TRUE,TRUE,TRUE}))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); /*oParser = new parserFormula( "SUMPRODUCT(({1,2,3})*({TRUE;TRUE;TRUE;TRUE}))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 24 );*/ oParser = new parserFormula( "SUMPRODUCT({TRUE,TRUE,FALSE})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "SUMPRODUCT({1,2,3,3,TRUE})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 9 ); oParser = new parserFormula( "SUMPRODUCT({1,2,3,3,TRUE})+SUMPRODUCT({1,2,3,3,TRUE})", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT({1,2,3,3,TRUE})+SUMPRODUCT({1,2,3,3,TRUE})" ); strictEqual( oParser.calculate().getValue(), 18 ); oParser = new parserFormula( "SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE})", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE})" ); strictEqual( oParser.calculate().getValue(), 81 ); oParser = new parserFormula( "SUMPRODUCT(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}))" ); strictEqual( oParser.calculate().getValue(), 81 ); oParser = new parserFormula( "SUM(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUM(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}))" ); strictEqual( oParser.calculate().getValue(), 81 ); oParser = new parserFormula( "SUM(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}),1,2,3)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUM(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}),1,2,3)" ); strictEqual( oParser.calculate().getValue(), 87 ); oParser = new parserFormula( "SUM(SUMPRODUCT(N44:O47))+SUM(SUMPRODUCT(N44:O47))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUM(SUMPRODUCT(N44:O47))+SUM(SUMPRODUCT(N44:O47))" ); strictEqual( oParser.calculate().getValue(), 72 ); oParser = new parserFormula( "SUM(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}),SUMPRODUCT({1,2,3,3,TRUE}),2,SUMPRODUCT({1,2,3,3}))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUM(SUMPRODUCT({1,2,3,3,TRUE})*SUMPRODUCT({1,2,3,3,TRUE}),SUMPRODUCT({1,2,3,3,TRUE}),2,SUMPRODUCT({1,2,3,3}))" ); strictEqual( oParser.calculate().getValue(), 101 ); ws.getRange2( "A101" ).setValue( "5" ); ws.getRange2( "A102" ).setValue( "6" ); ws.getRange2( "A103" ).setValue( "7" ); ws.getRange2( "A104" ).setValue( "8" ); ws.getRange2( "A105" ).setValue( "9" ); ws.getRange2( "B101" ).setValue( "1" ); ws.getRange2( "B102" ).setValue( "1" ); ws.getRange2( "B103" ).setValue( "0" ); ws.getRange2( "B104" ).setValue( "1" ); ws.getRange2( "B105" ).setValue( "1" ); oParser = new parserFormula( "SUMPRODUCT((A101:A105)*((B101:B105)=1))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT((A101:A105)*((B101:B105)=1))" ); strictEqual( oParser.calculate().getValue(), 28 ); oParser = new parserFormula( "SUMPRODUCT((A101:A105)*((B101:B105)=1))+SUMPRODUCT((A101:A104)*((B101:B104)=1))+SUMPRODUCT((A101:A103)*((B101:B103)=1))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT((A101:A105)*((B101:B105)=1))+SUMPRODUCT((A101:A104)*((B101:B104)=1))+SUMPRODUCT((A101:A103)*((B101:B103)=1))" ); strictEqual( oParser.calculate().getValue(), 58 ); oParser = new parserFormula( "SUMPRODUCT(({3})*({TRUE,TRUE,TRUE,TRUE}))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT(({3})*({TRUE,TRUE,TRUE,TRUE}))" ); strictEqual( oParser.calculate().getValue(), 12 ); oParser = new parserFormula( "SUMPRODUCT(({3;2;2;2})*({TRUE;TRUE;TRUE;TRUE}))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT(({3;2;2;2})*({TRUE;TRUE;TRUE;TRUE}))" ); strictEqual( oParser.calculate().getValue(), 9 ); oParser = new parserFormula( "SUMPRODUCT(--ISNUMBER({5;6;7;1;2;3;4}))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT(--ISNUMBER({5;6;7;1;2;3;4}))" ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( "SUMPRODUCT(--ISNUMBER(SEARCH({5;6;7;1;2;3;4},123)))", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "SUMPRODUCT(--ISNUMBER(SEARCH({5;6;7;1;2;3;4},123)))" ); strictEqual( oParser.calculate().getValue(), 3 ); testArrayFormula2("SUMPRODUCT", 1, 8, null, true); } ); test( "Test: \"SINH\"", function () { oParser = new parserFormula( "SINH(0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "SINH(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ((Math.E - 1 / Math.E) / 2) ); testArrayFormula("SINH"); } ); test( "Test: \"SIGN\"", function () { oParser = new parserFormula( "SIGN(10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "SIGN(4-4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "SIGN(-0.00001)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1 ); testArrayFormula("SIGN"); } ); test( "Test: \"COSH\"", function () { oParser = new parserFormula( "COSH(0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COSH(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ((Math.E + 1 / Math.E) / 2) ); } ); test( "Test: \"IMCOSH\"", function () { oParser = new parserFormula( 'IMCOSH("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMCOSH("4+3i")' ); strictEqual( oParser.calculate().getValue(), "-27.03494560307422+3.8511533348117766i", 'IMCOSH("4+3i")' ); testArrayFormula("IMCOSH", true); } ); test( "Test: \"IMCOS\"", function () { oParser = new parserFormula( 'IMCOS("1+i")', "A2", ws ); ok( oParser.parse(), 'IMCOS("1+i")' ); strictEqual( oParser.calculate().getValue(), "0.8337300251311491-0.9888977057628651i", 'IMCOS("1+i")' ); testArrayFormula("IMCOS", true); } ); test( "Test: \"IMCOT\"", function () { oParser = new parserFormula( 'IMCOT("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMCOT("4+3i")' ); strictEqual( oParser.calculate().getValue(), "0.004901182394304475-0.9992669278059015i", 'IMCOT("4+3i")' ); testArrayFormula("IMCOT", true); } ); test( "Test: \"IMCSC\"", function () { oParser = new parserFormula( 'IMCSC("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMCSC("4+3i")' ); strictEqual( oParser.calculate().getValue(), "-0.0754898329158637+0.06487747137063551i", 'IMCSC("4+3i")' ); testArrayFormula("IMCSC", true); } ); test( "Test: \"IMCSCH\"", function () { oParser = new parserFormula( 'IMCSCH("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMCSCH("4+3i")' ); strictEqual( oParser.calculate().getValue(), "-0.03627588962862601-0.0051744731840193976i", 'IMCSCH("4+3i")' ); testArrayFormula("IMCSCH", true); } ); test( "Test: \"IMSIN\"", function () { oParser = new parserFormula( 'IMSIN("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMSIN("4+3i")' ); strictEqual( oParser.calculate().getValue(), "-7.619231720321408-6.548120040911002i", 'IMSIN("4+3i")' ); testArrayFormula("IMSIN", true); } ); test( "Test: \"IMSINH\"", function () { oParser = new parserFormula( 'IMSINH("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMSINH("4+3i")' ); strictEqual( oParser.calculate().getValue(), "-27.01681325800393+3.8537380379193764i", 'IMSINH("4+3i")' ); testArrayFormula("IMSINH", true); } ); test( "Test: \"IMSEC\"", function () { oParser = new parserFormula( 'IMSEC("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMSEC("4+3i")' ); strictEqual( oParser.calculate().getValue(), "-0.06529402785794705-0.07522496030277323i", 'IMSEC("4+3i")' ); testArrayFormula("IMSEC", true); } ); test( "Test: \"IMSECH\"", function () { oParser = new parserFormula( 'IMSECH("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMSECH("4+3i")' ); strictEqual( oParser.calculate().getValue(), "-0.03625349691586888-0.00516434460775318i", 'IMSECH("4+3i")' ); testArrayFormula("IMSECH", true); } ); test( "Test: \"IMTAN\"", function () { oParser = new parserFormula( 'IMTAN("4+3i")', "A2", ws ); ok( oParser.parse(), 'IMTAN("4+3i")' ); strictEqual( oParser.calculate().getValue(), "0.004908258067496062+1.000709536067233i", 'IMTAN("4+3i")' ); testArrayFormula("IMTAN", true); } ); test( "Test: \"IMSQRT\"", function () { oParser = new parserFormula( 'IMSQRT("1+i")', "A2", ws ); ok( oParser.parse(), 'IMSQRT("1+i")' ); //strictEqual( oParser.calculate().getValue(), "1.0986841134678098+0.4550898605622274i", 'IMSQRT("1+i")' ); testArrayFormula("IMSQRT", true); } ); test( "Test: \"IMREAL\"", function () { oParser = new parserFormula( 'IMREAL("6-9i")', "A2", ws ); ok( oParser.parse(), 'IMREAL("6-9i")' ); strictEqual( oParser.calculate().getValue(), 6, 'IMREAL("6-9i")' ); testArrayFormula("IMREAL", true); } ); test( "Test: \"IMLOG2\"", function () { //TODO в excel результат данной формулы - "2.32192809488736+1.33780421245098i" oParser = new parserFormula( 'IMLOG2("3+4i")', "A2", ws ); ok( oParser.parse(), 'IMLOG2("3+4i")' ); strictEqual( oParser.calculate().getValue(), "2.321928094887362+1.3378042124509761i", 'IMLOG2("3+4i")' ); testArrayFormula("IMLOG2", true); } ); test( "Test: \"IMLOG10\"", function () { //TODO в excel результат данной формулы - "0.698970004336019+0.402719196273373i" oParser = new parserFormula( 'IMLOG10("3+4i")', "A2", ws ); ok( oParser.parse(), 'IMLOG10("3+4i")' ); strictEqual( oParser.calculate().getValue(), "0.6989700043360186+0.40271919627337305i", 'IMLOG10("3+4i")' ); testArrayFormula("IMLOG10", true); } ); test( "Test: \"IMLN\"", function () { //TODO в excel результат данной формулы - "1.6094379124341+0.927295218001612i" oParser = new parserFormula( 'IMLN("3+4i")', "A2", ws ); ok( oParser.parse(), 'IMLN("3+4i")' ); strictEqual( oParser.calculate().getValue(), "1.6094379124341003+0.9272952180016123i", 'IMLN("3+4i")' ); testArrayFormula("IMLN", true); } ); test( "Test: \"IMEXP\"", function () { //TODO в excel результат данной формулы - "1.46869393991589+2.28735528717884i" oParser = new parserFormula( 'IMEXP("1+i")', "A2", ws ); ok( oParser.parse(), 'IMEXP("1+i")' ); strictEqual( oParser.calculate().getValue(), "1.4686939399158851+2.2873552871788423i", 'IMEXP("1+i")' ); testArrayFormula("IMEXP", true); } ); test( "Test: \"IMCONJUGATE\"", function () { oParser = new parserFormula( 'IMCONJUGATE("3+4i")', "A2", ws ); ok( oParser.parse(), 'IMCONJUGATE("3+4i")' ); strictEqual( oParser.calculate().getValue(), "3-4i", 'IMCONJUGATE("3+4i")' ); testArrayFormula("IMCONJUGATE", true); } ); test( "Test: \"IMARGUMENT\"", function () { oParser = new parserFormula( 'IMARGUMENT("3+4i")', "A2", ws ); ok( oParser.parse(), 'IMARGUMENT("3+4i")' ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.92729522, 'IMARGUMENT("3+4i")' ); testArrayFormula("IMARGUMENT", true); } ); test( "Test: \"IMAGINARY\"", function () { oParser = new parserFormula( 'IMAGINARY("3+4i")', "A2", ws ); ok( oParser.parse(), 'IMAGINARY("3+4i")' ); strictEqual( oParser.calculate().getValue(), 4, 'IMAGINARY("3+4i")' ); oParser = new parserFormula( 'IMAGINARY("0-j")', "A2", ws ); ok( oParser.parse(), 'IMAGINARY("0-j")' ); strictEqual( oParser.calculate().getValue(), -1, 'IMAGINARY("0-j")' ); oParser = new parserFormula( 'IMAGINARY("4")', "A2", ws ); ok( oParser.parse(), 'IMAGINARY("4")' ); strictEqual( oParser.calculate().getValue(), 0, 'IMAGINARY("4")' ); testArrayFormula("IMAGINARY", true); } ); test( "Test: \"IMDIV\"", function () { oParser = new parserFormula( 'IMDIV("-238+240i","10+24i")', "A2", ws ); ok( oParser.parse(), 'IMDIV("-238+240i","10+24i")' ); strictEqual( oParser.calculate().getValue(), "5+12i", 'IMDIV("-238+240i","10+24i")' ); testArrayFormula2("IMDIV", 2, 2, true); } ); test( "Test: \"IMPOWER\"", function () { testArrayFormula2("IMPOWER", 2, 2, true); } ); test( "Test: \"IMABS\"", function () { oParser = new parserFormula( 'IMABS("5+12i")', "A2", ws ); ok( oParser.parse(), 'IMABS("5+12i"' ); strictEqual( oParser.calculate().getValue(), 13, 'IMABS("5+12i"' ); testArrayFormula("IMABS", true); } ); test( "Test: \"IMSUB\"", function () { oParser = new parserFormula( 'IMSUB("13+4i","5+3i")', "A2", ws ); ok( oParser.parse(), 'IMSUB("13+4i","5+3i")' ); strictEqual( oParser.calculate().getValue(), "8+i", 'IMSUB("13+4i","5+3i")' ); testArrayFormula2("IMSUB", 2, 2, true); } ); test( "Test: \"TAN\"", function () { oParser = new parserFormula( "TAN(0.785)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 0.99920 ); oParser = new parserFormula( "TAN(45*PI()/180)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(1) - 0, 1 ); testArrayFormula("TAN"); } ); test( "Test: \"TANH\"", function () { oParser = new parserFormula( "TANH(0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "TANH(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), ((Math.E * Math.E - 1) / (Math.E * Math.E + 1)) ), true ); testArrayFormula("TANH"); } ); test( "Test: \"ATAN\"", function () { oParser = new parserFormula( 'ATAN(1)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.785398163 ); testArrayFormula("ATAN"); } ); test( "Test: \"ATAN2\"", function () { oParser = new parserFormula( 'ATAN2(1, 1)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.785398163); oParser = new parserFormula( 'ATAN2(-1, -1)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, -2.35619449); oParser = new parserFormula( 'ATAN2(-1, -1)*180/PI()', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -135); oParser = new parserFormula( 'DEGREES(ATAN2(-1, -1))', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -135); testArrayFormula2("ATAN2", 2, 2); } ); test( "Test: \"ATANH\"", function () { oParser = new parserFormula( 'ATANH(0.76159416)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 1.00000001 ); oParser = new parserFormula( 'ATANH(-0.1)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, -0.100335348 ); testArrayFormula("ATANH"); } ); test( "Test: \"XOR\"", function () { oParser = new parserFormula( 'XOR(3>0,2<9)', "A2", ws ); ok( oParser.parse(), 'XOR(3>0,2<9)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'XOR(3>0,2<9)' ); oParser = new parserFormula( 'XOR(3>12,4>6)', "A2", ws ); ok( oParser.parse(), 'XOR(3>12,4>6)' ); strictEqual( oParser.calculate().getValue(), "FALSE", 'XOR(3>12,4>6)' ); oParser = new parserFormula( 'XOR(3>12,4<6)', "A2", ws ); ok( oParser.parse(), 'XOR(3>12,4<6)' ); strictEqual( oParser.calculate().getValue(), "TRUE", 'XOR(3>12,4<6)' ); //area - specific for xor function //all empty - false result ws.getRange2( "A101" ).setValue( "5" ); ws.getRange2( "A102" ).setValue( "6" ); ws.getRange2( "A103" ).setValue( "test1" ); ws.getRange2( "A104" ).setValue( "" ); ws.getRange2( "A105" ).setValue( "false" ); ws.getRange2( "B101" ).setValue( "1" ); ws.getRange2( "B102" ).setValue( "1" ); ws.getRange2( "B103" ).setValue( "test2" ); ws.getRange2( "B104" ).setValue( "" ); ws.getRange2( "B105" ).setValue( "false" ); ws.getRange2( "B106" ).setValue( "#VALUE!" ); oParser = new parserFormula( 'XOR(A101:B102)', "A2", ws ); ok( oParser.parse(), 'XOR(A101:B102)' ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( 'XOR(A101:B103)', "A2", ws ); ok( oParser.parse(), 'XOR(A101:B103)' ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( 'XOR(A101:A103)', "A2", ws ); ok( oParser.parse(), 'XOR(A101:A103)' ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( 'XOR(A101:A104)', "A2", ws ); ok( oParser.parse(), 'XOR(A101:A104)' ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( 'XOR(A104:B104)', "A2", ws ); ok( oParser.parse(), 'XOR(A104:B104)' ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( 'XOR(A101:B104)', "A2", ws ); ok( oParser.parse(), 'XOR(A101:B104)' ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( 'XOR(A101:B105)', "A2", ws ); ok( oParser.parse(), 'XOR(A101:B105)' ); strictEqual( oParser.calculate().getValue(), "FALSE" ); oParser = new parserFormula( 'XOR(A101:A105)', "A2", ws ); ok( oParser.parse(), 'XOR(A101:A105)' ); strictEqual( oParser.calculate().getValue(), "TRUE" ); oParser = new parserFormula( 'XOR(B101:A106)', "A2", ws ); ok( oParser.parse(), 'XOR(B101:A106)' ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("XOR", 1, 8, null, true); } ); test( "Test: \"COMBIN\"", function () { oParser = new parserFormula( "COMBIN(8,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 28 ); oParser = new parserFormula( "COMBIN(10,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 210 ); oParser = new parserFormula( "COMBIN(6,5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( "COMBIN(-6,5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "COMBIN(3,5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "COMBIN(6,-5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); } ); test( "Test: \"FACTDOUBLE\"", function () { oParser = new parserFormula( "FACTDOUBLE(8)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 * 4 * 6 * 8 ); oParser = new parserFormula( "FACTDOUBLE(9)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 9 * 7 * 5 * 3 ); oParser = new parserFormula( "FACTDOUBLE(6.5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 * 4 * 2 ); oParser = new parserFormula( "FACTDOUBLE(-6)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "FACTDOUBLE(600)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula("FACTDOUBLE", true); } ); test( "Test: \"FACT\"", function () { oParser = new parserFormula( "FACT(5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 120 ); oParser = new parserFormula( "FACT(1.9)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "FACT(0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "FACT(-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "FACT(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); testArrayFormula("FACT"); } ); test( "Test: \"GCD\"", function () { oParser = new parserFormula( "LCM(5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "LCM(24.6,36.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 72 ); oParser = new parserFormula( "LCM(-1,39,52)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "LCM(0,39,52)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "LCM(24,36,15)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 360 ); testArrayFormula2("LCM", 1, 8, null, true); } ); test( "Test: \"RANDBETWEEN\"", function () { var res; oParser = new parserFormula( "RANDBETWEEN(1,6)", "A1", ws ); ok( oParser.parse() ); res = oParser.calculate().getValue(); ok( res >= 1 && res <= 6 ); oParser = new parserFormula( "RANDBETWEEN(-10,10)", "A1", ws ); ok( oParser.parse() ); res = oParser.calculate().getValue(); ok( res >= -10 && res <= 10 ); oParser = new parserFormula( "RANDBETWEEN(-25,-3)", "A1", ws ); ok( oParser.parse() ); res = oParser.calculate().getValue(); ok( res >= -25 && res <= -3 ); testArrayFormula2("RANDBETWEEN", 2, 2, true) } ); test( "Test: \"QUOTIENT\"", function () { oParser = new parserFormula( "QUOTIENT(1,6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "QUOTIENT(-10,3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -3 ); oParser = new parserFormula( "QUOTIENT(5,3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "QUOTIENT(5,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); testArrayFormula2("QUOTIENT", 2 , 2, true) } ); test( "Test: \"TRUNC\"", function () { oParser = new parserFormula( "TRUNC(PI())", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "TRUNC(PI(),3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3.141 ); oParser = new parserFormula( "TRUNC(PI(),-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "TRUNC(-PI(),2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -3.14 ); oParser = new parserFormula( "TRUNC(8.9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 8 ); oParser = new parserFormula( "TRUNC(-8.9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -8 ); oParser = new parserFormula( "TRUNC(0.45)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "TRUNC(43214)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 43214 ); oParser = new parserFormula( "TRUNC(43214, 10)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 43214 ); oParser = new parserFormula( "TRUNC(43214, -2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 43200 ); oParser = new parserFormula( "TRUNC(43214, -10)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "TRUNC(34123.123, -2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 34100 ); oParser = new parserFormula( "TRUNC(123.23423,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 123.2 ); testArrayFormula2("TRUNC", 1, 2); } ); test( "Test: \"MULTINOMIAL\"", function () { oParser = new parserFormula( "MULTINOMIAL(2,3,4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.fact( 2 + 3 + 4 ) / (Math.fact( 2 ) * Math.fact( 3 ) * Math.fact( 4 )) ); oParser = new parserFormula( "MULTINOMIAL(2,3,\"r\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "MULTINOMIAL(150,50)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("MULTINOMIAL", 1, 8, null, true); } ); test( "Test: \"MUNIT\"", function () { ws.getRange2( "A101" ).setValue( "5" ); ws.getRange2( "B102" ).setValue( "6" ); oParser = new parserFormula( "MUNIT(1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); oParser = new parserFormula( "MUNIT(-1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "MUNIT(1.123)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); oParser = new parserFormula( "MUNIT(2.123)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(1,1).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 0 ); oParser = new parserFormula( "MUNIT(A101)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(1,1).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 0 ); oParser = new parserFormula( "MUNIT(A101:B102)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "MUNIT({0,0;1,2;123,\"sdf\"})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), "#VALUE!" ); strictEqual( oParser.calculate().getElementRowCol(1,1).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(2,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(2,1).getValue(), "#VALUE!" ); oParser = new parserFormula( "MUNIT({12,2})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue(), 1 ); } ); test( "Test: \"SUMSQ\"", function () { oParser = new parserFormula( "SUMSQ(2.5,-3.6,2.4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2.5 * 2.5 + 3.6 * 3.6 + 2.4 * 2.4 ); oParser = new parserFormula( "SUMSQ(2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "SUMSQ(150,50)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 150 * 150 + 50 * 50 ); oParser = new parserFormula( "SUMSQ(150,\"f\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("SUMSQ", 1, 8, null, true); } ); test( "Test: \"ROMAN\"", function () { oParser = new parserFormula( "ROMAN(499,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "CDXCIX" ); oParser = new parserFormula( "ROMAN(499,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "LDVLIV" ); oParser = new parserFormula( "ROMAN(499,2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "XDIX" ); oParser = new parserFormula( "ROMAN(499,3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "VDIV" ); oParser = new parserFormula( "ROMAN(499,4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "ID" ); oParser = new parserFormula( "ROMAN(2013,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "MMXIII" ); oParser = new parserFormula( "ROMAN(2013,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "ROMAN(-2013,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "ROMAN(2499,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "MMLDVLIV" ); oParser = new parserFormula( "ROMAN(499)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "CDXCIX" ); testArrayFormula2("ROMAN", 2, 2); } ); test( "Test: \"SUMXMY2\"", function () { ws.getRange2( "A101" ).setValue( "5" ); ws.getRange2( "A102" ).setValue( "6" ); ws.getRange2( "A103" ).setValue( "test1" ); ws.getRange2( "A104" ).setValue( "" ); ws.getRange2( "A105" ).setValue( "false" ); ws.getRange2( "B101" ).setValue( "1" ); ws.getRange2( "B102" ).setValue( "1" ); ws.getRange2( "B103" ).setValue( "test2" ); ws.getRange2( "B104" ).setValue( "" ); ws.getRange2( "B105" ).setValue( "false" ); oParser = new parserFormula( "SUMXMY2(A101,B101)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 16 ); oParser = new parserFormula( "SUMXMY2(A103,B103)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "SUMXMY2(A101:A102,B101:B102)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 41 ); oParser = new parserFormula( "SUMXMY2(A105,B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "SUMXMY2({2,3,9,1,8,7,5},{6,5,11,7,5,4,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 79 ); oParser = new parserFormula( "SUMXMY2({2,3,9;1,8,7},{6,5,11;7,5,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 78 ); oParser = new parserFormula( "SUMXMY2(7,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); testArrayFormula2("SUMXMY2", 2, 2, null, true) } ); test( "Test: \"SUMX2MY2\"", function () { ws.getRange2( "A101" ).setValue( "5" ); ws.getRange2( "A102" ).setValue( "6" ); ws.getRange2( "A103" ).setValue( "test1" ); ws.getRange2( "A104" ).setValue( "" ); ws.getRange2( "A105" ).setValue( "false" ); ws.getRange2( "B101" ).setValue( "1" ); ws.getRange2( "B102" ).setValue( "1" ); ws.getRange2( "B103" ).setValue( "test2" ); ws.getRange2( "B104" ).setValue( "" ); ws.getRange2( "B105" ).setValue( "false" ); oParser = new parserFormula( "SUMX2MY2({2,3,9,1,8,7,5},{6,5,11,7,5,4,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -55 ); oParser = new parserFormula( "SUMX2MY2({2,3,9;1,8,7},{6,5,11;7,5,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -64 ); oParser = new parserFormula( "SUMX2MY2(7,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 24 ); oParser = new parserFormula( "SUMX2MY2(A101,B101)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 24 ); oParser = new parserFormula( "SUMX2MY2(A103,B103)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "SUMX2MY2(A101:A102,B101:B102)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 59 ); /*oParser = new parserFormula( "SUMX2MY2(A101:A105,B101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 59 );*/ oParser = new parserFormula( "SUMX2MY2(A105,B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("SUMX2MY2", 2, 2, null, true); } ); test( "Test: \"SUMX2PY2\"", function () { ws.getRange2( "A101" ).setValue( "5" ); ws.getRange2( "A102" ).setValue( "6" ); ws.getRange2( "A103" ).setValue( "test1" ); ws.getRange2( "A104" ).setValue( "" ); ws.getRange2( "A105" ).setValue( "false" ); ws.getRange2( "B101" ).setValue( "1" ); ws.getRange2( "B102" ).setValue( "1" ); ws.getRange2( "B103" ).setValue( "test2" ); ws.getRange2( "B104" ).setValue( "" ); ws.getRange2( "B105" ).setValue( "false" ); oParser = new parserFormula( "SUMX2PY2({2,3,9,1,8,7,5},{6,5,11,7,5,4,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 521 ); oParser = new parserFormula( "SUMX2PY2({2,3,9;1,8,7},{6,5,11;7,5,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 480 ); oParser = new parserFormula( "SUMX2PY2(7,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 74 ); oParser = new parserFormula( "SUMX2PY2(A101,B101)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 26 ); oParser = new parserFormula( "SUMX2PY2(A103,B103)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "SUMX2PY2(A101:A102,B101:B102)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 63 ); oParser = new parserFormula( "SUMX2PY2(A105,B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("SUMX2PY2", 2, 2, null, true); } ); test( "Test: \"SERIESSUM\"", function () { ws.getRange2( "A2" ).setValue( "1" ); ws.getRange2( "A3" ).setValue( numDivFact(-1, 2) ); ws.getRange2( "A4" ).setValue( numDivFact(1, 4) ); ws.getRange2( "A5" ).setValue( numDivFact(-1, 6) ); oParser = new parserFormula( "SERIESSUM(PI()/4,0,2,A2:A5)", "A7", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - (1 - 1 / 2 * Math.pow( Math.PI / 4, 2 ) + 1 / Math.fact( 4 ) * Math.pow( Math.PI / 4, 4 ) - 1 / Math.fact( 6 ) * Math.pow( Math.PI / 4, 6 )) ) < dif ); ws.getRange2( "B2" ).setValue( "1" ); ws.getRange2( "B3" ).setValue( numDivFact(-1, 3) ); ws.getRange2( "B4" ).setValue( numDivFact(1, 5) ); ws.getRange2( "B5" ).setValue( numDivFact(-1, 7) ); oParser = new parserFormula( "SERIESSUM(PI()/4,1,2,B2:B5)", "B7", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - (Math.PI / 4 - 1 / Math.fact( 3 ) * Math.pow( Math.PI / 4, 3 ) + 1 / Math.fact( 5 ) * Math.pow( Math.PI / 4, 5 ) - 1 / Math.fact( 7 ) * Math.pow( Math.PI / 4, 7 )) ) < dif ); //TODO нужна другая функция для тестирования //testArrayFormula2("SERIESSUM", 4, 4); } ); /* * Mathematical Function * */ test( "Test: \"CEILING\"", function () { oParser = new parserFormula( "CEILING(2.5,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "CEILING(-2.5,-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -4 ); oParser = new parserFormula( "CEILING(-2.5,2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -2 ); oParser = new parserFormula( "CEILING(1.5,0.1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1.5 ); oParser = new parserFormula( "CEILING(0.234,0.01)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0.24 ); testArrayFormula2("CEILING", 2, 2); } ); test( "Test: \"CELL\"", function () { ws.getRange2( "J2" ).setValue( "1" ); ws.getRange2( "J3" ).setValue( "test" ); ws.getRange2( "J4" ).setValue( "test2" ); oParser = new parserFormula( 'CELL("address",J3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "$J$3" ); oParser = new parserFormula( 'CELL("address",J3:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "$J$3" ); oParser = new parserFormula( 'CELL("col",J3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( 'CELL("col",J3:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( 'CELL("row",J3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( 'CELL("row",J3:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( 'CELL("color",J3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( 'CELL("color",J3:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( 'CELL("contents",J3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "test" ); oParser = new parserFormula( 'CELL("contents",J3:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "test" ); oParser = new parserFormula( 'CELL("contents",J4:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "test2" ); oParser = new parserFormula( 'CELL("contents",J5:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( 'CELL("prefix",J3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "'" ); /*oParser = new parserFormula( 'CELL("prefix",J2)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "" );*/ oParser = new parserFormula( 'CELL("prefix",J6:O12)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "" ); } ); /* * Statistical Function * */ test( "Test: \"AVEDEV\"", function () { oParser = new parserFormula( "AVEDEV(-3.5,1.4,6.9,-4.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4.075 ); oParser = new parserFormula( "AVEDEV({-3.5,1.4,6.9,-4.5})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4.075 ); oParser = new parserFormula( "AVEDEV(-3.5,1.4,6.9,-4.5,-0.3)", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 3.32 ), true ); testArrayFormula2("AVEDEV", 1, 8, null, true); } ); test( "Test: \"AVERAGE\"", function () { oParser = new parserFormula( "AVERAGE(1,2,3,4,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "AVERAGE({1,2;3,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2.5 ); oParser = new parserFormula( "AVERAGE({1,2,3,4,5},6,\"7\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "AVERAGE({1,\"2\",TRUE,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2.5 ); testArrayFormula2("AVERAGE", 1, 8, null, true); } ); test( "Test: \"AVERAGEA\"", function () { ws.getRange2( "E2" ).setValue( "TRUE" ); ws.getRange2( "E3" ).setValue( "FALSE" ); ws.getRange2( "F2" ).setValue( "10" ); ws.getRange2( "F3" ).setValue( "7" ); ws.getRange2( "F4" ).setValue( "9" ); ws.getRange2( "F5" ).setValue( "2" ); ws.getRange2( "F6" ).setValue( "Not available" ); ws.getRange2( "F7" ).setValue( "" ); oParser = new parserFormula( "AVERAGEA(10,E1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( "AVERAGEA(10,E2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5.5 ); oParser = new parserFormula( "AVERAGEA(10,E3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "AVERAGEA(F2:F6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5.6 ); oParser = new parserFormula( "AVERAGEA(F2:F5,F7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); testArrayFormula2("AVERAGEA", 1, 8, null, true); } ); test( "Test: \"AVERAGEIF\"", function () { ws.getRange2( "E2" ).setValue( "10" ); ws.getRange2( "E3" ).setValue( "20" ); ws.getRange2( "E4" ).setValue( "28" ); ws.getRange2( "E5" ).setValue( "30" ); oParser = new parserFormula( "AVERAGEIF(E2:E5,\">15\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 26 ); testArrayFormula2("AVERAGEIF", 2, 3, null, true); } ); test( "Test: \"AVERAGEIFS\"", function () { ws.getRange2( "E2" ).setValue( "Quiz" ); ws.getRange2( "E3" ).setValue( "Grade" ); ws.getRange2( "E4" ).setValue( "75" ); ws.getRange2( "E5" ).setValue( "94" ); ws.getRange2( "F2" ).setValue( "Quiz" ); ws.getRange2( "F3" ).setValue( "Grade" ); ws.getRange2( "F4" ).setValue( "85" ); ws.getRange2( "F5" ).setValue( "80" ); ws.getRange2( "G2" ).setValue( "Exam" ); ws.getRange2( "G3" ).setValue( "Grade" ); ws.getRange2( "G4" ).setValue( "87" ); ws.getRange2( "G5" ).setValue( "88" ); oParser = new parserFormula( "AVERAGEIFS(E2:E5,E2:E5,\">70\",E2:E5,\"<90\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 75 ); oParser = new parserFormula( "AVERAGEIFS(F2:F5,F2:F5,\">95\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "AVERAGEIFS(G2:G5,G2:G5,\"<>Incomplete\",G2:G5,\">80\")", "A3", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 87.5 ); testArrayFormulaEqualsValues("1,3.123,-4,#N/A;2,4,5,#N/A;#N/A,#N/A,#N/A,#N/A", "AVERAGEIFS(A1:C2,A1:C2,A1:C2,A1:C2, A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,#DIV/0!,#DIV/0!,#N/A;#DIV/0!,#DIV/0!,#DIV/0!,#N/A;#N/A,#N/A,#N/A,#N/A", "AVERAGEIFS(A1:C2,A1:C2,A1:A1,A1:C2,A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,#DIV/0!,#DIV/0!,#N/A;2,#DIV/0!,#DIV/0!,#N/A;#N/A,#N/A,#N/A,#N/A", "AVERAGEIFS(A1:C2,A1:C2,A1:A2,A1:C2,A1:C2,A1:C2,A1:C2)"); } ); test( "Test: \"AGGREGATE\"", function () { ws.getRange2( "A101" ).setValue( "TEST" ); ws.getRange2( "A102" ).setValue( "72" ); ws.getRange2( "A103" ).setValue( "30" ); ws.getRange2( "A104" ).setValue( "TEST2" ); ws.getRange2( "A105" ).setValue( "31" ); ws.getRange2( "A106" ).setValue( "96" ); ws.getRange2( "A107" ).setValue( "32" ); ws.getRange2( "A108" ).setValue( "81" ); ws.getRange2( "A109" ).setValue( "33" ); ws.getRange2( "A110" ).setValue( "53" ); ws.getRange2( "A111" ).setValue( "34" ); ws.getRange2( "B101" ).setValue( "82" ); ws.getRange2( "B102" ).setValue( "65" ); ws.getRange2( "B103" ).setValue( "95" ); ws.getRange2( "B104" ).setValue( "63" ); ws.getRange2( "B105" ).setValue( "53" ); ws.getRange2( "B106" ).setValue( "71" ); ws.getRange2( "B107" ).setValue( "55" ); ws.getRange2( "B108" ).setValue( "83" ); ws.getRange2( "B109" ).setValue( "100" ); ws.getRange2( "B110" ).setValue( "91" ); ws.getRange2( "B111" ).setValue( "89" ); oParser = new parserFormula( "AGGREGATE(4, 6, A101:A111)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 96 ); oParser = new parserFormula( "AGGREGATE(14, 6, A101:A111, 3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 72 ); oParser = new parserFormula( "AGGREGATE(15, 6, A101:A111)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "AGGREGATE(12, 6, A101:A111, B101:B111)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 68 ); oParser = new parserFormula( "AGGREGATE(12, 6, A101:A111, B101:B111)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 68 ); oParser = new parserFormula( "AGGREGATE(1,1,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 61.375); oParser = new parserFormula( "AGGREGATE(2,1,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 8); oParser = new parserFormula( "AGGREGATE(3,1,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10); oParser = new parserFormula( "AGGREGATE(4,1,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 95); oParser = new parserFormula( "AGGREGATE(5,3,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30); oParser = new parserFormula( "AGGREGATE(6,1,100)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!"); oParser = new parserFormula( "AGGREGATE(7,3,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 22.87192602); oParser = new parserFormula( "AGGREGATE(8,3,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 21.39472774); oParser = new parserFormula( "AGGREGATE(9,3,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 491); oParser = new parserFormula( "AGGREGATE(10,3,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 523.125); oParser = new parserFormula( "AGGREGATE(11,3,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 457.734375); oParser = new parserFormula( "AGGREGATE(12,3,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 64); oParser = new parserFormula( "AGGREGATE(13,3,A101:B105,A101:B105)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30); oParser = new parserFormula( "AGGREGATE(14,3,A101:B105,2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 82); oParser = new parserFormula( "AGGREGATE(15,3,A101:B105,2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 31); oParser = new parserFormula( "AGGREGATE(16,3,A101:B105,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 95); oParser = new parserFormula( "AGGREGATE(17,3,A101:B105,3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 74.5); oParser = new parserFormula( "AGGREGATE(18,3,A101:B105,0.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30.8); oParser = new parserFormula( "AGGREGATE(19,3,A101:B105,2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 64); } ); test( "Test: \"AND\"", function () { ws.getRange2( "A2" ).setValue( "50" ); ws.getRange2( "A3" ).setValue( "100" ); oParser = new parserFormula( "AND(A2>1,A2<100)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE"); oParser = new parserFormula( 'AND(A2<A3,A2<100)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE"); oParser = new parserFormula( 'AND(A3>1,A3<100)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE"); testArrayFormula2("AND", 1, 8, null, true); } ); test( "Test: \"OR\"", function () { ws.getRange2( "A2" ).setValue( "50" ); ws.getRange2( "A3" ).setValue( "100" ); oParser = new parserFormula( "AND(A2>1,A2<100)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE"); oParser = new parserFormula( 'AND(A2<A3,A2<100)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE"); oParser = new parserFormula( 'AND(A3<1,A3>100)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "FALSE"); testArrayFormula2("OR", 1, 8, null, true); } ); test( "Test: \"BINOMDIST\"", function () { function binomdist( x, n, p ) { x = parseInt( x ); n = parseInt( n ); return Math.binomCoeff( n, x ) * Math.pow( p, x ) * Math.pow( 1 - p, n - x ); } oParser = new parserFormula( "BINOMDIST(6,10,0.5,FALSE)", "A1", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - binomdist( 6, 10, 0.5 ) ) < dif ); oParser = new parserFormula( "BINOMDIST(6,10,0.5,TRUE)", "A1", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - (function () { var bm = 0; for ( var y = 0; y <= 6; y++ ) { bm += binomdist( y, 10, 0.5 ) } return bm; })() ) < dif ); oParser = new parserFormula( "BINOMDIST(11,10,0.5,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("BINOMDIST", 4, 4); } ); test( "Test: \"BINOM.DIST\"", function () { ws.getRange2( "A2" ).setValue( "6" ); ws.getRange2( "A3" ).setValue( "10" ); ws.getRange2( "A4" ).setValue( "0.5" ); oParser = new parserFormula( "BINOM.DIST(A2,A3,A4,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 7 ) - 0, 0.2050781); } ); test( "Test: \"BINOM.DIST.RANGE\"", function () { oParser = new parserFormula( "BINOM.DIST.RANGE(60,0.75,48)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 3 ) - 0, 0.084); oParser = new parserFormula( "BINOM.DIST.RANGE(60,0.75,45,50)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 3 ) - 0, 0.524); testArrayFormula2("BINOM.DIST.RANGE", 3, 4); } ); test( "Test: \"CONFIDENCE\"", function () { oParser = new parserFormula( "CONFIDENCE(0.4,5,12)", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 1.214775614397568 ), true ); oParser = new parserFormula( "CONFIDENCE(0.75,9,7)", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 1.083909233527114 ), true ); testArrayFormula2("CONFIDENCE", 3, 3); } ); test( "Test: \"CONFIDENCE.NORM\"", function () { ws.getRange2( "A2" ).setValue( "0.05" ); ws.getRange2( "A3" ).setValue( "2.5" ); ws.getRange2( "A4" ).setValue( "50" ); oParser = new parserFormula( "CONFIDENCE.NORM(A2,A3,A4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 6 ) - 0, 0.692952); } ); test( "Test: \"CONFIDENCE.T\"", function () { oParser = new parserFormula( "CONFIDENCE.T(0.05,1,50)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 9 ) - 0, 0.284196855); testArrayFormula2("CONFIDENCE.T", 3, 3); } ); test( "Test: \"CORREL\"", function () { oParser = new parserFormula( "CORREL({2.532,5.621;2.1,3.4},{5.32,2.765;5.2,\"f\"})", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), -0.988112020032211 ), true ); oParser = new parserFormula( "CORREL({1;2;3},{4;5;\"E\"})", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 1 ), true ); oParser = new parserFormula( "CORREL({1,2},{1,\"e\"})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); testArrayFormula2("CORREL", 2, 2, null, true) } ); test( "Test: \"COUNT\"", function () { ws.getRange2( "E2" ).setValue( "TRUE" ); oParser = new parserFormula( "COUNT({1,2,3,4,5})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "COUNT(1,2,3,4,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "COUNT({1,2,3,4,5},6,\"7\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( "COUNT(10,E150)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNT(10,E2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); ws.getRange2( "S5" ).setValue( "#DIV/0!" ); ws.getRange2( "S6" ).setValue( "TRUE" ); ws.getRange2( "S7" ).setValue( "qwe" ); ws.getRange2( "S8" ).setValue( "" ); ws.getRange2( "S9" ).setValue( "2" ); oParser = new parserFormula( "COUNT(S5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNT(S6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNT(S7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNT(S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNT(S5:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNT(S6:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); testArrayFormula2("COUNT", 2, 2, null, true); } ); test( "Test: \"COUNTA\"", function () { ws.getRange2( "E2" ).setValue( "TRUE" ); oParser = new parserFormula( "COUNTA({1,2,3,4,5})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "COUNTA(1,2,3,4,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "COUNTA({1,2,3,4,5},6,\"7\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( "COUNTA(10,E150)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNTA(10,E2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); ws.getRange2( "S5" ).setValue( "#DIV/0!" ); ws.getRange2( "S6" ).setValue( "TRUE" ); ws.getRange2( "S7" ).setValue( "qwe" ); ws.getRange2( "S8" ).setValue( "" ); ws.getRange2( "S9" ).setValue( "2" ); oParser = new parserFormula( "COUNTA(S5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNTA(S6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNTA(S7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNTA(S8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNTA(S5:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "COUNTA(S6:S9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); } ); test( "Test: \"COUNTIFS\"", function () { ws.getRange2( "A15" ).setValue( "Yes" ); ws.getRange2( "A16" ).setValue( "Yes" ); ws.getRange2( "A17" ).setValue( "Yes" ); ws.getRange2( "A18" ).setValue( "No" ); ws.getRange2( "B15" ).setValue( "No" ); ws.getRange2( "B16" ).setValue( "Yes" ); ws.getRange2( "B17" ).setValue( "Yes" ); ws.getRange2( "B18" ).setValue( "Yes" ); ws.getRange2( "C15" ).setValue( "No" ); ws.getRange2( "C16" ).setValue( "No" ); ws.getRange2( "C17" ).setValue( "Yes" ); ws.getRange2( "C18" ).setValue( "Yes" ); oParser = new parserFormula( "COUNTIFS(A15:C15,\"=Yes\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNTIFS(A15:A18,\"=Yes\",B15:B18,\"=Yes\")", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIFS(A18:C18,\"=Yes\",A16:C16,\"=Yes\")", "C1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); ws.getRange2( "D15" ).setValue( "1" ); ws.getRange2( "D16" ).setValue( "2" ); ws.getRange2( "D17" ).setValue( "3" ); ws.getRange2( "D18" ).setValue( "4" ); ws.getRange2( "D19" ).setValue( "5" ); ws.getRange2( "D20" ).setValue( "6" ); ws.getRange2( "E15" ).setValue( "5/1/2011" ); ws.getRange2( "E16" ).setValue( "5/2/2011" ); ws.getRange2( "E17" ).setValue( "5/3/2011" ); ws.getRange2( "E18" ).setValue( "5/4/2011" ); ws.getRange2( "E19" ).setValue( "5/5/2011" ); ws.getRange2( "E20" ).setValue( "5/6/2011" ); oParser = new parserFormula( "COUNTIFS(D15:D20,\"<6\",D15:D20,\">1\")", "D1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "COUNTIFS(D15:D20,\"<5\",E15:E20,\"<5/3/2011\")", "E1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIFS(D15:D20,\"<\" & D19,E15:E20,\"<\" & E17)", "E1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); testArrayFormulaEqualsValues("1,1,1,#N/A;1,1,1,#N/A;#N/A,#N/A,#N/A,#N/A", "COUNTIFS(A1:C2,A1:C2,A1:C2,A1:C2, A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,0,0,#N/A;1,0,0,#N/A;#N/A,#N/A,#N/A,#N/A", "COUNTIFS(A1:C2,A1:A2,A1:C2,A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("#VALUE!,#VALUE!,#VALUE!,#N/A;#VALUE!,#VALUE!,#VALUE!,#N/A;#N/A,#N/A,#N/A,#N/A", "COUNTIFS(A1:C2,A1:C2,A1:A2,A1:C2,A1:A2,A1:C2)"); } ); test( "Test: \"COUNTIF\"", function () { ws.getRange2( "A7" ).setValue( "3" ); ws.getRange2( "B7" ).setValue( "10" ); ws.getRange2( "C7" ).setValue( "7" ); ws.getRange2( "D7" ).setValue( "10" ); ws.getRange2( "A8" ).setValue( "apples" ); ws.getRange2( "B8" ).setValue( "oranges" ); ws.getRange2( "C8" ).setValue( "grapes" ); ws.getRange2( "D8" ).setValue( "melons" ); oParser = new parserFormula( "COUNTIF(A7:D7,\"=10\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(A7:D7,\">5\")", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "COUNTIF(A7:D7,\"<>10\")", "C1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(A8:D8,\"*es\")", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "COUNTIF(A8:D8,\"??a*\")", "B2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(A8:D8,\"*l*\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); wb.dependencyFormulas.unlockRecal(); ws.getRange2( "CC1" ).setValue( "1" ); ws.getRange2( "CC2" ).setValue( "0" ); ws.getRange2( "CC3" ).setValue( "1" ); ws.getRange2( "CC4" ).setValue( "true" ); ws.getRange2( "CC5" ).setValue( "=true" ); ws.getRange2( "CC6" ).setValue( "=true()" ); ws.getRange2( "CC7" ).setValue( "'true'" ); ws.getRange2( "CC8" ).setValue( "" ); /*oParser = new parserFormula( "COUNTIF(CC1:CC8,\"<\"&\"F007\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 );*/ oParser = new parserFormula( "COUNTIF(CC1:CC7, TRUE())", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "COUNTIF(CC1:CC7, TRUE)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "COUNTIF(CC1:CC7, 1)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(CC1:CC7, 0)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); ws.getRange2( "CC8" ).setValue( ">3" ); oParser = new parserFormula( "COUNTIF(CC8,\">3\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); ws.getRange2( "CC8" ).setValue( ">3" ); oParser = new parserFormula( "COUNTIF(CC8,\"=>3\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); ws.getRange2( "CC9" ).setValue( "=NA()" ); ws.getRange2( "CC10" ).setValue( "#N/A" ); oParser = new parserFormula( "COUNTIF(CC9:CC10,\"#N/A\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(CC9:CC10, NA())", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(CC9:CC10,\"=NA()\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNTIF(#REF!, 1)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "COUNTIF(CC1:CC8,\">=1\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(CC1:CC8,\"=1\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTIF(CC1:CC8,\"<1\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "COUNTIF(CC1:CC8,\">1\")", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNTIF(CC1:CC8,\"=\"&CC8)", "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); wb.dependencyFormulas.lockRecal(); ws.getRange2( "A22" ).setValue( "apples" ); ws.getRange2( "A23" ).setValue( "" ); ws.getRange2( "A24" ).setValue( "oranges" ); ws.getRange2( "A25" ).setValue( "peaches" ); ws.getRange2( "A26" ).setValue( "" ); ws.getRange2( "A27" ).setValue( "apples" ); oParser = new parserFormula( 'COUNTIF(A22:A27,"*es")', "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( 'COUNTIF(A22:A27,"?????es")', "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( 'COUNTIF(A22:A27,"*")', "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( 'COUNTIF(A22:A27,"<>"&"***")', "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( 'COUNTIF(A22:A27,"<>"&"*")', "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( 'COUNTIF(A22:A27,"<>"&"?")', "C2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); testArrayFormula2("COUNTIF", 2, 2) } ); test( "Test: \"COUNTBLANK\"", function () { ws.getRange2( "A22" ).setValue( "6" ); ws.getRange2( "A23" ).setValue( "" ); ws.getRange2( "A24" ).setValue( "4" ); ws.getRange2( "B22" ).setValue( "" ); ws.getRange2( "B23" ).setValue( "27" ); ws.getRange2( "B24" ).setValue( "34" ); oParser = new parserFormula( "COUNTBLANK(A22:B24)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "COUNTBLANK(A22)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "COUNTBLANK(A23)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); } ); test( "Test: \"COVAR\"", function () { oParser = new parserFormula( "COVAR({2.532,5.621;2.1,3.4},{5.32,2.765;5.2,6.7})", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), -1.3753740625 ), true ); oParser = new parserFormula( "COVAR({1,2},{4,5})", "B1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 0.25 ), true ); testArrayFormula2("COVAR", 2, 2, null, true) } ); test( "Test: \"COVARIANCE.P\"", function () { ws.getRange2( "AA1" ).setValue( "3" ); ws.getRange2( "AA2" ).setValue( "2" ); ws.getRange2( "AA4" ).setValue( "4" ); ws.getRange2( "AA5" ).setValue( "5" ); ws.getRange2( "AA6" ).setValue( "6" ); ws.getRange2( "BB1" ).setValue( "9" ); ws.getRange2( "BB2" ).setValue( "7" ); ws.getRange2( "BB4" ).setValue( "12" ); ws.getRange2( "BB5" ).setValue( "15" ); ws.getRange2( "BB6" ).setValue( "17" ); oParser = new parserFormula( "COVARIANCE.P(AA1:AA6, BB1:BB6)", "A1", ws ); ok( oParser.parse() ); strictEqual(oParser.calculate().getValue(), 5.2 ); testArrayFormula2("COVARIANCE.P", 2, 2, null, true); } ); test( "Test: \"COVARIANCE.S\"", function () { ws.getRange2( "AAA1" ).setValue( "2" ); ws.getRange2( "AAA2" ).setValue( "4" ); ws.getRange2( "AAA3" ).setValue( "8" ); ws.getRange2( "BBB1" ).setValue( "5" ); ws.getRange2( "BBB2" ).setValue( "11" ); ws.getRange2( "BBB3" ).setValue( "12" ); oParser = new parserFormula( "COVARIANCE.S({2,4,8},{5,11,12})", "A1", ws ); ok( oParser.parse() ); strictEqual(oParser.calculate().getValue().toFixed(9) - 0, 9.666666667 ); oParser = new parserFormula( "COVARIANCE.S(AAA1:AAA3,BBB1:BBB3)", "A1", ws ); ok( oParser.parse() ); strictEqual(oParser.calculate().getValue().toFixed(9) - 0, 9.666666667 ); testArrayFormula2("COVARIANCE.S", 2, 2, null, true); } ); test( "Test: \"CRITBINOM\"", function () { oParser = new parserFormula( "CRITBINOM(6,0.5,0.75)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "CRITBINOM(12,0.3,0.95)", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( "CRITBINOM(-12,0.3,0.95)", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "CRITBINOM(-12,1.3,0.95)", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "CRITBINOM(-12,-1.3,0.95)", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "CRITBINOM(-12,0,0.95)", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "CRITBINOM(-12,0.3,1.95)", "B1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("CRITBINOM", 3, 3); } ); test( "Test: \"CONCAT\"", function () { ws.getRange2( "AA1" ).setValue( "a1" ); ws.getRange2( "AA2" ).setValue( "a2" ); ws.getRange2( "AA4" ).setValue( "a4" ); ws.getRange2( "AA5" ).setValue( "a5" ); ws.getRange2( "AA6" ).setValue( "a6" ); ws.getRange2( "AA7" ).setValue( "a7" ); ws.getRange2( "BB1" ).setValue( "b1" ); ws.getRange2( "BB2" ).setValue( "b2" ); ws.getRange2( "BB4" ).setValue( "b4" ); ws.getRange2( "BB5" ).setValue( "b5" ); ws.getRange2( "BB6" ).setValue( "b6" ); ws.getRange2( "BB7" ).setValue( "b7" ); oParser = new parserFormula('CONCAT("The"," ","sun"," ","will"," ","come"," ","up"," ","tomorrow.")', "A3", ws); ok(oParser.parse(), "CONCAT(AA:AA, BB:BB)"); strictEqual(oParser.calculate().getValue(), "The sun will come up tomorrow.", "CONCAT(AA:AA, BB:BB)"); oParser = new parserFormula("CONCAT(AA:AA, BB:BB)", "A3", ws); ok(oParser.parse(), "CONCAT(AA:AA, BB:BB)"); strictEqual(oParser.calculate().getValue(), "a1a2a4a5a6a7b1b2b4b5b6b7", "CONCAT(AA:AA, BB:BB)"); oParser = new parserFormula("CONCAT(AA1:BB7)", "A3", ws); ok(oParser.parse(), "CONCAT(AA1:BB7)"); strictEqual(oParser.calculate().getValue(), "a1b1a2b2a4b4a5b5a6b6a7b7", "CONCAT(AA1:BB7)"); oParser = new parserFormula( 'CONCAT(TRUE,"test")', "A2", ws ); ok( oParser.parse(), 'CONCAT(TRUE,"test")' ); strictEqual( oParser.calculate().getValue(), "TRUEtest", 'CONCAT(TRUE,"test")'); testArrayFormulaEqualsValues("13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245;13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245;13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245,13.123-424513.123-424513.123-4245", "CONCAT(A1:C2,A1:C2,A1:C2)") }); test( "Test: \"CONCATENATE\"", function () { ws.getRange2( "AA2" ).setValue( "brook trout" ); ws.getRange2( "AA3" ).setValue( "species" ); ws.getRange2( "AA4" ).setValue( "32" ); ws.getRange2( "AB2" ).setValue( "Andreas" ); ws.getRange2( "AB3" ).setValue( "Fourth" ); ws.getRange2( "AC2" ).setValue( "Hauser" ); ws.getRange2( "AC3" ).setValue( "Pine" ); oParser = new parserFormula( 'CONCATENATE("Stream population for ", AA2, " ", AA3, " is ", AA4, "/mile.")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Stream population for brook trout species is 32/mile." ); oParser = new parserFormula( 'CONCATENATE(AB2, " ", AC2)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Andreas Hauser" ); oParser = new parserFormula( 'CONCATENATE(AC2, ", ", AB2)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Hauser, Andreas" ); oParser = new parserFormula( 'CONCATENATE(AB3, " & ", AC3)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Fourth & Pine" ); oParser = new parserFormula( 'CONCATENATE(TRUE,"test")', "A2", ws ); ok( oParser.parse(), 'CONCATENATE(TRUE,"test")' ); strictEqual( oParser.calculate().getValue(), "TRUEtest", 'CONCATENATE(TRUE,"test")'); testArrayFormula2("CONCATENATE", 1, 8); }); test( "Test: \"DEVSQ\"", function () { ws.getRange2( "A1" ).setValue( "5.6" ); ws.getRange2( "A2" ).setValue( "8.2" ); ws.getRange2( "A3" ).setValue( "9.2" ); oParser = new parserFormula( "DEVSQ(5.6,8.2,9.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 6.906666666666665 ), true ); oParser = new parserFormula( "DEVSQ({5.6,8.2,9.2})", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 6.906666666666665 ), true ); oParser = new parserFormula( "DEVSQ(5.6,8.2,\"9.2\")", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 3.379999999999999 ), true ); oParser = new parserFormula( "DEVSQ(" + ws.getName() + "!A1:A3)", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 6.906666666666665 ), true ); testArrayFormula2("DEVSQ", 1, 8, null, true); } ); test( "Test: \"EXPONDIST\"", function () { oParser = new parserFormula( "EXPONDIST(0.2,10,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 1.353352832366127 ), true ); oParser = new parserFormula( "EXPONDIST(2.3,1.5,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), 0.968254363621932 ), true ); testArrayFormula2("EXPONDIST", 3, 3); } ); test( "Test: \"SIN(3.1415926)\"", function () { oParser = new parserFormula( 'SIN(3.1415926)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), Math.sin( 3.1415926 ) ); testArrayFormula("SIN"); } ); test( "Test: \"EXP\"", function () { oParser = new parserFormula( "EXP(1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 2.71828183 ); oParser = new parserFormula( "EXP(2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 7.3890561 ); testArrayFormula("EXP"); } ); test( "Test: \"FISHER\"", function () { function fisher( x ) { return toFixed( 0.5 * Math.ln( (1 + x) / (1 - x) ) ); } oParser = new parserFormula( "FISHER(-0.43)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fisher( -.43 ) ); oParser = new parserFormula( "FISHER(0.578)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fisher( 0.578 ) ); oParser = new parserFormula( "FISHER(1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "FISHER(-1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula("FISHER"); } ); test( "Test: \"FISHERINV\"", function () { function fisherInv( x ) { return toFixed( ( Math.exp( 2 * x ) - 1 ) / ( Math.exp( 2 * x ) + 1 ) ); } oParser = new parserFormula( "FISHERINV(-0.43)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fisherInv( -.43 ) ); oParser = new parserFormula( "FISHERINV(0.578)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fisherInv( 0.578 ) ); oParser = new parserFormula( "FISHERINV(1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fisherInv( 1 ) ); oParser = new parserFormula( "FISHERINV(-1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fisherInv( -1 ) ); testArrayFormula("FISHERINV"); } ); test( "Test: \"FORECAST\"", function () { function forecast( fx, y, x ) { var fSumDeltaXDeltaY = 0, fSumSqrDeltaX = 0, _x = 0, _y = 0, xLength = 0; for ( var i = 0; i < x.length; i++ ) { _x += x[i]; _y += y[i]; xLength++; } _x /= xLength; _y /= xLength; for ( var i = 0; i < x.length; i++ ) { var fValX = x[i]; var fValY = y[i]; fSumDeltaXDeltaY += ( fValX - _x ) * ( fValY - _y ); fSumSqrDeltaX += ( fValX - _x ) * ( fValX - _x ); } return toFixed( _y + fSumDeltaXDeltaY / fSumSqrDeltaX * ( fx - _x ) ); } oParser = new parserFormula( "FORECAST(30,{6,7,9,15,21},{20,28,31,38,40})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), forecast( 30, [6, 7, 9, 15, 21], [20, 28, 31, 38, 40] ) ); } ); function putDataForForecastEts(){ ws.getRange2( 'A4' ).setValue( '39814' ); ws.getRange2( 'A5' ).setValue( '39845' ); ws.getRange2( 'A6' ).setValue( '39873' ); ws.getRange2( 'A7' ).setValue( '39904' ); ws.getRange2( 'A8' ).setValue( '39934' ); ws.getRange2( 'A9' ).setValue( '39965' ); ws.getRange2( 'A10' ).setValue( '39995' ); ws.getRange2( 'A11' ).setValue( '40026' ); ws.getRange2( 'A12' ).setValue( '40057' ); ws.getRange2( 'A13' ).setValue( '40087' ); ws.getRange2( 'A14' ).setValue( '40118' ); ws.getRange2( 'A15' ).setValue( '40148' ); ws.getRange2( 'A16' ).setValue( '40179' ); ws.getRange2( 'A17' ).setValue( '40210' ); ws.getRange2( 'A18' ).setValue( '40238' ); ws.getRange2( 'A19' ).setValue( '40269' ); ws.getRange2( 'A20' ).setValue( '40299' ); ws.getRange2( 'A21' ).setValue( '40330' ); ws.getRange2( 'A22' ).setValue( '40360' ); ws.getRange2( 'A23' ).setValue( '40391' ); ws.getRange2( 'A24' ).setValue( '40422' ); ws.getRange2( 'A25' ).setValue( '40452' ); ws.getRange2( 'A26' ).setValue( '40483' ); ws.getRange2( 'A27' ).setValue( '40513' ); ws.getRange2( 'A28' ).setValue( '40544' ); ws.getRange2( 'A29' ).setValue( '40575' ); ws.getRange2( 'A30' ).setValue( '40603' ); ws.getRange2( 'A31' ).setValue( '40634' ); ws.getRange2( 'A32' ).setValue( '40664' ); ws.getRange2( 'A33' ).setValue( '40695' ); ws.getRange2( 'A34' ).setValue( '40725' ); ws.getRange2( 'A35' ).setValue( '40756' ); ws.getRange2( 'A36' ).setValue( '40787' ); ws.getRange2( 'A37' ).setValue( '40817' ); ws.getRange2( 'A38' ).setValue( '40848' ); ws.getRange2( 'A39' ).setValue( '40878' ); ws.getRange2( 'A40' ).setValue( '40909' ); ws.getRange2( 'A41' ).setValue( '40940' ); ws.getRange2( 'A42' ).setValue( '40969' ); ws.getRange2( 'A43' ).setValue( '41000' ); ws.getRange2( 'A44' ).setValue( '41030' ); ws.getRange2( 'A45' ).setValue( '41061' ); ws.getRange2( 'A46' ).setValue( '41091' ); ws.getRange2( 'A47' ).setValue( '41122' ); ws.getRange2( 'A48' ).setValue( '41153' ); ws.getRange2( 'A49' ).setValue( '41183' ); ws.getRange2( 'A50' ).setValue( '41214' ); ws.getRange2( 'A51' ).setValue( '41244' ); ws.getRange2( 'A52' ).setValue( '41275' ); ws.getRange2( 'A53' ).setValue( '41306' ); ws.getRange2( 'A54' ).setValue( '41334' ); ws.getRange2( 'A55' ).setValue( '41365' ); ws.getRange2( 'A56' ).setValue( '41395' ); ws.getRange2( 'A57' ).setValue( '41426' ); ws.getRange2( 'A58' ).setValue( '41456' ); ws.getRange2( 'A59' ).setValue( '41487' ); ws.getRange2( 'A60' ).setValue( '41518' ); ws.getRange2( 'B4' ).setValue( '2644539' ); ws.getRange2( 'B5' ).setValue( '2359800' ); ws.getRange2( 'B6' ).setValue( '2925918' ); ws.getRange2( 'B7' ).setValue( '3024973' ); ws.getRange2( 'B8' ).setValue( '3177100' ); ws.getRange2( 'B9' ).setValue( '3419595' ); ws.getRange2( 'B10' ).setValue( '3649702' ); ws.getRange2( 'B11' ).setValue( '3650668' ); ws.getRange2( 'B12' ).setValue( '3191526' ); ws.getRange2( 'B13' ).setValue( '3249428' ); ws.getRange2( 'B14' ).setValue( '2971484' ); ws.getRange2( 'B15' ).setValue( '3074209' ); ws.getRange2( 'B16' ).setValue( '2785466' ); ws.getRange2( 'B17' ).setValue( '2515361' ); ws.getRange2( 'B18' ).setValue( '3105958' ); ws.getRange2( 'B19' ).setValue( '3139059' ); ws.getRange2( 'B20' ).setValue( '3380355' ); ws.getRange2( 'B21' ).setValue( '3612886' ); ws.getRange2( 'B22' ).setValue( '3765824' ); ws.getRange2( 'B23' ).setValue( '3771842' ); ws.getRange2( 'B24' ).setValue( '3356365' ); ws.getRange2( 'B25' ).setValue( '3490100' ); ws.getRange2( 'B26' ).setValue( '3163659' ); ws.getRange2( 'B27' ).setValue( '3167124' ); ws.getRange2( 'B28' ).setValue( '2883810' ); ws.getRange2( 'B29' ).setValue( '2610667' ); ws.getRange2( 'B30' ).setValue( '3129205' ); ws.getRange2( 'B31' ).setValue( '3200527' ); ws.getRange2( 'B32' ).setValue( '3547804' ); ws.getRange2( 'B33' ).setValue( '3766323' ); ws.getRange2( 'B34' ).setValue( '3935589' ); ws.getRange2( 'B35' ).setValue( '3917884' ); ws.getRange2( 'B36' ).setValue( '3564970' ); ws.getRange2( 'B37' ).setValue( '3602455' ); ws.getRange2( 'B38' ).setValue( '3326859' ); ws.getRange2( 'B39' ).setValue( '3441693' ); ws.getRange2( 'B40' ).setValue( '3211600' ); ws.getRange2( 'B41' ).setValue( '2998119' ); ws.getRange2( 'B42' ).setValue( '3472440' ); ws.getRange2( 'B43' ).setValue( '3563007' ); ws.getRange2( 'B44' ).setValue( '3820570' ); ws.getRange2( 'B45' ).setValue( '4107195' ); ws.getRange2( 'B46' ).setValue( '4284443' ); ws.getRange2( 'B47' ).setValue( '4356216' ); ws.getRange2( 'B48' ).setValue( '3819379' ); ws.getRange2( 'B49' ).setValue( '3844987' ); ws.getRange2( 'B50' ).setValue( '3478890' ); ws.getRange2( 'B51' ).setValue( '3443039' ); ws.getRange2( 'B52' ).setValue( '3204637' ); ws.getRange2( 'B53' ).setValue( '2966477' ); ws.getRange2( 'B54' ).setValue( '3593364' ); ws.getRange2( 'B55' ).setValue( '3604104' ); ws.getRange2( 'B56' ).setValue( '3933016' ); ws.getRange2( 'B57' ).setValue( '4146797' ); ws.getRange2( 'B58' ).setValue( '4176486' ); ws.getRange2( 'B59' ).setValue( '4347059' ); ws.getRange2( 'B60' ).setValue( '3781168' ); ws.getRange2( 'A61' ).setValue( '41548' ); ws.getRange2( 'A62' ).setValue( '41579' ); ws.getRange2( 'A63' ).setValue( '41609' ); ws.getRange2( 'A64' ).setValue( '41640' ); ws.getRange2( 'A65' ).setValue( '41671' ); ws.getRange2( 'A66' ).setValue( '41699' ); ws.getRange2( 'A67' ).setValue( '41730' ); ws.getRange2( 'A68' ).setValue( '41760' ); ws.getRange2( 'A69' ).setValue( '41791' ); ws.getRange2( 'A70' ).setValue( '41821' ); ws.getRange2( 'A71' ).setValue( '41852' ); ws.getRange2( 'A72' ).setValue( '41883' ); ws.getRange2( 'A73' ).setValue( '41913' ); ws.getRange2( 'A74' ).setValue( '41944' ); ws.getRange2( 'A75' ).setValue( '41974' ); ws.getRange2( 'A76' ).setValue( '42005' ); ws.getRange2( 'A77' ).setValue( '42036' ); ws.getRange2( 'A78' ).setValue( '42064' ); ws.getRange2( 'A79' ).setValue( '42095' ); ws.getRange2( 'A80' ).setValue( '42125' ); ws.getRange2( 'A81' ).setValue( '42156' ); ws.getRange2( 'A82' ).setValue( '42186' ); ws.getRange2( 'A83' ).setValue( '42217' ); ws.getRange2( 'A84' ).setValue( '42248' ); } test( "Test: \"FORECAST.ETS\"", function () { //результаты данного теста соответсвуют результатам LO, но отличаются от MS!!! putDataForForecastEts(); oParser = new parserFormula( "FORECAST.ETS(A61,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3868499.49723621); oParser = new parserFormula( "FORECAST.ETS(A62,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3560200.99816396); oParser = new parserFormula( "FORECAST.ETS(A63,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3619491.6524986); oParser = new parserFormula( "FORECAST.ETS(A64,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3397521.44972895); oParser = new parserFormula( "FORECAST.ETS(A65,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3152698.4854144); oParser = new parserFormula( "FORECAST.ETS(A66,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3704079.5812005); oParser = new parserFormula( "FORECAST.ETS(A67,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3747546.50043675); oParser = new parserFormula( "FORECAST.ETS(A68,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4042011.75785885); oParser = new parserFormula( "FORECAST.ETS(A69,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4250095.33429725); oParser = new parserFormula( "FORECAST.ETS(A70,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4360538.1411926); oParser = new parserFormula( "FORECAST.ETS(A71,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4463640.2710391); oParser = new parserFormula( "FORECAST.ETS(A72,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3963675.88150212); oParser = new parserFormula( "FORECAST.ETS(A73,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4028087.58056954); oParser = new parserFormula( "FORECAST.ETS(A74,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3719789.0814973); oParser = new parserFormula( "FORECAST.ETS(A75,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3779079.73583193); oParser = new parserFormula( "FORECAST.ETS(A76,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3557109.53306228); oParser = new parserFormula( "FORECAST.ETS(A77,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3312286.56874774); oParser = new parserFormula( "FORECAST.ETS(A78,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3863667.66453383); oParser = new parserFormula( "FORECAST.ETS(A79,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 3907134.58377009); oParser = new parserFormula( "FORECAST.ETS(A80,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4201599.84119218); oParser = new parserFormula( "FORECAST.ETS(A81,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4409683.41763059); oParser = new parserFormula( "FORECAST.ETS(A82,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4520126.22452593); oParser = new parserFormula( "FORECAST.ETS(A83,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4623228.35437243); oParser = new parserFormula( "FORECAST.ETS(A84,B4:B60,A4:A60,1,1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 8 ) - 0, 4123263.96483545); } ); test( "Test: \"FORECAST.ETS.SEASONALITY\"", function () { //результаты данного теста соответсвуют результатам LO, но отличаются от MS!!! putDataForForecastEts(); oParser = new parserFormula("FORECAST.ETS.SEASONALITY(B4:B60,A4:A60,1,1)", "A1", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 12); } ); test( "Test: \"FORECAST.ETS.STAT\"", function () { //результаты данного теста соответсвуют результатам LO, но отличаются от MS!!! putDataForForecastEts(); oParser = new parserFormula("FORECAST.ETS.STAT(B4:B60,A4:A60,1,1)", "A1", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue().toFixed( 8 ) - 0, 0.65234375); } ); test( "Test: \"FORECAST.LINEAR\"", function () { oParser = new parserFormula( "FORECAST(30,{6,7,9,15,21},{20,28,31,38,40})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 13 ) - 0, 10.6072530864198); } ); test( "FORMULATEXT", function () { wb.dependencyFormulas.unlockRecal(); ws.getRange2( "S101" ).setValue( "=TODAY()" ); ws.getRange2( "S102" ).setValue( "" ); ws.getRange2( "S103" ).setValue( "=1+1" ); oParser = new parserFormula( "FORMULATEXT(S101)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "=TODAY()" ); oParser = new parserFormula( "FORMULATEXT(S101:S102)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "=TODAY()" ); oParser = new parserFormula( "FORMULATEXT(S102)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "FORMULATEXT(S100:105)", "A1", ws ); ok( oParser.parse() ); //"#N/A" - в ms excel strictEqual( oParser.calculate().getValue(), newFormulaParser ? "#N/A" : "#VALUE!"); oParser = new parserFormula( "FORMULATEXT(S103)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "=1+1" ); oParser = new parserFormula( "FORMULATEXT(#REF!)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); wb.dependencyFormulas.lockRecal(); testArrayFormulaEqualsValues("#N/A,#N/A,#N/A,#N/A;#N/A,#N/A,#N/A,#N/A;#N/A,#N/A,#N/A,#N/A", "FORMULATEXT(A1:C2)"); } ); test( "Test: \"FREQUENCY\"", function () { ws.getRange2( "A202" ).setValue( "79" ); ws.getRange2( "A203" ).setValue( "85" ); ws.getRange2( "A204" ).setValue( "78" ); ws.getRange2( "A205" ).setValue( "85" ); ws.getRange2( "A206" ).setValue( "50" ); ws.getRange2( "A207" ).setValue( "81" ); ws.getRange2( "A208" ).setValue( "95" ); ws.getRange2( "A209" ).setValue( "88" ); ws.getRange2( "A210" ).setValue( "97" ); ws.getRange2( "B202" ).setValue( "70" ); ws.getRange2( "B203" ).setValue( "89" ); ws.getRange2( "B204" ).setValue( "79" ); oParser = new parserFormula( "FREQUENCY(A202:A210,B202:B204)", "A201", ws ); ok( oParser.parse() ); var a = oParser.calculate(); strictEqual( a.getElement( 0 ).getValue(), 1 ); strictEqual( a.getElement( 1 ).getValue(), 2 ); strictEqual( a.getElement( 2 ).getValue(), 4 ); strictEqual( a.getElement( 3 ).getValue(), 2 ); } ); test( "Test: \"GAMMALN\"", function () { oParser = new parserFormula( "GAMMALN(4.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed( 14 ) - 0, 2.45373657084244 ); oParser = new parserFormula( "GAMMALN(-4.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula("GAMMALN"); } ); test( "Test: \"GAMMALN.PRECISE\"", function () { oParser = new parserFormula( "GAMMALN.PRECISE(4)", "A1", ws ); ok( oParser.parse(), "GAMMALN.PRECISE(4)" ); strictEqual( oParser.calculate().getValue().toFixed( 7 ) - 0, 1.7917595, "GAMMALN.PRECISE(4)" ); oParser = new parserFormula( "GAMMALN.PRECISE(-4.5)", "A1", ws ); ok( oParser.parse(), "GAMMALN.PRECISE(-4.5)" ); strictEqual( oParser.calculate().getValue(), "#NUM!", "GAMMALN.PRECISE(-4.5)" ); testArrayFormula2("GAMMALN.PRECISE", 1, 1); } ); test( "Test: \"GEOMEAN\"", function () { function geommean( x ) { var s1 = 0, _x = 1, xLength = 0, _tx; for ( var i = 0; i < x.length; i++ ) { _x *= x[i]; } return Math.pow( _x, 1 / x.length ) } oParser = new parserFormula( "GEOMEAN(10.5,5.3,2.9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), geommean( [10.5, 5.3, 2.9] ) ); oParser = new parserFormula( "GEOMEAN(10.5,{5.3,2.9},\"12\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), geommean( [10.5, 5.3, 2.9, 12] ) ); oParser = new parserFormula( "GEOMEAN(10.5,{5.3,2.9},\"12\",0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); } ); test( "Test: \"HARMEAN\"", function () { function harmmean( x ) { var _x = 0, xLength = 0; for ( var i = 0; i < x.length; i++ ) { _x += 1 / x[i]; xLength++; } return xLength / _x; } oParser = new parserFormula( "HARMEAN(10.5,5.3,2.9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), harmmean( [10.5, 5.3, 2.9] ) ); oParser = new parserFormula( "HARMEAN(10.5,{5.3,2.9},\"12\")", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), harmmean( [10.5, 5.3, 2.9, 12] ) ); oParser = new parserFormula( "HARMEAN(10.5,{5.3,2.9},\"12\",0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("HARMEAN", 1, 8, null, true); } ); test( "Test: \"HYPGEOMDIST\"", function () { function hypgeomdist( x, n, M, N ) { return toFixed( Math.binomCoeff( M, x ) * Math.binomCoeff( N - M, n - x ) / Math.binomCoeff( N, n ) ); } oParser = new parserFormula( "HYPGEOMDIST(1,4,8,20)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), hypgeomdist( 1, 4, 8, 20 ) ); oParser = new parserFormula( "HYPGEOMDIST(1,4,8,20)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), hypgeomdist( 1, 4, 8, 20 ) ); oParser = new parserFormula( "HYPGEOMDIST(-1,4,8,20)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "HYPGEOMDIST(5,4,8,20)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("HYPGEOMDIST", 4, 4); } ); test( "Test: \"HYPGEOM.DIST\"", function () { oParser = new parserFormula( "HYPGEOM.DIST(1,4,8,20,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(4) - 0, 0.4654 ); oParser = new parserFormula( "HYPGEOM.DIST(1,4,8,20,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(4) - 0, 0.3633 ); oParser = new parserFormula( "HYPGEOM.DIST(2,2,3,40,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.003846154); oParser = new parserFormula( "HYPGEOM.DIST(2,3,3,40,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.999898785); oParser = new parserFormula( "HYPGEOM.DIST(1,2,3,4,5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue() - 0, 0.5); testArrayFormula2("HYPGEOM.DIST", 5, 5); } ); test( "Test: \"HYPLINK\"", function () { ws.getRange2( "D101" ).setValue( "" ); ws.getRange2( "D102" ).setValue( "123" ); oParser = new parserFormula( 'HYPERLINK("http://example.microsoft.com/report/budget report.xlsx", "Click for report")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Click for report" ); strictEqual( oParser.value.hyperlink, "http://example.microsoft.com/report/budget report.xlsx" ); oParser = new parserFormula( 'HYPERLINK("[http://example.microsoft.com/report/budget report.xlsx]Annual!F10", D1)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue() - 0, 0 ); strictEqual( oParser.value.hyperlink, "[http://example.microsoft.com/report/budget report.xlsx]Annual!F10" ); oParser = new parserFormula( 'HYPERLINK("http://example.microsoft.com/Annual Report.docx]QrtlyProfits", "Quarterly Profit Report")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Quarterly Profit Report" ); strictEqual( oParser.value.hyperlink, 'http://example.microsoft.com/Annual Report.docx]QrtlyProfits' ); oParser = new parserFormula( 'HYPERLINK("\\FINANCE\Statements\1stqtr.xlsx",D101)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue() - 0, 0 ); strictEqual( oParser.value.hyperlink, '\\FINANCE\Statements\1stqtr.xlsx' ); oParser = new parserFormula( 'HYPERLINK("http://test.com")', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "http://test.com" ); strictEqual( oParser.value.hyperlink, "http://test.com" ); oParser = new parserFormula( 'HYPERLINK(D101,111)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 111 ); strictEqual( oParser.value.hyperlink - 0, 0 ); oParser = new parserFormula( 'HYPERLINK(D102,111)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 111 ); strictEqual( oParser.value.hyperlink, "123" ); oParser = new parserFormula( 'HYPERLINK(D102)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "123" ); strictEqual( oParser.value.hyperlink - 0, 123 ); oParser = new parserFormula( 'HYPERLINK(D101,TRUE)', "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TRUE" ); strictEqual( oParser.value.hyperlink - 0, 0 ); } ); test( "Test: \"HOUR\"", function () { ws.getRange2( "A202" ).setValue( "0.75" ); ws.getRange2( "A203" ).setValue( "7/18/2011 7:45" ); ws.getRange2( "A204" ).setValue( "4/21/2012" ); oParser = new parserFormula( "HOUR(A202)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 18 ); oParser = new parserFormula( "HOUR(A203)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( "HOUR(A204)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); testArrayFormula2("HOUR", 1, 1); } ); test( "Test: \"INTERCEPT\"", function () { function intercept( y, x ) { var fSumDeltaXDeltaY = 0, fSumSqrDeltaX = 0, _x = 0, _y = 0, xLength = 0; for ( var i = 0; i < x.length; i++ ) { _x += x[i]; _y += y[i]; xLength++; } _x /= xLength; _y /= xLength; for ( var i = 0; i < x.length; i++ ) { var fValX = x[i]; var fValY = y[i]; fSumDeltaXDeltaY += ( fValX - _x ) * ( fValY - _y ); fSumSqrDeltaX += ( fValX - _x ) * ( fValX - _x ); } return toFixed( _y - fSumDeltaXDeltaY / fSumSqrDeltaX * _x ); } oParser = new parserFormula( "INTERCEPT({6,7,9,15,21},{20,28,31,38,40})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), intercept( [6, 7, 9, 15, 21], [20, 28, 31, 38, 40] ) ); testArrayFormula2("INTERCEPT", 2, 2, null, true); } ); test( "Test: \"INT\"", function () { ws.getRange2( "A202" ).setValue( "19.5" ); oParser = new parserFormula( "INT(8.9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 8 ); oParser = new parserFormula( "INT(-8.9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -9 ); oParser = new parserFormula( "A202-INT(A202)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0.5 ); testArrayFormula("INT"); } ); test( "Test: \"KURT\"", function () { function kurt( x ) { var sumSQRDeltaX = 0, _x = 0, xLength = 0, standDev = 0, sumSQRDeltaXDivstandDev = 0; for ( var i = 0; i < x.length; i++ ) { _x += x[i]; xLength++; } _x /= xLength; for ( var i = 0; i < x.length; i++ ) { sumSQRDeltaX += Math.pow( x[i] - _x, 2 ); } standDev = Math.sqrt( sumSQRDeltaX / ( xLength - 1 ) ); for ( var i = 0; i < x.length; i++ ) { sumSQRDeltaXDivstandDev += Math.pow( (x[i] - _x) / standDev, 4 ); } return toFixed( xLength * (xLength + 1) / (xLength - 1) / (xLength - 2) / (xLength - 3) * sumSQRDeltaXDivstandDev - 3 * (xLength - 1) * (xLength - 1) / (xLength - 2) / (xLength - 3) ) } oParser = new parserFormula( "KURT(10.5,12.4,19.4,23.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), kurt( [10.5, 12.4, 19.4, 23.2] ) ); oParser = new parserFormula( "KURT(10.5,{12.4,19.4},23.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), kurt( [10.5, 12.4, 19.4, 23.2] ) ); oParser = new parserFormula( "KURT(10.5,12.4,19.4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("KURT", 1, 8, null, true); } ); test( "Test: \"LARGE\"", function () { oParser = new parserFormula( "LARGE({3,5,3,5,4;4,2,4,6,7},3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "LARGE({3,5,3,5,4;4,2,4,6,7},7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); //TODO нужна другая функция для тестирования //testArrayFormula2("LARGE", 2, 2) } ); test( "Test: \"LN\"", function () { oParser = new parserFormula( "LN(86)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 4.4543473 ); oParser = new parserFormula( "LN(2.7182818)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(1) - 0, 1 ); oParser = new parserFormula( "LN(EXP(3))", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); testArrayFormula("LN"); } ); test( "Test: \"LOG10\"", function () { oParser = new parserFormula( "LOG10(86)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(4) - 0, 1.9345 ); oParser = new parserFormula( "LOG10(10)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "LOG10(100000)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "LOG10(10^5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); testArrayFormula("LOG10"); } ); test( "Test: \"LINEST\"", function () { ws.getRange2( "A202" ).setValue( "1" ); ws.getRange2( "A203" ).setValue( "2" ); ws.getRange2( "A204" ).setValue( "3" ); ws.getRange2( "B202" ).setValue( "2" ); ws.getRange2( "B203" ).setValue( "3" ); ws.getRange2( "B204" ).setValue( "4" ); oParser = new parserFormula( "LINEST(A202:B204)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 0.54285714); oParser = new parserFormula( "LINEST(A202:B204, A202:B204)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1); oParser = new parserFormula( "LINEST(A202:B204, A202:B204, 1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1); oParser = new parserFormula( "LINEST(A202:B204, A202:B204, 1, 1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1); ws.getRange2( "A202" ).setValue( "1" ); ws.getRange2( "A203" ).setValue( "9" ); ws.getRange2( "A204" ).setValue( "5" ); ws.getRange2( "A205" ).setValue( "7" ); ws.getRange2( "B202" ).setValue( "0" ); ws.getRange2( "B203" ).setValue( "4" ); ws.getRange2( "B204" ).setValue( "2" ); ws.getRange2( "B205" ).setValue( "3" ); oParser = new parserFormula( "LINEST(A202:A205,B202:B205,,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 2); oParser = new parserFormula( "LINEST(A202:A205,B202:B205,FALSE,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 2.31034483); oParser = new parserFormula( "LINEST(A202:A205,B202:B205,FALSE,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 2.31034483); ws.getRange2( "A102" ).setValue( "1" ); ws.getRange2( "A103" ).setValue( "9" ); ws.getRange2( "A104" ).setValue( "5" ); ws.getRange2( "A105" ).setValue( "7" ); ws.getRange2( "B102" ).setValue( "0" ); ws.getRange2( "B103" ).setValue( "4" ); ws.getRange2( "B104" ).setValue( "2" ); ws.getRange2( "B105" ).setValue( "3" ); oParser = new parserFormula( "LINEST(A102:A105,B102:B105,,FALSE)", "A1", ws ); oParser.setArrayFormulaRef(ws.getRange2("E106:F106").bbox); ok( oParser.parse() ); var array = oParser.calculate(); if(AscCommonExcel.cElementType.array === array.type) { strictEqual( array.getElementRowCol(0,0).getValue(), 2); strictEqual( array.getElementRowCol(0,1).getValue(), 1); } ws.getRange2( "A102" ).setValue( "2310" ); ws.getRange2( "A103" ).setValue( "2333" ); ws.getRange2( "A104" ).setValue( "2356" ); ws.getRange2( "A105" ).setValue( "2379" ); ws.getRange2( "A106" ).setValue( "2402" ); ws.getRange2( "A107" ).setValue( "2425" ); ws.getRange2( "A108" ).setValue( "2448" ); ws.getRange2( "A109" ).setValue( "2471" ); ws.getRange2( "A110" ).setValue( "2494" ); ws.getRange2( "A111" ).setValue( "2517" ); ws.getRange2( "A112" ).setValue( "2540" ); ws.getRange2( 'B102' ).setValue( '2') ws.getRange2( 'B103' ).setValue( '2') ws.getRange2( 'B104' ).setValue( '3') ws.getRange2( 'B105' ).setValue( '3') ws.getRange2( 'B106' ).setValue( '2') ws.getRange2( 'B107' ).setValue( '4') ws.getRange2( 'B108' ).setValue( '2') ws.getRange2( 'B109' ).setValue( '2') ws.getRange2( 'B110' ).setValue( '3') ws.getRange2( 'B111' ).setValue( '4') ws.getRange2( 'B112' ).setValue( '2') ws.getRange2( 'C102' ).setValue( '2') ws.getRange2( 'C103' ).setValue( '2') ws.getRange2( 'C104' ).setValue( '1.5') ws.getRange2( 'C105' ).setValue( '2') ws.getRange2( 'C106' ).setValue( '3') ws.getRange2( 'C107' ).setValue( '2') ws.getRange2( 'C108' ).setValue( '1.5') ws.getRange2( 'C109' ).setValue( '2') ws.getRange2( 'C110' ).setValue( '3') ws.getRange2( 'C111' ).setValue( '4') ws.getRange2( 'C112' ).setValue( '3') ws.getRange2( 'D102' ).setValue( '20') ws.getRange2( 'D103' ).setValue( '12') ws.getRange2( 'D104' ).setValue( '33') ws.getRange2( 'D105' ).setValue( '43') ws.getRange2( 'D106' ).setValue( '53') ws.getRange2( 'D107' ).setValue( '23') ws.getRange2( 'D108' ).setValue( '99') ws.getRange2( 'D109' ).setValue( '34') ws.getRange2( 'D110' ).setValue( '23') ws.getRange2( 'D111' ).setValue( '55') ws.getRange2( 'D112' ).setValue( '22') ws.getRange2( 'E102' ).setValue( '142000') ws.getRange2( 'E103' ).setValue( '144000') ws.getRange2( 'E104' ).setValue( '151000') ws.getRange2( 'E105' ).setValue( '150000') ws.getRange2( 'E106' ).setValue( '139000') ws.getRange2( 'E107' ).setValue( '169000') ws.getRange2( 'E108' ).setValue( '126000') ws.getRange2( 'E109' ).setValue( '142900') ws.getRange2( 'E110' ).setValue( '163000') ws.getRange2( 'E111' ).setValue( '169000') ws.getRange2( 'E112' ).setValue( '149000') oParser = new parserFormula( "LINEST(E102:E112,A102:D112,TRUE,TRUE)", "A1", ws ); oParser.setArrayFormulaRef(ws.getRange2("E120:E123").bbox); ok( oParser.parse() ); var array = oParser.calculate(); if(AscCommonExcel.cElementType.array === array.type) { strictEqual( array.getElementRowCol(0,0).getValue().toFixed(7) - 0, -234.2371645); strictEqual( array.getElementRowCol(1,0).getValue().toFixed(8) - 0, 13.26801148); strictEqual( array.getElementRowCol(2,0).getValue().toFixed(9) - 0, 0.996747993); strictEqual( array.getElementRowCol(3,0).getValue().toFixed(7) - 0, 459.7536742); } } ); test( "Test: \"MEDIAN\"", function () { function median( x ) { x.sort(fSortAscending); if ( x.length % 2 ) return x[(x.length - 1) / 2]; else return (x[x.length / 2 - 1] + x[x.length / 2]) / 2; } oParser = new parserFormula( "MEDIAN(10.5,12.4,19.4,23.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), median( [10.5, 12.4, 19.4, 23.2] ) ); oParser = new parserFormula( "MEDIAN(10.5,{12.4,19.4},23.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), median( [10.5, 12.4, 19.4, 23.2] ) ); oParser = new parserFormula( "MEDIAN(-3.5,1.4,6.9,-4.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), median( [-3.5, 1.4, 6.9, -4.5] ) ); testArrayFormula2("MEDIAN", 1, 8, null, true); } ); test( "Test: \"MODE\"", function () { function mode( x ) { x.sort(AscCommon.fSortAscending); if ( x.length < 1 ) return "#VALUE!"; else { var nMaxIndex = 0, nMax = 1, nCount = 1, nOldVal = x[0], i; for ( i = 1; i < x.length; i++ ) { if ( x[i] == nOldVal ) nCount++; else { nOldVal = x[i]; if ( nCount > nMax ) { nMax = nCount; nMaxIndex = i - 1; } nCount = 1; } } if ( nCount > nMax ) { nMax = nCount; nMaxIndex = i - 1; } if ( nMax == 1 && nCount == 1 ) return "#VALUE!"; else if ( nMax == 1 ) return nOldVal; else return x[nMaxIndex]; } } oParser = new parserFormula( "MODE(9,1,5,1,9,5,6,6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), mode( [9, 1, 5, 1, 9, 5, 6, 6] ) ); oParser = new parserFormula( "MODE(1,9,5,1,9,5,6,6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), mode( [1, 9, 5, 1, 9, 5, 6, 6] ) ); oParser = new parserFormula( "MODE(1,9,5,5,9,5,6,6)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), mode( [1, 9, 5, 5, 9, 5, 6, 6] ) ); testArrayFormula2("mode", 1, 8, null, true); } ); test( "Test: \"MODE.MULT \"", function () { ws.getRange2( "F202" ).setValue( "1" ); ws.getRange2( "F203" ).setValue( "2" ); ws.getRange2( "F204" ).setValue( "3" ); ws.getRange2( "F205" ).setValue( "4" ); ws.getRange2( "F206" ).setValue( "3" ); ws.getRange2( "F207" ).setValue( "2" ); ws.getRange2( "F208" ).setValue( "1" ); ws.getRange2( "F209" ).setValue( "2" ); ws.getRange2( "F210" ).setValue( "3" ); ws.getRange2( "F211" ).setValue( "5" ); ws.getRange2( "F212" ).setValue( "6" ); ws.getRange2( "F213" ).setValue( "1" ); oParser = new parserFormula( "MODE.MULT(F202:F213)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); } ); test( "Test: \"MODE.SNGL \"", function () { ws.getRange2( "F202" ).setValue( "5.6" ); ws.getRange2( "F203" ).setValue( "4" ); ws.getRange2( "F204" ).setValue( "4" ); ws.getRange2( "F205" ).setValue( "3" ); ws.getRange2( "F206" ).setValue( "2" ); ws.getRange2( "F207" ).setValue( "4" ); oParser = new parserFormula( "MODE.SNGL(F202:F207)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); } ); test( "Test: \"NUMBERVALUE\"", function () { oParser = new parserFormula( 'NUMBERVALUE("2.500,27",",",".")', "A1", ws ); ok( oParser.parse(), 'NUMBERVALUE("2.500,27",",",".")'); strictEqual( oParser.calculate().getValue(), 2500.27, 'NUMBERVALUE("2.500,27",",",".")'); oParser = new parserFormula( 'NUMBERVALUE("3.5%")', "A1", ws ); ok( oParser.parse(), 'NUMBERVALUE("3.5%")'); strictEqual( oParser.calculate().getValue(), 0.035, 'NUMBERVALUE("3.5%")'); oParser = new parserFormula( 'NUMBERVALUE("3.5%%%")', "A1", ws ); ok( oParser.parse(), 'NUMBERVALUE("3.5%%%")'); strictEqual( oParser.calculate().getValue(), 0.0000035, 'NUMBERVALUE("3.5%%%")'); oParser = new parserFormula( 'NUMBERVALUE(123123,6,6)', "A1", ws ); ok( oParser.parse(), 'NUMBERVALUE(123123,6,6)'); strictEqual( oParser.calculate().getValue(), "#VALUE!", 'NUMBERVALUE(123123,6,6)'); testArrayFormula2("NUMBERVALUE", 1, 3); }); test( "Test: \"NORMDIST\"", function () { function normdist( x, mue, sigma, kum ) { if ( sigma <= 0 ) return "#NUM!"; else if ( kum == false ) return toFixed( AscCommonExcel.phi( (x - mue) / sigma ) / sigma ); else return toFixed( 0.5 + AscCommonExcel.gauss( (x - mue) / sigma ) ); } oParser = new parserFormula( "NORMDIST(42,40,1.5,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normdist( 42, 40, 1.5, true ) ); oParser = new parserFormula( "NORMDIST(42,40,1.5,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normdist( 42, 40, 1.5, false ) ); oParser = new parserFormula( "NORMDIST(42,40,-1.5,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normdist( 42, 40, -1.5, true ) ); oParser = new parserFormula( "NORMDIST(1,40,-1.5,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normdist( 1, 40, -1.5, true ) ); testArrayFormula2("NORMDIST", 4, 4); } ); test( "Test: \"NORM.DIST \"", function () { ws.getRange2( "F202" ).setValue( "42" ); ws.getRange2( "F203" ).setValue( "40" ); ws.getRange2( "F204" ).setValue( "1.5" ); oParser = new parserFormula( "NORM.DIST(F202,F203,F204,TRUE)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.9087888 ); oParser = new parserFormula( "NORM.DIST(F202,F203,F204,FALSE)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 0.10934 ); } ); test( "Test: \"NORMSDIST\"", function () { function normsdist( x ) { return toFixed( 0.5 + AscCommonExcel.gauss( x ) ); } oParser = new parserFormula( "NORMSDIST(1.333333)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normsdist( 1.333333 ) ); oParser = new parserFormula( "NORMSDIST(-1.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normsdist( -1.5 ) ); testArrayFormula("NORMSDIST"); } ); test( "Test: \"NORM.S.DIST\"", function () { oParser = new parserFormula( "NORM.S.DIST(1.333333,TRUE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.908788726 ); oParser = new parserFormula( "NORM.S.DIST(1.333333,FALSE)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.164010148 ); testArrayFormula2("NORM.S.DIST", 2, 2) } ); test( "Test: \"NEGBINOMDIST\"", function () { function negbinomdist( x, r, p ) { x = parseInt( x ); r = parseInt( r ); if ( x < 0 || r < 1 || p < 0 || p > 1 ) return "#NUM!"; else return toFixed( Math.binomCoeff( x + r - 1, r - 1 ) * Math.pow( p, r ) * Math.pow( 1 - p, x ) ); } oParser = new parserFormula( "NEGBINOMDIST(6,10,0.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), negbinomdist( 6, 10, 0.5 ) ); oParser = new parserFormula( "NEGBINOMDIST(6,10,1.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), negbinomdist( 6, 10, 1.5 ) ); oParser = new parserFormula( "NEGBINOMDIST(20,10,0.63)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), negbinomdist( 20, 10, 0.63 ) ); testArrayFormula2("NEGBINOMDIST", 3, 3); } ); test( "Test: \"NEGBINOM.DIST \"", function () { ws.getRange2( "F202" ).setValue( "10" ); ws.getRange2( "F203" ).setValue( "5" ); ws.getRange2( "F204" ).setValue( "0.25" ); oParser = new parserFormula( "NEGBINOM.DIST(F202,F203,F204,TRUE)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.3135141 ); oParser = new parserFormula( "NEGBINOM.DIST(F202,F203,F204,FALSE)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0550487 ); testArrayFormula2("NEGBINOM.DIST", 4, 4); } ); test( "Test: \"NEGBINOMDIST \"", function () { ws.getRange2( "F202" ).setValue( "10" ); ws.getRange2( "F203" ).setValue( "5" ); ws.getRange2( "F204" ).setValue( "0.25" ); oParser = new parserFormula( "NEGBINOMDIST(F202,F203,F204)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.05504866 ); } ); test( "Test: \"NORMSINV\"", function () { function normsinv( x ) { if ( x <= 0.0 || x >= 1.0 ) return "#N/A"; else return toFixed( AscCommonExcel.gaussinv( x ) ); } oParser = new parserFormula( "NORMSINV(0.954)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normsinv( 0.954 ) ); oParser = new parserFormula( "NORMSINV(0.13)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normsinv( 0.13 ) ); oParser = new parserFormula( "NORMSINV(0.6782136)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normsinv( 0.6782136 ) ); oParser = new parserFormula( "NORMSINV(1.6782136)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normsinv( 1.6782136 ) ); oParser = new parserFormula( "NORMSINV(-1.6782136)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), normsinv( -1.6782136 ) ); testArrayFormula("NORMSINV"); } ); test( "Test: \"NORM.S.INV \"", function () { oParser = new parserFormula( "NORM.S.INV(0.908789)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 1.3333347 ); } ); test( "Test: \"LOGINV\"", function () { function loginv( x, mue, sigma ) { if ( sigma <= 0 || x <= 0 || x >= 1 ) return "#NUM!"; else return toFixed( Math.exp( mue + sigma * ( AscCommonExcel.gaussinv( x ) ) ) ); } oParser = new parserFormula( "LOGINV(0.039084,3.5,1.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), loginv( 0.039084, 3.5, 1.2 ) ); oParser = new parserFormula( "LOGINV(0,3.5,1.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), loginv( 0, 3.5, 1.2 ) ); oParser = new parserFormula( "LOGINV(0,3.5,1.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), loginv( 10, 3.5, 1.2 ) ); oParser = new parserFormula( "LOGINV(0,3.5,1.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), loginv( -10, 3.5, 1.2 ) ); testArrayFormula2("LOGINV", 3, 3); } ); test( "Test: \"NORMINV\"", function () { function norminv( x, mue, sigma ) { if ( sigma <= 0.0 || x <= 0.0 || x >= 1.0 ) return "#NUM!"; else return toFixed( AscCommonExcel.gaussinv( x ) * sigma + mue ); } oParser = new parserFormula( "NORMINV(0.954,40,1.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), norminv( 0.954, 40, 1.5 ) ); oParser = new parserFormula( "NORMINV(0.13,100,0.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), norminv( 0.13, 100, 0.5 ) ); oParser = new parserFormula( "NORMINV(0.6782136,6,0.005)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), norminv( 0.6782136, 6, 0.005 ) ); oParser = new parserFormula( "NORMINV(-1.6782136,7,0)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), norminv( -1.6782136, 7, 0 ) ); testArrayFormula2("NORMINV", 3, 3); } ); test( "Test: \"NORM.INV \"", function () { ws.getRange2( "F202" ).setValue( "0.908789" ); ws.getRange2( "F203" ).setValue( "40" ); ws.getRange2( "F204" ).setValue( "1.5" ); oParser = new parserFormula( "NORM.INV(F202,F203,F204)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 42.000002 ); } ); test( "Test: \"PEARSON\"", function () { function pearson( x, y ) { var sumXDeltaYDelta = 0, sqrXDelta = 0, sqrYDelta = 0, _x = 0, _y = 0, xLength = 0; if ( x.length != y.length ) return "#N/A" for ( var i = 0; i < x.length; i++ ) { _x += x[i] _y += y[i] xLength++; } _x /= xLength; _y /= xLength; for ( var i = 0; i < x.length; i++ ) { sumXDeltaYDelta += (x[i] - _x) * (y[i] - _y); sqrXDelta += (x[i] - _x) * (x[i] - _x); sqrYDelta += (y[i] - _y) * (y[i] - _y); } if ( sqrXDelta == 0 || sqrYDelta == 0 ) return "#DIV/0!" else return toFixed( sumXDeltaYDelta / Math.sqrt( sqrXDelta * sqrYDelta ) ); } oParser = new parserFormula( "PEARSON({9,7,5,3,1},{10,6,1,5,3})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), pearson( [9, 7, 5, 3, 1], [10, 6, 1, 5, 3] ) ); testArrayFormula2("PEARSON", 2, 2, null, true) } ); test( "Test: \"PERCENTILE\"", function () { function percentile( A, k ) { A.sort(fSortAscending) var nSize = A.length; if ( A.length < 1 || nSize == 0 ) return new AscCommonExcel.cError( AscCommonExcel.cErrorType.not_available ).toString(); else { if ( nSize == 1 ) return toFixed( A[0] ); else { var nIndex = Math.floor( k * (nSize - 1) ); var fDiff = k * (nSize - 1) - Math.floor( k * (nSize - 1) ); if ( fDiff == 0.0 ) return toFixed( A[nIndex] ); else { return toFixed( A[nIndex] + fDiff * (A[nIndex + 1] - A[nIndex]) ); } } } } oParser = new parserFormula( "PERCENTILE({1,3,2,4},0.3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), percentile( [1, 3, 2, 4], 0.3 ) ); oParser = new parserFormula( "PERCENTILE({1,3,2,4},0.75)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), percentile( [1, 3, 2, 4], 0.75 ) ); //TODO нужна другая функция для тестирования //testArrayFormula2("PERCENTILE", 2, 2, null, true); } ); test( "Test: \"PERCENTILE.INC\"", function () { ws.getRange2( "A2" ).setValue( "1" ); ws.getRange2( "A3" ).setValue( "2" ); ws.getRange2( "A4" ).setValue( "3" ); ws.getRange2( "A5" ).setValue( "4" ); oParser = new parserFormula( "PERCENTILE.INC(A2:A5,0.3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1.9 ); } ); test( "Test: \"PERCENTILE.EXC\"", function () { ws.getRange2( "A202" ).setValue( "1" ); ws.getRange2( "A203" ).setValue( "2" ); ws.getRange2( "A204" ).setValue( "3" ); ws.getRange2( "A205" ).setValue( "6" ); ws.getRange2( "A206" ).setValue( "6" ); ws.getRange2( "A207" ).setValue( "6" ); ws.getRange2( "A208" ).setValue( "7" ); ws.getRange2( "A209" ).setValue( "8" ); ws.getRange2( "A210" ).setValue( "9" ); oParser = new parserFormula( "PERCENTILE.EXC(A202:A210, 0.25)", "A1", ws ); ok( oParser.parse(), "PERCENTILE.EXC(A202:A210, 0.25)" ); strictEqual( oParser.calculate().getValue(), 2.5, "PERCENTILE.EXC(A202:A210, 0.25)" ); oParser = new parserFormula( "PERCENTILE.EXC(A202:A210, 0)", "A1", ws ); ok( oParser.parse(), "PERCENTILE.EXC(A202:A210, 0)" ); strictEqual( oParser.calculate().getValue(), "#NUM!", "PERCENTILE.EXC(A202:A210, 0)" ); oParser = new parserFormula( "PERCENTILE.EXC(A202:A210, 0.01)", "A1", ws ); ok( oParser.parse(), "PERCENTILE.EXC(A202:A210, 0.01)" ); strictEqual( oParser.calculate().getValue(), "#NUM!", "PERCENTILE.EXC(A202:A210, 0.01)" ); oParser = new parserFormula( "PERCENTILE.EXC(A202:A210, 2)", "A1", ws ); ok( oParser.parse(), "PERCENTILE.EXC(A202:A210, 2)" ); strictEqual( oParser.calculate().getValue(), "#NUM!", "PERCENTILE.EXC(A202:A210, 2)" ); //TODO нужна другая функция для тестирования //testArrayFormula2("PERCENTILE.EXC", 2, 2, null, true) } ); test( "Test: \"PERCENTRANK\"", function () { function percentrank( A, x, k ) { var tA = A, t, fNum = x; if ( !k ) k = 3; tA.sort(fSortAscending); var nSize = tA.length; if ( tA.length < 1 || nSize == 0 ) return "#N/A"; else { if ( fNum < tA[0] || fNum > tA[nSize - 1] ) return "#N/A"; else if ( nSize == 1 ) return 1 else { var fRes, nOldCount = 0, fOldVal = tA[0], i; for ( i = 1; i < nSize && tA[i] < fNum; i++ ) { if ( tA[i] != fOldVal ) { nOldCount = i; fOldVal = tA[i]; } } if ( tA[i] != fOldVal ) nOldCount = i; if ( fNum == tA[i] ) fRes = nOldCount / (nSize - 1); else { if ( nOldCount == 0 ) { fRes = 0.0; } else { var fFract = ( fNum - tA[nOldCount - 1] ) / ( tA[nOldCount] - tA[nOldCount - 1] ); fRes = ( nOldCount - 1 + fFract ) / (nSize - 1); } } return fRes.toString().substr( 0, fRes.toString().indexOf( "." ) + 1 + k ) - 0; } } } oParser = new parserFormula( "PERCENTRANK({12,6,7,9,3,8},4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), percentrank( [12, 6, 7, 9, 3, 8], 4 ) ); oParser = new parserFormula( "PERCENTRANK({12,6,7,9,3,8},5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), percentrank( [12, 6, 7, 9, 3, 8], 5 ) ); //TODO нужен другой тест //testArrayFormula2("PERCENTRANK", 2, 3, null, true); } ); test( "Test: \"PERCENTRANK.EXC\"", function () { ws.getRange2( "A202" ).setValue( "1" ); ws.getRange2( "A203" ).setValue( "2" ); ws.getRange2( "A204" ).setValue( "3" ); ws.getRange2( "A205" ).setValue( "6" ); ws.getRange2( "A206" ).setValue( "6" ); ws.getRange2( "A207" ).setValue( "6" ); ws.getRange2( "A208" ).setValue( "7" ); ws.getRange2( "A209" ).setValue( "8" ); ws.getRange2( "A210" ).setValue( "9" ); oParser = new parserFormula( "PERCENTRANK.EXC(A202:A210, 7)", "A1", ws ); ok( oParser.parse(), "PERCENTRANK.EXC(A202:A210, 7)" ); strictEqual( oParser.calculate().getValue(), 0.7, "PERCENTRANK.EXC(A202:A210, 7)" ); oParser = new parserFormula( "PERCENTRANK.EXC(A202:A210, 5.43)", "A1", ws ); ok( oParser.parse(), "PERCENTRANK.EXC(A202:A210, 5.43)" ); strictEqual( oParser.calculate().getValue(), 0.381, "PERCENTRANK.EXC(A202:A210, 5.43)" ); oParser = new parserFormula( "PERCENTRANK.EXC(A202:A210, 5.43, 1)", "A1", ws ); ok( oParser.parse(), "PERCENTRANK.EXC(A202:A210, 5.43, 1)" ); strictEqual( oParser.calculate().getValue(), 0.3, "PERCENTRANK.EXC(A202:A210, 5.43, 1)" ); //TODO нужен другой тест //testArrayFormula2("PERCENTRANK.EXC", 2, 3, null, true); } ); test( "Test: \"PERCENTRANK.INC\"", function () { ws.getRange2( "A202" ).setValue( "13" ); ws.getRange2( "A203" ).setValue( "12" ); ws.getRange2( "A204" ).setValue( "11" ); ws.getRange2( "A205" ).setValue( "8" ); ws.getRange2( "A206" ).setValue( "4" ); ws.getRange2( "A207" ).setValue( "3" ); ws.getRange2( "A208" ).setValue( "2" ); ws.getRange2( "A209" ).setValue( "1" ); ws.getRange2( "A210" ).setValue( "1" ); ws.getRange2( "A211" ).setValue( "1" ); oParser = new parserFormula( "PERCENTRANK.INC(A202:A211, 2)", "A1", ws ); ok( oParser.parse(), "PERCENTRANK.INC(A202:A211, 2)" ); strictEqual( oParser.calculate().getValue(), 0.333, "PERCENTRANK.INC(A202:A211, 2)" ); oParser = new parserFormula( "PERCENTRANK.INC(A202:A211, 4)", "A1", ws ); ok( oParser.parse(), "PERCENTRANK.INC(A202:A211, 4)" ); strictEqual( oParser.calculate().getValue(), 0.555, "PERCENTRANK.INC(A202:A211, 4)" ); oParser = new parserFormula( "PERCENTRANK.INC(A202:A211, 8)", "A1", ws ); ok( oParser.parse(), "PERCENTRANK.INC(A202:A211, 8)" ); strictEqual( oParser.calculate().getValue(), 0.666, "PERCENTRANK.INC(A202:A211, 8)" ); oParser = new parserFormula( "PERCENTRANK.INC(A202:A211, 5)", "A1", ws ); ok( oParser.parse(), "PERCENTRANK.INC(A202:A211, 5)" ); strictEqual( oParser.calculate().getValue(), 0.583, "PERCENTRANK.INC(A202:A211, 5)" ); } ); test( "Test: \"PERMUT\"", function () { ws.getRange2( "A2" ).setValue( "100" ); ws.getRange2( "A3" ).setValue( "3" ); oParser = new parserFormula( "PERMUT(A2,A3)", "A1", ws ); ok( oParser.parse(), "PERMUT(A2,A3)" ); strictEqual( oParser.calculate().getValue(), 970200, "PERMUT(A2,A3)" ); oParser = new parserFormula( "PERMUT(3,2)", "A1", ws ); ok( oParser.parse(), "PERMUT(3,2)" ); strictEqual( oParser.calculate().getValue(), 6, "PERMUT(3,2)" ); testArrayFormula2("PERMUT", 2, 2); } ); test( "Test: \"PERMUTATIONA\"", function () { oParser = new parserFormula( "PERMUTATIONA(3,2)", "A1", ws ); ok( oParser.parse(), "PERMUTATIONA(3,2)" ); strictEqual( oParser.calculate().getValue(), 9, "PERMUTATIONA(3,2)" ); oParser = new parserFormula( "PERMUTATIONA(2,2)", "A1", ws ); ok( oParser.parse(), "PERMUTATIONA(2,2)" ); strictEqual( oParser.calculate().getValue(), 4, "PERMUTATIONA(2,2)" ); testArrayFormula2("PERMUTATIONA", 2, 2); } ); test( "Test: \"PHI\"", function () { oParser = new parserFormula( "PHI(0.75)", "A1", ws ); ok( oParser.parse(), "PHI(0.75)" ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 0.301137432, "PHI(0.75)" ); testArrayFormula2("PHI", 1, 1); } ); test( "Test: \"POISSON\"", function () { function poisson( x, l, cumulativeFlag ) { var _x = parseInt( x ), _l = l, f = cumulativeFlag; if ( f ) { var sum = 0; for ( var k = 0; k <= x; k++ ) { sum += Math.pow( _l, k ) / Math.fact( k ); } sum *= Math.exp( -_l ); return toFixed( sum ); } else { return toFixed( Math.exp( -_l ) * Math.pow( _l, _x ) / Math.fact( _x ) ); } } oParser = new parserFormula( "POISSON(8,2,false)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), poisson( 8, 2, false ) ); oParser = new parserFormula( "POISSON(8,2,true)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), poisson( 8, 2, true ) ); oParser = new parserFormula( "POISSON(2.6,5,false)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), poisson( 2, 5, false ) ); oParser = new parserFormula( "POISSON(2,5.7,true)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), poisson( 2, 5.7, true ) ); oParser = new parserFormula( "POISSON(-6,5,true)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "POISSON(6,-5,false)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("POISSON", 3, 3); } ); test( "Test: \"POISSON.DIST\"", function () { ws.getRange2( "A202" ).setValue( "2" ); ws.getRange2( "A203" ).setValue( "5" ); oParser = new parserFormula( "POISSON.DIST(A202,A203,TRUE)", "A1", ws ); ok( oParser.parse(), "POISSON.DIST(A202,A203,TRUE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.124652, "POISSON.DIST(A202,A203,TRUE)" ); oParser = new parserFormula( "POISSON.DIST(A202,A203,FALSE)", "A1", ws ); ok( oParser.parse(), "POISSON.DIST(A202,A203,FALSE)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.084224, "POISSON.DIST(A202,A203,FALSE)" ); testArrayFormula2("POISSON.DIST", 3, 3); } ); test( "Test: \"PROB\"", function () { oParser = new parserFormula( "PROB({0,1,2,3},{0.2,0.3,0.1,0.4},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0.1 ); oParser = new parserFormula( "PROB({0,1,2,3},{0.2,0.3,0.1,0.4},1,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0.8 ); } ); test( "Test: \"PROB\"", function () { function quartile( A, k ) { var fFlag = k; A.sort(fSortAscending); var nSize = A.length; if ( A.length < 1 || nSize == 0 ) return "#N/A" else { if ( nSize == 1 ) return toFixed( A[0] ); else { if ( fFlag < 0.0 || fFlag > 4 ) return "#NUM!"; else if ( fFlag == 0.0 ) return toFixed( A[0] ); else if ( fFlag == 1.0 ) { var nIndex = Math.floor( 0.25 * (nSize - 1) ), fDiff = 0.25 * (nSize - 1) - Math.floor( 0.25 * (nSize - 1) ); if ( fDiff == 0.0 ) return toFixed( A[nIndex] ); else { return toFixed( A[nIndex] + fDiff * (A[nIndex + 1] - A[nIndex]) ); } } else if ( fFlag == 2.0 ) { if ( nSize % 2 == 0 ) return toFixed( (A[nSize / 2 - 1] + A[nSize / 2]) / 2.0 ); else return toFixed( A[(nSize - 1) / 2] ); } else if ( fFlag == 3.0 ) { var nIndex = Math.floor( 0.75 * (nSize - 1) ), fDiff = 0.75 * (nSize - 1) - Math.floor( 0.75 * (nSize - 1) ); if ( fDiff == 0.0 ) return toFixed( A[nIndex] ); else { return toFixed( A[nIndex] + fDiff * (A[nIndex + 1] - A[nIndex]) ); } } else return toFixed( A[nSize - 1] ); } } } oParser = new parserFormula( "QUARTILE({1,2,4,7,8,9,10,12},-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), quartile( [1, 2, 4, 7, 8, 9, 10, 12], -1 ) ); oParser = new parserFormula( "QUARTILE({1,2,4,7,8,9,10,12},0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), quartile( [1, 2, 4, 7, 8, 9, 10, 12], 0 ) ); oParser = new parserFormula( "QUARTILE({1,2,4,7,8,9,10,12},1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), quartile( [1, 2, 4, 7, 8, 9, 10, 12], 1 ) ); oParser = new parserFormula( "QUARTILE({1,2,4,7,8,9,10,12},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), quartile( [1, 2, 4, 7, 8, 9, 10, 12], 2 ) ); oParser = new parserFormula( "QUARTILE({1,2,4,7,8,9,10,12},3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), quartile( [1, 2, 4, 7, 8, 9, 10, 12], 3 ) ); oParser = new parserFormula( "QUARTILE({1,2,4,7,8,9,10,12},4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), quartile( [1, 2, 4, 7, 8, 9, 10, 12], 4 ) ); oParser = new parserFormula( "QUARTILE({1,2,4,7,8,9,10,12},5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), quartile( [1, 2, 4, 7, 8, 9, 10, 12], 5 ) ); } ); test( "Test: \"QUARTILE\"", function () { ws.getRange2( "A202" ).setValue( "1" ); ws.getRange2( "A203" ).setValue( "2" ); ws.getRange2( "A204" ).setValue( "4" ); ws.getRange2( "A205" ).setValue( "7" ); ws.getRange2( "A206" ).setValue( "8" ); ws.getRange2( "A207" ).setValue( "9" ); ws.getRange2( "A208" ).setValue( "10" ); ws.getRange2( "A209" ).setValue( "12" ); oParser = new parserFormula( "QUARTILE(A202:A209,1)", "A1", ws ); ok( oParser.parse(), "QUARTILE(A202:A209,1)" ); strictEqual( oParser.calculate().getValue(), 3.5, "QUARTILE(A202:A209,1)" ); //TODO нужна другая функция для тестирования //testArrayFormula2("QUARTILE", 2, 2) } ); test( "Test: \"QUARTILE.INC\"", function () { ws.getRange2( "A202" ).setValue( "1" ); ws.getRange2( "A203" ).setValue( "2" ); ws.getRange2( "A204" ).setValue( "4" ); ws.getRange2( "A205" ).setValue( "7" ); ws.getRange2( "A206" ).setValue( "8" ); ws.getRange2( "A207" ).setValue( "9" ); ws.getRange2( "A208" ).setValue( "10" ); ws.getRange2( "A209" ).setValue( "12" ); oParser = new parserFormula( "QUARTILE.INC(A202:A209,1)", "A1", ws ); ok( oParser.parse(), "QUARTILE.INC(A202:A209,1)" ); strictEqual( oParser.calculate().getValue(), 3.5, "QUARTILE.INC(A202:A209,1)" ); } ); test( "Test: \"QUARTILE.EXC\"", function () { ws.getRange2( "A202" ).setValue( "6" ); ws.getRange2( "A203" ).setValue( "7" ); ws.getRange2( "A204" ).setValue( "15" ); ws.getRange2( "A205" ).setValue( "36" ); ws.getRange2( "A206" ).setValue( "39" ); ws.getRange2( "A207" ).setValue( "40" ); ws.getRange2( "A208" ).setValue( "41" ); ws.getRange2( "A209" ).setValue( "42" ); ws.getRange2( "A210" ).setValue( "43" ); ws.getRange2( "A211" ).setValue( "47" ); ws.getRange2( "A212" ).setValue( "49" ); oParser = new parserFormula( "QUARTILE.EXC(A202:A212,1)", "A1", ws ); ok( oParser.parse(), "QUARTILE.EXC(A202:A212,1)" ); strictEqual( oParser.calculate().getValue(), 15, "QUARTILE.EXC(A202:A212,1)" ); oParser = new parserFormula( "QUARTILE.EXC(A202:A212,3)", "A1", ws ); ok( oParser.parse(), "QUARTILE.EXC(A202:A212,3)" ); strictEqual( oParser.calculate().getValue(), 43, "QUARTILE.EXC(A202:A212,3)" ); //TODO нужна другая функция для тестирования //testArrayFormula2("QUARTILE.EXC", 2, 2) } ); test( "Test: \"RSQ\"", function () { function rsq( x, y ) { var sumXDeltaYDelta = 0, sqrXDelta = 0, sqrYDelta = 0, _x = 0, _y = 0, xLength = 0; if ( x.length != y.length ) return "#N/A" for ( var i = 0; i < x.length; i++ ) { _x += x[i] _y += y[i] xLength++; } _x /= xLength; _y /= xLength; for ( var i = 0; i < x.length; i++ ) { sumXDeltaYDelta += (x[i] - _x) * (y[i] - _y); sqrXDelta += (x[i] - _x) * (x[i] - _x); sqrYDelta += (y[i] - _y) * (y[i] - _y); } if ( sqrXDelta == 0 || sqrYDelta == 0 ) return "#DIV/0!" else return toFixed( Math.pow( sumXDeltaYDelta / Math.sqrt( sqrXDelta * sqrYDelta ), 2 ) ); } oParser = new parserFormula( "RSQ({9,7,5,3,1},{10,6,1,5,3})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), rsq( [9, 7, 5, 3, 1], [10, 6, 1, 5, 3] ) ); oParser = new parserFormula( "RSQ({2,3,9,1,8,7,5},{6,5,11,7,5,4,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), rsq( [2, 3, 9, 1, 8, 7, 5], [6, 5, 11, 7, 5, 4, 4] ) ); testArrayFormula2("RSQ", 2, 2, null, true) } ); test( "Test: \"SKEW\"", function () { function skew( x ) { var sumSQRDeltaX = 0, _x = 0, xLength = 0, standDev = 0, sumSQRDeltaXDivstandDev = 0; for ( var i = 0; i < x.length; i++ ) { _x += x[i]; xLength++; } if ( xLength <= 2 ) return "#N/A" _x /= xLength; for ( var i = 0; i < x.length; i++ ) { sumSQRDeltaX += Math.pow( x[i] - _x, 2 ); } standDev = Math.sqrt( sumSQRDeltaX / ( xLength - 1 ) ); for ( var i = 0; i < x.length; i++ ) { sumSQRDeltaXDivstandDev += Math.pow( (x[i] - _x) / standDev, 3 ); } return toFixed( xLength / (xLength - 1) / (xLength - 2) * sumSQRDeltaXDivstandDev ) } oParser = new parserFormula( "SKEW(3,4,5,2,3,4,5,6,4,7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), skew( [3, 4, 5, 2, 3, 4, 5, 6, 4, 7] ) ); oParser = new parserFormula( "SKEW({2,3,9,1,8,7,5},{6,5,11,7,5,4,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), skew( [2, 3, 9, 1, 8, 7, 5, 6, 5, 11, 7, 5, 4, 4] ) ); testArrayFormula2("SKEW", 1, 8, null, true); } ); test( "Test: \"SKEW.P\"", function () { ws.getRange2( "A202" ).setValue( "3" ); ws.getRange2( "A203" ).setValue( "4" ); ws.getRange2( "A204" ).setValue( "5" ); ws.getRange2( "A205" ).setValue( "2" ); ws.getRange2( "A206" ).setValue( "3" ); ws.getRange2( "A207" ).setValue( "4" ); ws.getRange2( "A208" ).setValue( "5" ); ws.getRange2( "A209" ).setValue( "6" ); ws.getRange2( "A210" ).setValue( "4" ); ws.getRange2( "A211" ).setValue( "7" ); oParser = new parserFormula( "SKEW.P(A202:A211)", "A1", ws ); ok( oParser.parse(), "SKEW.P(A202:A211)" ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.303193, "SKEW.P(A202:A211)" ); } ); test( "Test: \"SMALL\"", function () { oParser = new parserFormula( "SMALL({3,5,3,5,4;4,2,4,6,7},3)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "SMALL({3,5,3,5,4;4,2,4,6,7},7)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "SMALL({1,TRUE,FALSE,3,4,5,32,5,4,3},9)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "SMALL({1,TRUE,FALSE,3,4,5,32,5,4,3},8)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 32 ); oParser = new parserFormula( "SMALL({1,TRUE,10,3,4,5,32,5,4,3},10)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "SMALL({1,TRUE,10,3,4,5,32,5,4,3},1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); //TODO нужна другая функция для тестирования //testArrayFormula2("SMALL", 2, 2) } ); test( "Test: \"SLOPE\"", function () { function slope( y, x ) { var sumXDeltaYDelta = 0, sqrXDelta = 0, _x = 0, _y = 0, xLength = 0; if ( x.length != y.length ) return "#N/A" for ( var i = 0; i < x.length; i++ ) { _x += x[i] _y += y[i] xLength++; } _x /= xLength; _y /= xLength; for ( var i = 0; i < x.length; i++ ) { sumXDeltaYDelta += (x[i] - _x) * (y[i] - _y); sqrXDelta += (x[i] - _x) * (x[i] - _x); } if ( sqrXDelta == 0 ) return "#DIV/0!" else return toFixed( sumXDeltaYDelta / sqrXDelta ); } oParser = new parserFormula( "SLOPE({9,7,5,3,1},{10,6,1,5,3})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), slope( [9, 7, 5, 3, 1], [10, 6, 1, 5, 3] ) ); oParser = new parserFormula( "SLOPE({2,3,9,1,8,7,5},{6,5,11,7,5,4,4})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), slope( [2, 3, 9, 1, 8, 7, 5], [6, 5, 11, 7, 5, 4, 4] ) ); testArrayFormula2("SLOPE", 2, 2, null, true); } ); test( "Test: \"STEYX\"", function () { ws.getRange2( "A203" ).setValue( "2" ); ws.getRange2( "A204" ).setValue( "3" ); ws.getRange2( "A205" ).setValue( "9" ); ws.getRange2( "A206" ).setValue( "1" ); ws.getRange2( "A207" ).setValue( "8" ); ws.getRange2( "A208" ).setValue( "7" ); ws.getRange2( "A209" ).setValue( "5" ); ws.getRange2( "B203" ).setValue( "6" ); ws.getRange2( "B204" ).setValue( "5" ); ws.getRange2( "B205" ).setValue( "11" ); ws.getRange2( "B206" ).setValue( "7" ); ws.getRange2( "B207" ).setValue( "5" ); ws.getRange2( "B208" ).setValue( "4" ); ws.getRange2( "B209" ).setValue( "4" ); oParser = new parserFormula( "STEYX(A203:A209,B203:B209)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 3.305719 ); testArrayFormula2("STEYX", 2, 2, null, true); } ); test( "Test: \"STANDARDIZE\"", function () { function STANDARDIZE( x, mean, sigma ) { if ( sigma <= 0 ) return "#NUM!" else return toFixed( (x - mean) / sigma ); } oParser = new parserFormula( "STANDARDIZE(42,40,1.5)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), STANDARDIZE( 42, 40, 1.5 ) ); oParser = new parserFormula( "STANDARDIZE(22,12,2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), STANDARDIZE( 22, 12, 2 ) ); oParser = new parserFormula( "STANDARDIZE(22,12,-2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), STANDARDIZE( 22, 12, -2 ) ); testArrayFormula2("STANDARDIZE", 3, 3); } ); test( "Test: \"STDEV\"", function () { function stdev() { var average = 0, res = 0; for ( var i = 0; i < arguments.length; i++ ) { average += arguments[i]; } average /= arguments.length; for ( var i = 0; i < arguments.length; i++ ) { res += (arguments[i] - average) * (arguments[i] - average); } return toFixed( Math.sqrt( res / (arguments.length - 1) ) ); } oParser = new parserFormula( "STDEV(123,134,143,173,112,109)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), stdev( 123, 134, 143, 173, 112, 109 ) ); ws.getRange2( "E400" ).setValue( "\"123\"" ); ws.getRange2( "E401" ).setValue( "134" ); ws.getRange2( "E402" ).setValue( "143" ); ws.getRange2( "E403" ).setValue( "173" ); ws.getRange2( "E404" ).setValue( "112" ); ws.getRange2( "E405" ).setValue( "109" ); oParser = new parserFormula( "STDEV(E400:E405)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), stdev( 134, 143, 173, 112, 109 ) ); } ); test( "Test: \"STDEV.S\"", function () { ws.getRange2( "A202" ).setValue( "1345" ); ws.getRange2( "A203" ).setValue( "1301" ); ws.getRange2( "A204" ).setValue( "1368" ); ws.getRange2( "A205" ).setValue( "1322" ); ws.getRange2( "A206" ).setValue( "1310" ); ws.getRange2( "A207" ).setValue( "1370" ); ws.getRange2( "A208" ).setValue( "1318" ); ws.getRange2( "A209" ).setValue( "1350" ); ws.getRange2( "A210" ).setValue( "1303" ); ws.getRange2( "A211" ).setValue( "1299" ); oParser = new parserFormula( "STDEV.S(A202:A211)", "A1", ws ); ok( oParser.parse(), "STDEV.S(A202:A211)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 27.46391572, "STDEV.S(A202:A211)" ); } ); test( "Test: \"STDEV.P\"", function () { ws.getRange2( "A202" ).setValue( "1345" ); ws.getRange2( "A203" ).setValue( "1301" ); ws.getRange2( "A204" ).setValue( "1368" ); ws.getRange2( "A205" ).setValue( "1322" ); ws.getRange2( "A206" ).setValue( "1310" ); ws.getRange2( "A207" ).setValue( "1370" ); ws.getRange2( "A208" ).setValue( "1318" ); ws.getRange2( "A209" ).setValue( "1350" ); ws.getRange2( "A210" ).setValue( "1303" ); ws.getRange2( "A211" ).setValue( "1299" ); oParser = new parserFormula( "STDEV.P(A202:A211)", "A1", ws ); ok( oParser.parse(), "STDEV.P(A202:A211)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 26.05455814, "STDEV.P(A202:A211)" ); } ); test( "Test: \"STDEVA\"", function () { ws.getRange2( "E400" ).setValue( "\"123\"" ); ws.getRange2( "E401" ).setValue( "134" ); ws.getRange2( "E402" ).setValue( "143" ); ws.getRange2( "E403" ).setValue( "173" ); ws.getRange2( "E404" ).setValue( "112" ); ws.getRange2( "E405" ).setValue( "109" ); function stdeva() { var average = 0, res = 0; for ( var i = 0; i < arguments.length; i++ ) { average += arguments[i]; } average /= arguments.length; for ( var i = 0; i < arguments.length; i++ ) { res += (arguments[i] - average) * (arguments[i] - average); } return toFixed( Math.sqrt( res / (arguments.length - 1) ) ); } oParser = new parserFormula( "STDEVA(123,134,143,173,112,109)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), stdeva( 123, 134, 143, 173, 112, 109 ) ); oParser = new parserFormula( "STDEVA(123,134,143,173,112,109)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), stdeva( 123, 134, 143, 173, 112, 109 ) ); testArrayFormula2("STDEVA", 1, 8, null, true); } ); test( "Test: \"SWITCH\"", function () { ws.getRange2( "A2" ).setValue( "2" ); ws.getRange2( "A3" ).setValue( "99" ); ws.getRange2( "A4" ).setValue( "99" ); ws.getRange2( "A5" ).setValue( "2" ); ws.getRange2( "A6" ).setValue( "3" ); oParser = new parserFormula( 'SWITCH(WEEKDAY(A2),1,"Sunday",2,"Monday",3,"Tuesday","No match")', "A1", ws ); ok( oParser.parse(), 'SWITCH(WEEKDAY(A2),1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); strictEqual( oParser.calculate().getValue(), "Monday", 'SWITCH(WEEKDAY(A2),1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); oParser = new parserFormula( 'SWITCH(A3,1,"Sunday",2,"Monday",3,"Tuesday")', "A1", ws ); ok( oParser.parse(), 'SWITCH(A3,1,"Sunday",2,"Monday",3,"Tuesday")' ); strictEqual( oParser.calculate().getValue(), "#N/A", 'SWITCH(A3,1,"Sunday",2,"Monday",3,"Tuesday")' ); oParser = new parserFormula( 'SWITCH(A4,1,"Sunday",2,"Monday",3,"Tuesday","No match")', "A1", ws ); ok( oParser.parse(), 'SWITCH(A4,1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); strictEqual( oParser.calculate().getValue(), "No match", 'SWITCH(A4,1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); oParser = new parserFormula( 'SWITCH(A5,1,"Sunday",7,"Saturday","weekday")', "A1", ws ); ok( oParser.parse(), 'SWITCH(A5,1,"Sunday",7,"Saturday","weekday")' ); strictEqual( oParser.calculate().getValue(), "weekday", 'SWITCH(A5,1,"Sunday",7,"Saturday","weekday")' ); oParser = new parserFormula( 'SWITCH(A6,1,"Sunday",2,"Monday",3,"Tuesday","No match")', "A1", ws ); ok( oParser.parse(), 'SWITCH(A6,1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); strictEqual( oParser.calculate().getValue(), "Tuesday", 'SWITCH(A6,1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); oParser = new parserFormula( 'SWITCH(122,1,"Sunday",2,"Monday",3,"Tuesday","No match")', "A1", ws ); ok( oParser.parse(), 'SWITCH(122,1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); strictEqual( oParser.calculate().getValue(), "No match", 'SWITCH(122,1,"Sunday",2,"Monday",3,"Tuesday","No match")' ); oParser = new parserFormula( 'SWITCH({1,"2asd",3},{12,2,3},{"asd",2,3,4})', "A1", ws ); ok( oParser.parse(), 'SWITCH({1,"2asd",3},{12,2,3},{"asd",2,3,4})' ); strictEqual( oParser.calculate().getValue(), "#N/A", 'SWITCH({1,"2asd",3},{12,2,3},{"asd",2,3,4})' ); oParser = new parserFormula( 'SWITCH({"asd1","2asd",3},{"asd1",1,3},"sdf")', "A1", ws ); ok( oParser.parse(), 'SWITCH({"asd1","2asd",3},{"asd1",1,3},"sdf")' ); strictEqual( oParser.calculate().getValue(), "sdf", 'SWITCH({"asd1","2asd",3},{"asd1",1,3},"sdf")' ); testArrayFormulaEqualsValues("1,3.123,-4,#N/A;2,4,5,#N/A;#N/A,#N/A,#N/A,#N/A", "SWITCH(A1:C2,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,1,1,#N/A;1,1,1,#N/A;#N/A,#N/A,#N/A,#N/A", "SWITCH(A1:C2,A1:C2,A1:A1,A1:C2,A1:C2)"); testArrayFormulaEqualsValues("1,1,1,#N/A;2,2,2,#N/A;#N/A,#N/A,#N/A,#N/A", "SWITCH(A1:C2,A1:C2,A1:A2,A1:C2,A1:A2,A1:C2)"); } ); test( "Test: \"VAR\"", function () { function _var( x ) { var sumSQRDeltaX = 0, _x = 0, xLength = 0, standDev = 0, sumSQRDeltaXDivstandDev = 0; for ( var i = 0; i < x.length; i++ ) { _x += x[i]; xLength++; } _x /= xLength; for ( var i = 0; i < x.length; i++ ) { sumSQRDeltaX += Math.pow( x[i] - _x, 2 ); } return toFixed( sumSQRDeltaX / (xLength - 1) ) } oParser = new parserFormula( "VAR(10.5,12.4,19.4,23.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _var( [10.5, 12.4, 19.4, 23.2] ) ); oParser = new parserFormula( "VAR(10.5,{12.4,19.4},23.2)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _var( [10.5, 12.4, 19.4, 23.2] ) ); oParser = new parserFormula( "VAR(10.5,12.4,19.4)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _var( [10.5, 12.4, 19.4] ) ); oParser = new parserFormula( "VAR(1)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "VAR({1})", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); ws.getRange2( "A202" ).setValue( "1345" ); ws.getRange2( "A203" ).setValue( "" ); ws.getRange2( "A204" ).setValue( "" ); oParser = new parserFormula( "VAR(A202)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "VAR(A202:A204)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); oParser = new parserFormula( "VAR(#REF!)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); } ); test( "Test: \"VAR.P\"", function () { ws.getRange2( "A202" ).setValue( "1345" ); ws.getRange2( "A203" ).setValue( "1301" ); ws.getRange2( "A204" ).setValue( "1368" ); ws.getRange2( "A205" ).setValue( "1322" ); ws.getRange2( "A206" ).setValue( "1310" ); ws.getRange2( "A207" ).setValue( "1370" ); ws.getRange2( "A208" ).setValue( "1318" ); ws.getRange2( "A209" ).setValue( "1350" ); ws.getRange2( "A210" ).setValue( "1303" ); ws.getRange2( "A211" ).setValue( "1299" ); oParser = new parserFormula( "VAR.P(A202:A211)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 678.84 ); testArrayFormula2("VAR.P", 1, 8, null, true); } ); test( "Test: \"VAR.S\"", function () { ws.getRange2( "A202" ).setValue( "1345" ); ws.getRange2( "A203" ).setValue( "1301" ); ws.getRange2( "A204" ).setValue( "1368" ); ws.getRange2( "A205" ).setValue( "1322" ); ws.getRange2( "A206" ).setValue( "1310" ); ws.getRange2( "A207" ).setValue( "1370" ); ws.getRange2( "A208" ).setValue( "1318" ); ws.getRange2( "A209" ).setValue( "1350" ); ws.getRange2( "A210" ).setValue( "1303" ); ws.getRange2( "A211" ).setValue( "1299" ); oParser = new parserFormula( "VAR.S(A202:A211)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 754.27 ); testArrayFormula2("VAR.S", 1, 8, null, true); } ); test( "Test: \"VARPA\"", function () { ws.getRange2( "A202" ).setValue( "1345" ); ws.getRange2( "A203" ).setValue( "1301" ); ws.getRange2( "A204" ).setValue( "1368" ); ws.getRange2( "A205" ).setValue( "1322" ); ws.getRange2( "A206" ).setValue( "1310" ); ws.getRange2( "A207" ).setValue( "1370" ); ws.getRange2( "A208" ).setValue( "1318" ); ws.getRange2( "A209" ).setValue( "1350" ); ws.getRange2( "A210" ).setValue( "1303" ); ws.getRange2( "A211" ).setValue( "1299" ); oParser = new parserFormula( "VARPA(A202:A211)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 678.84 ); testArrayFormula2("VARPA", 1, 8, null, true); } ); /* * Lookup and Reference */ test( "Test: \"HLOOKUP\"", function () { ws.getRange2( "A401" ).setValue( "Axles" );ws.getRange2( "B401" ).setValue( "Bearings" );ws.getRange2( "C401" ).setValue( "Bolts" ); ws.getRange2( "A402" ).setValue( "4" );ws.getRange2( "B402" ).setValue( "6" );ws.getRange2( "C402" ).setValue( "9" ); ws.getRange2( "A403" ).setValue( "5" );ws.getRange2( "B403" ).setValue( "7" );ws.getRange2( "C403" ).setValue( "10" ); ws.getRange2( "A404" ).setValue( "6" );ws.getRange2( "B404" ).setValue( "8" );ws.getRange2( "C404" ).setValue( "11" ); oParser = new parserFormula( "HLOOKUP(\"Axles\",A401:C404,2,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "HLOOKUP(\"Bearings\",A401:C404,3,FALSE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 7 ); oParser = new parserFormula( "HLOOKUP(\"B\",A401:C404,3,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "HLOOKUP(\"Bolts\",A401:C404,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 11 ); oParser = new parserFormula( "HLOOKUP(3,{1,2,3;\"a\",\"b\",\"c\";\"d\",\"e\",\"f\"},2,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "c" ); /*oParser = new parserFormula( "HLOOKUP(1,{1,2,3;2,3,4},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "HLOOKUP(1,{1,2,3;2,3,4},3,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "HLOOKUP(1,{1,2,3;2,3,4},3,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "HLOOKUP({2,3,4},{1,2,3;2,3,4},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "HLOOKUP({2,3,4},{1,2,3;2,3,4},{4,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "HLOOKUP({2,3,4},{1,2,3;2,3,4},{1,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "HLOOKUP({2,3,4},{1,2,3;2,3,4;6,7,8},{1,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "HLOOKUP({5,3,4},{1,2,3;2,3,4;6,7,8},{1,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "HLOOKUP(4,{1,2,3;2,3,4;6,7,8},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "HLOOKUP(4,{1,2,3;2,3,4;6,7,8},3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 8 ); oParser = new parserFormula( "HLOOKUP(4,{1,2,3;2,3,4;6,7,8},5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "HLOOKUP({2,3,4},{1,2,3;2,3,4;6,7,8},1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 );*/ } ); test( "Test: \"VLOOKUP\"", function () { ws.getRange2( "A501" ).setValue( "Density" );ws.getRange2( "B501" ).setValue( "Bearings" );ws.getRange2( "C501" ).setValue( "Bolts" ); ws.getRange2( "A502" ).setValue( "0.457" );ws.getRange2( "B502" ).setValue( "3.55" );ws.getRange2( "C502" ).setValue( "500" ); ws.getRange2( "A503" ).setValue( "0.525" );ws.getRange2( "B503" ).setValue( "3.25" );ws.getRange2( "C503" ).setValue( "400" ); ws.getRange2( "A504" ).setValue( "0.616" );ws.getRange2( "B504" ).setValue( "2.93" );ws.getRange2( "C504" ).setValue( "300" ); ws.getRange2( "A505" ).setValue( "0.675" );ws.getRange2( "B505" ).setValue( "2.75" );ws.getRange2( "C505" ).setValue( "250" ); ws.getRange2( "A506" ).setValue( "0.746" );ws.getRange2( "B506" ).setValue( "2.57" );ws.getRange2( "C506" ).setValue( "200" ); ws.getRange2( "A507" ).setValue( "0.835" );ws.getRange2( "B507" ).setValue( "2.38" );ws.getRange2( "C507" ).setValue( "15" ); ws.getRange2( "A508" ).setValue( "0.946" );ws.getRange2( "B508" ).setValue( "2.17" );ws.getRange2( "C508" ).setValue( "100" ); ws.getRange2( "A509" ).setValue( "1.09" );ws.getRange2( "B509" ).setValue( "1.95" );ws.getRange2( "C509" ).setValue( "50" ); ws.getRange2( "A510" ).setValue( "1.29" );ws.getRange2( "B510" ).setValue( "1.71" );ws.getRange2( "C510" ).setValue( "0" ); oParser = new parserFormula( "VLOOKUP(1,A502:C510,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2.17 ); oParser = new parserFormula( "VLOOKUP(1,A502:C510,3,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 100.00 ); oParser = new parserFormula( "VLOOKUP(2,A502:C510,2,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1.71 ); oParser = new parserFormula( "VLOOKUP(1,{1,2,3;2,3,4},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "VLOOKUP(1,{1,2,3;2,3,4},3,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "VLOOKUP(1,{1,2,3;2,3,4},3,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "VLOOKUP({2,3,4},{1,2,3;2,3,4},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "VLOOKUP({2,3,4},{1,2,3;2,3,4},{4,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "VLOOKUP({2,3,4},{1,2,3;2,3,4},{1,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "VLOOKUP({2,3,4},{1,2,3;2,3,4;6,7,8},{1,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "VLOOKUP({5,3,4},{1,2,3;2,3,4;6,7,8},{1,5,6})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "VLOOKUP(4,{1,2,3;2,3,4;6,7,8},2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "VLOOKUP(4,{1,2,3;2,3,4;6,7,8},3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 4 ); oParser = new parserFormula( "VLOOKUP(4,{1,2,3;2,3,4;6,7,8},5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "VLOOKUP({2,3,4},{1,2,3;2,3,4;6,7,8},1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); } ); test( "Test: \"LOOKUP\"", function () { ws.getRange2( "A102" ).setValue( "4.14" ); ws.getRange2( "A103" ).setValue( "4.19" ); ws.getRange2( "A104" ).setValue( "5.17" ); ws.getRange2( "A105" ).setValue( "5.77" ); ws.getRange2( "A106" ).setValue( "6.39" ); ws.getRange2( "B102" ).setValue( "red" ); ws.getRange2( "B103" ).setValue( "orange" ); ws.getRange2( "B104" ).setValue( "yellow" ); ws.getRange2( "B105" ).setValue( "green" ); ws.getRange2( "B106" ).setValue( "blue" ); oParser = new parserFormula( "LOOKUP(4.19, A102:A106, B102:B106)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "orange" ); oParser = new parserFormula( "LOOKUP(5.75, A102:A106, B102:B106)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "yellow" ); oParser = new parserFormula( "LOOKUP(7.66, A102:A106, B102:B106)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "blue" ); oParser = new parserFormula( "LOOKUP(0, A102:A106, B102:B106)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); ws.getRange2( "C101" ).setValue( "4.14" ); ws.getRange2( "D101" ).setValue( "4.19" ); ws.getRange2( "E101" ).setValue( "5.17" ); ws.getRange2( "F101" ).setValue( "5.77" ); ws.getRange2( "G101" ).setValue( "6.39" ); ws.getRange2( "H101" ).setValue( "7.99" ); ws.getRange2( "C102" ).setValue( "red" ); ws.getRange2( "D102" ).setValue( "orange" ); ws.getRange2( "E102" ).setValue( "yellow" ); ws.getRange2( "F102" ).setValue( "green" ); ws.getRange2( "G102" ).setValue( "blue" ); ws.getRange2( "H102" ).setValue( "black" ); oParser = new parserFormula( "LOOKUP(4.19,C101:H101,C102:H102)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "orange" ); oParser = new parserFormula( "LOOKUP(5.75,C101:H101,C102:H102)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "yellow" ); oParser = new parserFormula( "LOOKUP(7.66,C101:H101,C102:H102)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "blue" ); oParser = new parserFormula( "LOOKUP(0,C101:H101,C102:H102)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "LOOKUP(5.17,C101:H101,C102:H102)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "yellow" ); oParser = new parserFormula( "LOOKUP(9,C101:H101,C102:H102)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), "black" ); }); test( "Test: \"MATCH\"", function () { ws.getRange2( "A551" ).setValue( "28" ); ws.getRange2( "A552" ).setValue( "29" ); ws.getRange2( "A553" ).setValue( "31" ); ws.getRange2( "A554" ).setValue( "45" ); ws.getRange2( "A555" ).setValue( "89" ); ws.getRange2( "B551" ).setValue( "89" ); ws.getRange2( "B552" ).setValue( "45" ); ws.getRange2( "B553" ).setValue( "31" ); ws.getRange2( "B554" ).setValue( "29" ); ws.getRange2( "B555" ).setValue( "28" ); ws.getRange2( "C551" ).setValue( "89" ); ws.getRange2( "C552" ).setValue( "45" ); ws.getRange2( "C553" ).setValue( "31" ); ws.getRange2( "C554" ).setValue( "29" ); ws.getRange2( "C555" ).setValue( "28" ); oParser = new parserFormula( "MATCH(30,A551:A555,-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "MATCH(30,A551:A555,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); oParser = new parserFormula( "MATCH(30,A551:A555,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "MATCH(30,B551:B555)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "MATCH(30,B551:B555,-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "MATCH(30,B551:B555,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "MATCH(31,C551:C555,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "MATCH(\"b\",{\"a\";\"b\";\"c\"},0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2 ); ws.getRange2( "F3" ).setValue( "" ); ws.getRange2( "F106" ).setValue( "1" ); ws.getRange2( "F107" ).setValue( "" ); ws.getRange2( "F108" ).setValue( "" ); ws.getRange2( "F109" ).setValue( "" ); ws.getRange2( "F110" ).setValue( "2" ); ws.getRange2( "F111" ).setValue( "123" ); ws.getRange2( "F112" ).setValue( "4" ); ws.getRange2( "F113" ).setValue( "5" ); ws.getRange2( "F114" ).setValue( "6" ); ws.getRange2( "F115" ).setValue( "0" ); ws.getRange2( "F116" ).setValue( "" ); ws.getRange2( "F117" ).setValue( "0" ); oParser = new parserFormula( "MATCH(F3,F106:F114,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "MATCH(F3,F106:F117,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( "MATCH(0,F106:F114,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); oParser = new parserFormula( "MATCH(0,F106:F117,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10 ); oParser = new parserFormula( "MATCH(6,F106:F117,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 9 ); oParser = new parserFormula( "MATCH(6,F106:F117,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 5 ); oParser = new parserFormula( "MATCH(6,F106:F117,-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); //TODO excel по-другому работает /*oParser = new parserFormula( "MATCH(123,F106:F117,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 );*/ } ); test( "Test: \"INDEX\"", function () { ws.getRange2( "A651" ).setValue( "1" ); ws.getRange2( "A652" ).setValue( "2" ); ws.getRange2( "A653" ).setValue( "3" ); ws.getRange2( "A654" ).setValue( "4" ); ws.getRange2( "A655" ).setValue( "5" ); ws.getRange2( "B651" ).setValue( "6" ); ws.getRange2( "B652" ).setValue( "7" ); ws.getRange2( "B653" ).setValue( "8" ); ws.getRange2( "B654" ).setValue( "9" ); ws.getRange2( "B655" ).setValue( "10" ); ws.getRange2( "C651" ).setValue( "11" ); ws.getRange2( "C652" ).setValue( "12" ); ws.getRange2( "C653" ).setValue( "13" ); ws.getRange2( "C654" ).setValue( "14" ); ws.getRange2( "C655" ).setValue( "15" ); oParser = new parserFormula( "INDEX({\"Apples\",\"Lemons\";\"Bananas\",\"Pears\"},2,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Pears" ); oParser = new parserFormula( "INDEX({\"Apples\",\"Lemons\";\"Bananas\",\"Pears\"},1,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Lemons" ); oParser = new parserFormula( "INDEX(\"Apples\",2,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "INDEX({\"Apples\",\"Lemons\"},,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "Lemons" ); //данная функция возвращает area а далее уже в функции simplifyRefType находится резальтат // - пересечение а ячейкой, где располагается формула oParser = new parserFormula( "INDEX(A651:C655,,2)", "A2", ws ); ok( oParser.parse() ); var parent = AscCommonExcel.g_oRangeCache.getAscRange(oParser.parent); strictEqual( oParser.simplifyRefType(oParser.calculate(), ws, parent.r1, parent.c1).getValue(), "#VALUE!" ); oParser = new parserFormula( "INDEX(A651:C655,,2)", "D651", ws ); ok( oParser.parse() ); parent = AscCommonExcel.g_oRangeCache.getAscRange(oParser.parent); strictEqual( oParser.simplifyRefType(oParser.calculate(), ws, parent.r1, parent.c1).getValue(), 6 ); oParser = new parserFormula( "INDEX(A651:C655,,2)", "D652", ws ); ok( oParser.parse() ); parent = AscCommonExcel.g_oRangeCache.getAscRange(oParser.parent); strictEqual( oParser.simplifyRefType(oParser.calculate(), ws, parent.r1, parent.c1).getValue(), 7 ); oParser = new parserFormula( "INDEX(A651:C655,,3)", "E652", ws ); ok( oParser.parse() ); parent = AscCommonExcel.g_oRangeCache.getAscRange(oParser.parent); strictEqual( oParser.simplifyRefType(oParser.calculate(), ws, parent.r1, parent.c1).getValue(), 12 ); oParser = new parserFormula( "INDEX(A651:C655,,4)", "E652", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "INDEX(A651:C655,,14)", "E652", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "INDEX(A651:C655,3,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 8 ); oParser = new parserFormula( "INDEX(A651:C655,10,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "INDEX(A651:C651,1,3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 11 ); oParser = new parserFormula( "INDEX(A651:C651,1,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 6 ); oParser = new parserFormula( "INDEX(A651:C651,0,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 1 ); oParser = new parserFormula( "INDEX(A651:C651,1,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 1 ); oParser = new parserFormula( "INDEX(A651:C651,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 6 ); oParser = new parserFormula( "INDEX(A651:C651,3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 11 ); oParser = new parserFormula( "INDEX(A651:C651,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "INDEX(A651:C652,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "INDEX(A651:C652,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "INDEX(A651:C652,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); oParser = new parserFormula( "INDEX(A651:C651,1,1,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 1 ); oParser = new parserFormula( "INDEX(A651:C651,1,1,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#REF!" ); } ); test( "Test: \"INDIRECT\"", function () { ws.getRange2( "A22" ).setValue( "B22" ); ws.getRange2( "B22" ).setValue( "1.333" ); ws.getRange2( "A23" ).setValue( "B23" ); ws.getRange2( "B23" ).setValue( "45" ); ws.getRange2( "A24" ).setValue( "George" ); ws.getRange2( "B24" ).setValue( "10" ); ws.getRange2( "A25" ).setValue( "25" ); ws.getRange2( "B25" ).setValue( "62" ); oParser = new parserFormula( "INDIRECT(A22)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 1.333 ); oParser = new parserFormula( "INDIRECT(A23)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 45 ); /*oParser = new parserFormula( "INDIRECT(A24)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 10 );*/ oParser = new parserFormula( 'INDIRECT("B"&A25)', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().getValue(), 62 ); } ); test( "Test: \"OFFSET\"", function () { ws.getRange2( "C150" ).setValue( "1" ); ws.getRange2( "D150" ).setValue( "2" ); ws.getRange2( "E150" ).setValue( "3" ); ws.getRange2( "C151" ).setValue( "2" ); ws.getRange2( "D151" ).setValue( "3" ); ws.getRange2( "E151" ).setValue( "4" ); ws.getRange2( "C152" ).setValue( "3" ); ws.getRange2( "D152" ).setValue( "4" ); ws.getRange2( "E152" ).setValue( "5" ); oParser = new parserFormula( "OFFSET(C3,2,3,1,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "F5" ); oParser = new parserFormula( "SUM(OFFSET(C151:E155,-1,0,3,3))", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 27 ); oParser = new parserFormula( "OFFSET(B3, -2, 0, 1, 1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "B1" ); oParser = new parserFormula( "OFFSET(B3, 0, 0, -1, 1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "B3" ); oParser = new parserFormula( "OFFSET(B3, 0, 0, -1, -1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "B3" ); oParser = new parserFormula( "OFFSET(B3, 0, 0,,)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "B3" ); oParser = new parserFormula( "OFFSET(B3, 0, 0, 1,)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "B3" ); oParser = new parserFormula( "OFFSET(B3, 0, 0, -2, -2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "A2:B3" ); oParser = new parserFormula( "OFFSET(B3, 0, 0, -1, -2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "A3:B3" ); oParser = new parserFormula( "OFFSET(B3, 0, 0, 0, -2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "#REF!" ); oParser = new parserFormula( "OFFSET(B3, 0, 0, 2, 0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "#REF!" ); oParser = new parserFormula( "OFFSET(C3:D4, 0, 0, 2, 2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "C3:D4" ); oParser = new parserFormula( "OFFSET(C3:D4, 0, 0, 3, 3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "C3:E5" ); oParser = new parserFormula( "OFFSET(C3:D4, 2, 2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "E5:F6" ); oParser = new parserFormula( "OFFSET(C3:D4,2,2,3,3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "E5:G7" ); oParser = new parserFormula( "OFFSET(C3:E6, 0, 0, 3, 3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "C3:E5" ); oParser = new parserFormula( "OFFSET(C3:D4, 0, 0, -2, -2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "B2:C3" ); oParser = new parserFormula( "OFFSET(C3:D4, 0, 0, -3, -3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "A1:C3" ); oParser = new parserFormula( "OFFSET(C3:E6, 0, 0, -3, -3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "A1:C3" ); oParser = new parserFormula( "OFFSET(F10:M17, 0, 0, -7,-5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "B4:F10" ); } ); /* * Financial */ test( "Test: \"FV\"", function () { function fv( rate, nper, pmt, pv, type ) { var res; if ( type === undefined || type === null ) type = 0; if ( pv === undefined || pv === null ) pv = 0; if ( rate != 0 ) { res = -1 * ( pv * Math.pow( 1 + rate, nper ) + pmt * ( 1 + rate * type ) * ( Math.pow( 1 + rate, nper ) - 1) / rate ); } else { res = -1 * ( pv + pmt * nper ); } return res; } oParser = new parserFormula( "FV(0.06/12,10,-200,-500,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fv( 0.06 / 12, 10, -200, -500, 1 ) ); oParser = new parserFormula( "FV(0.12/12,12,-1000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fv( 0.12 / 12, 12, -1000 ) ); oParser = new parserFormula( "FV(0.11/12,35,-2000,,1)", "A2", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - fv( 0.11 / 12, 35, -2000, null, 1 ) ) < dif ); oParser = new parserFormula( "FV(0.06/12,12,-100,-1000,1)", "A2", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - fv( 0.06 / 12, 12, -100, -1000, 1 ) ) < dif ); testArrayFormula2("FV", 3, 5); } ); test( "Test: \"PMT\"", function () { function pmt( rate, nper, pv, fv, type ) { var res; if ( type === undefined || type === null ) type = 0; if ( fv === undefined || fv === null ) fv = 0; if ( rate != 0 ) { res = -1 * ( pv * Math.pow( 1 + rate, nper ) + fv ) / ( ( 1 + rate * type ) * ( Math.pow( 1 + rate, nper ) - 1 ) / rate ); } else { res = -1 * ( pv + fv ) / nper; } return res; } oParser = new parserFormula( "PMT(0.08/12,10,10000)", "A2", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - pmt( 0.08 / 12, 10, 10000 ) ) < dif ); oParser = new parserFormula( "PMT(0.08/12,10,10000,0,1)", "A2", ws ); ok( oParser.parse() ); ok( Math.abs( oParser.calculate().getValue() - pmt( 0.08 / 12, 10, 10000, 0, 1 ) ) < dif ); testArrayFormula2("PMT", 3, 5); } ); test( "Test: \"NPER\"", function () { function nper(rate,pmt,pv,fv,type){ if ( rate === undefined || rate === null ) rate = 0; if ( pmt === undefined || pmt === null ) pmt = 0; if ( pv === undefined || pv === null ) pv = 0; if ( type === undefined || type === null ) type = 0; if ( fv === undefined || fv === null ) fv = 0; var res; if ( rate != 0 ) { res = (-fv * rate + pmt * (1 + rate * type)) / (rate * pv + pmt * (1 + rate * type)) res = Math.log( res ) / Math.log( 1+rate ) } else { res = (- pv - fv )/ pmt ; } return res; } oParser = new parserFormula( "NPER(0.12/12,-100,-1000,10000,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), nper(0.12/12,-100,-1000,10000,1) ); oParser = new parserFormula( "NPER(0.12/12,-100,-1000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), nper(0.12/12,-100,-1000) ); testArrayFormula2("NPER", 3, 5); } ); test( "Test: \"PV\"", function () { function pv( rate, nper, pmt, fv, type ) { if ( rate != 0 ) { return -1 * ( fv + pmt * (1 + rate * type) * ( (Math.pow( (1 + rate), nper ) - 1) / rate ) ) / Math.pow( 1 + rate, nper ) } else { return -1 * ( fv + pmt * nper ); } } oParser = new parserFormula( "PV(0.08/12,12*20,500,,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), pv( 0.08 / 12, 12 * 20, 500, 0, 0 ) ); oParser = new parserFormula( "PV(0,12*20,500,,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), pv( 0, 12 * 20, 500, 0, 0 ) ); testArrayFormula2("PV", 3, 5); } ); test( "Test: \"NPV\"", function () { oParser = new parserFormula( "NPV(0.1,-10000,3000,4200,6800)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1188.4434123352216 ); } ); test( "Test: \"EFFECT\"", function () { function effect(nr,np){ if( nr <= 0 || np < 1 ) return "#NUM!"; return Math.pow( ( 1 + nr/np ), np ) - 1; } oParser = new parserFormula( "EFFECT(0.0525,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), effect(0.0525,4) ); oParser = new parserFormula( "EFFECT(0.0525,-4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), effect(0.0525,-4) ); oParser = new parserFormula( "EFFECT(0.0525,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), effect(0.0525,1) ); oParser = new parserFormula( "EFFECT(-1,54)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), effect(-1,54) ); testArrayFormula2("EFFECT", 2, 2, true) } ); test( "Test: \"ISPMT\"", function () { function ISPMT( rate, per, nper, pv ){ return pv * rate * (per / nper - 1.0) } oParser = new parserFormula( "ISPMT(0.1/12,1,3*12,8000000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ISPMT(0.1/12,1,3*12,8000000) ); oParser = new parserFormula( "ISPMT(0.1,1,3,8000000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ISPMT(0.1,1,3,8000000) ); testArrayFormula2("ISPMT", 4, 4); } ); test( "Test: \"ISFORMULA\"", function () { ws.getRange2( "C150" ).setValue( "=TODAY()" ); ws.getRange2( "C151" ).setValue( "7" ); ws.getRange2( "C152" ).setValue( "Hello, world!" ); ws.getRange2( "C153" ).setValue( "=3/0" ); oParser = new parserFormula( "ISFORMULA(C150)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "TRUE" ); oParser = new parserFormula( "ISFORMULA(C151)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "FALSE" ); oParser = new parserFormula( "ISFORMULA(C152)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "FALSE" ); oParser = new parserFormula( "ISFORMULA(C153)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().toString(), "TRUE" ); testArrayFormulaEqualsValues("FALSE,FALSE,FALSE,#N/A;FALSE,FALSE,FALSE,#N/A;#N/A,#N/A,#N/A,#N/A", "ISFORMULA(A1:C2)"); testArrayFormulaEqualsValues("FALSE,FALSE,#N/A,#N/A;FALSE,FALSE,#N/A,#N/A;FALSE,FALSE,#N/A,#N/A", "ISFORMULA(A1:B1)"); testArrayFormulaEqualsValues("FALSE,FALSE,FALSE,FALSE;FALSE,FALSE,FALSE,FALSE;FALSE,FALSE,FALSE,FALSE", "ISFORMULA(A1)"); } ); test( "Test: \"IFNA\"", function () { oParser = new parserFormula( 'IFNA(MATCH(30,B1:B5,0),"Not found")', "A2", ws ); ok( oParser.parse(), 'IFNA(MATCH(30,B1:B5,0),"Not found")' ); strictEqual( oParser.calculate().getValue(), "Not found", 'IFNA(MATCH(30,B1:B5,0),"Not found")' ); } ); test( "Test: \"IFERROR\"", function () { ws.getRange2( "A2" ).setValue( "210" ); ws.getRange2( "A3" ).setValue( "55" ); ws.getRange2( "A4" ).setValue( "" ); ws.getRange2( "B2" ).setValue( "35" ); ws.getRange2( "B3" ).setValue( "0" ); ws.getRange2( "B4" ).setValue( "23" ); oParser = new parserFormula( 'IFERROR(A2/B2,"Error in calculation")', "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 6 ); oParser = new parserFormula( 'IFERROR(A3/B3,"Error in calculation")', "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 'Error in calculation'); oParser = new parserFormula( 'IFERROR(A4/B4,"Error in calculation")', "A22", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0); //testArrayFormula2("IFERROR", 2, 2); } ); test( "Test: \"XNPV\"", function () { function xnpv( rate, valueArray, dateArray ){ var res = 0, r = rate; var d1 = dateArray[0]; for( var i = 0; i < dateArray.length; i++ ){ res += valueArray[i] / ( Math.pow( ( 1 + r ), ( dateArray[i] - d1 ) / 365 ) ) } return res; } ws.getRange2( "A701" ).setValue( "39448" ); ws.getRange2( "A702" ).setValue( "39508" ); ws.getRange2( "A703" ).setValue( "39751" ); ws.getRange2( "A704" ).setValue( "39859" ); ws.getRange2( "A705" ).setValue( "39904" ); oParser = new parserFormula( "XNPV(0.09,{-10000,2750,4250,3250,2750},A701:A705)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), xnpv( 0.09, [-10000,2750,4250,3250,2750], [39448,39508,39751,39859,39904] ) ); ws.getRange2( "A705" ).setValue( "43191" ); oParser = new parserFormula( "XNPV(0.09,{-10000,2750,4250,3250,2750},A701:A705)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), xnpv( 0.09, [-10000,2750,4250,3250,2750], [39448,39508,39751,39859,43191] ) ); } ); test( "Test: \"IRR\"", function () { function irr( costArr, x ){ if (!x) x = 0.1 var nC = 0, g_Eps = 1e-7, fEps = 1.0, fZ = 0, fN = 0, xN = 0, nIM = 100, nMC = 0,arr0 = costArr[0], arrI, wasNegative = false, wasPositive = false; if( arr0 < 0 ) wasNegative = true; else if( arr0 > 0 ) wasPositive = true; while(fEps > g_Eps && nMC < nIM ){ nC = 0; fZ = 0; fN = 0; fZ += costArr[0]/Math.pow( 1.0 + x, nC ); fN += -nC * costArr[0]/Math.pow( 1 + x, nC + 1 ); nC++; for(var i = 1; i < costArr.length; i++){ arrI = costArr[i]; fZ += arrI/Math.pow( 1.0 + x, nC ); fN += -nC * arrI/Math.pow( 1 + x, nC + 1 ); if( arrI < 0 ) wasNegative = true; else if( arrI > 0 ) wasPositive = true nC++ } xN = x - fZ / fN; nMC ++; fEps = Math.abs( xN - x ); x = xN; } if( !(wasNegative && wasPositive) ) return "#NUM!"; if (fEps < g_Eps) return x; else return "#NUM!"; } oParser = new parserFormula( "IRR({-70000,12000,15000,18000,21000})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -0.021244848273410923 ); ws.getRange2( "A705" ).setValue( "43191" ); oParser = new parserFormula( "IRR({-70000,12000,15000,18000,21000,26000})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0.08663094803653171 ); oParser = new parserFormula( "IRR({-70000,12000,15000},-0.1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -0.44350694133450463 ); oParser = new parserFormula( "IRR({-70000},-0.1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); //TODO пересмотреть тест для этой функции //testArrayFormula2("IRR", 1, 2, true) } ); test( "Test: \"ACCRINT\"", function () { oParser = new parserFormula( "ACCRINT(DATE(2006,3,1),DATE(2006,9,1),DATE(2006,5,1),0.1,1100,2,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 18.333333333333332 ); oParser = new parserFormula( "ACCRINT(DATE(2006,3,1),DATE(2006,9,1),DATE(2006,5,1),0.1,,2,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 16.666666666666664 ); oParser = new parserFormula( "ACCRINT(DATE(2008,3,1),DATE(2008,8,31),DATE(2010,5,1),0.1,1000,2,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 216.94444444444444 ); oParser = new parserFormula( "ACCRINT(DATE(2008,3,1),DATE(2008,8,31),DATE(2010,5,1),0.1,1000,2,0,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 216.94444444444444 ); oParser = new parserFormula( "ACCRINT(DATE(2008,3,1),DATE(2008,8,31),DATE(2010,5,1),0.1,1000,2,0,FALSE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 216.66666666666666 ); testArrayFormula2("ACCRINT", 6, 8, true); } ); test( "Test: \"ACCRINTM\"", function () { oParser = new parserFormula( "ACCRINTM(DATE(2006,3,1),DATE(2006,5,1),0.1,1100,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 18.333333333333332 ); oParser = new parserFormula( "ACCRINTM(DATE(2006,3,1),DATE(2006,5,1),0.1,,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 16.666666666666664 ); oParser = new parserFormula( "ACCRINTM(DATE(2006,3,1),DATE(2006,5,1),0.1,)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 16.666666666666664 ); testArrayFormula2("ACCRINTM", 4, 5, true) } ); test( "Test: \"AMORDEGRC\"", function () { oParser = new parserFormula( "AMORDEGRC(2400,DATE(2008,8,19),DATE(2008,12,31),300,1,0.15,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 776 ); oParser = new parserFormula( "AMORDEGRC(2400,DATE(2008,8,19),DATE(2008,12,31),300,1,0.50,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "AMORDEGRC(2400,DATE(2008,8,19),DATE(2008,12,31),300,1,0.20,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 819 ); oParser = new parserFormula( "AMORDEGRC(2400,DATE(2008,8,19),DATE(2008,12,31),300,1,0.33,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 972 ); testArrayFormula2("AMORDEGRC", 6, 7, true); } ); test( "Test: \"AMORLINC\"", function () { oParser = new parserFormula( "AMORLINC(2400,DATE(2008,8,19),DATE(2008,12,31),300,1,0.15,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 360 ); oParser = new parserFormula( "AMORLINC(2400,DATE(2008,8,19),DATE(2008,12,31),300,1,0.70,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1484 ); testArrayFormula2("AMORLINC", 6, 7, true); } ); test( "Test: \"CUMIPMT\"", function () { function cumipmt(fRate, nNumPeriods, fVal, nStartPer, nEndPer, nPayType){ var fRmz, fZinsZ; if( nStartPer < 1 || nEndPer < nStartPer || fRate <= 0.0 || nEndPer > nNumPeriods || nNumPeriods <= 0 || fVal <= 0.0 || ( nPayType != 0 && nPayType != 1 ) ) return "#NUM!" fRmz = _getPMT( fRate, nNumPeriods, fVal, 0.0, nPayType ); fZinsZ = 0.0; if( nStartPer == 1 ) { if( nPayType <= 0 ) fZinsZ = -fVal; nStartPer++; } for( var i = nStartPer ; i <= nEndPer ; i++ ) { if( nPayType > 0 ) fZinsZ += _getFV( fRate, i - 2, fRmz, fVal, 1 ) - fRmz; else fZinsZ += _getFV( fRate, i - 1, fRmz, fVal, 0 ); } fZinsZ *= fRate; return fZinsZ; } oParser = new parserFormula( "CUMIPMT(0.09/12,30*12,125000,1,1,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), cumipmt(0.09/12,30*12,125000,1,1,0) ); oParser = new parserFormula( "CUMIPMT(0.09/12,30*12,125000,13,24,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), cumipmt(0.09/12,30*12,125000,13,24,0) ); testArrayFormula2("CUMIPMT", 6, 6, true); } ); test( "Test: \"CUMPRINC\"", function () { function cumpring(fRate, nNumPeriods, fVal, nStartPer, nEndPer, nPayType){ var fRmz, fKapZ; if( nStartPer < 1 || nEndPer < nStartPer || nEndPer < 1 || fRate <= 0 || nNumPeriods <= 0 || fVal <= 0 || ( nPayType != 0 && nPayType != 1 ) ) return "#NUM!" fRmz = _getPMT( fRate, nNumPeriods, fVal, 0.0, nPayType ); fKapZ = 0.0; var nStart = nStartPer; var nEnd = nEndPer; if( nStart == 1 ) { if( nPayType <= 0 ) fKapZ = fRmz + fVal * fRate; else fKapZ = fRmz; nStart++; } for( var i = nStart ; i <= nEnd ; i++ ) { if( nPayType > 0 ) fKapZ += fRmz - ( _getFV( fRate, i - 2, fRmz, fVal, 1 ) - fRmz ) * fRate; else fKapZ += fRmz - _getFV( fRate, i - 1, fRmz, fVal, 0 ) * fRate; } return fKapZ } oParser = new parserFormula( "CUMPRINC(0.09/12,30*12,125000,1,1,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), cumpring(0.09/12,30*12,125000,1,1,0) ); oParser = new parserFormula( "CUMPRINC(0.09/12,30*12,-125000,1,1,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), cumpring(0.09/12,30*12,-125000,1,1,0) ); oParser = new parserFormula( "CUMPRINC(0.09/12,30*12,125000,13,24,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), cumpring(0.09/12,30*12,125000,13,24,0) ); testArrayFormula2("CUMPRINC", 6, 6, true); } ); test( "Test: \"NOMINAL\"", function () { function nominal(rate,np){ if( rate <= 0 || np < 1 ) return "#NUM!" return ( Math.pow( rate + 1, 1 / np ) - 1 ) * np; } oParser = new parserFormula( "NOMINAL(0.053543,4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), nominal(0.053543,4) ); oParser = new parserFormula( "NOMINAL(0.053543,-4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), nominal(0.053543,-4) ); testArrayFormula2("NOMINAL", 2, 2, true); } ); test( "Test: \"NOT\"", function () { testArrayFormula2("NOT", 1, 1); } ); test( "Test: \"FVSCHEDULE\"", function () { function fvschedule(rate,shedList){ for( var i = 0; i < shedList.length; i++){ rate *= 1 + shedList[i] } return rate; } oParser = new parserFormula( "FVSCHEDULE(1,{0.09,0.11,0.1})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), fvschedule(1,[0.09,0.11,0.1]) ); //testArrayFormula2("FVSCHEDULE", 2, 2, true, true); } ); test( "Test: \"DISC\"", function () { function disc( settlement, maturity, pr, redemption, basis ){ if( settlement >= maturity || pr <= 0 || redemption <= 0 || basis < 0 || basis > 4 ) return "#NUM!" return ( 1.0 - pr / redemption ) / AscCommonExcel.yearFrac( settlement, maturity, basis ); } oParser = new parserFormula( "DISC(DATE(2007,1,25),DATE(2007,6,15),97.975,100,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), disc( new cDate(2007,0,25),new cDate(2007,5,15),97.975,100,1 ) ); testArrayFormula2("DISC",4,5,true); } ); test( "Test: \"DOLLARDE\"", function () { function dollarde( fractionalDollar, fraction ){ if( fraction < 0 ) return "#NUM!"; else if( fraction == 0 ) return "#DIV/0!"; var fInt = Math.floor( fractionalDollar ), res = fractionalDollar - fInt; res /= fraction; res *= Math.pow( 10, Math.ceil( Math.log( fraction ) / Math.log( 10 ) ) ); res += fInt; return res; } oParser = new parserFormula( "DOLLARDE(1.02,16)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), dollarde( 1.02,16 ) ); oParser = new parserFormula( "DOLLARDE(1.1,32)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), dollarde( 1.1,32 ) ); testArrayFormula2("DOLLARDE", 2, 2, true); } ); test( "Test: \"DOLLARFR\"", function () { function dollarde( fractionalDollar, fraction ){ if( fraction < 0 ) return "#NUM!"; else if( fraction == 0 ) return "#DIV/0!"; var fInt = Math.floor( fractionalDollar ), res = fractionalDollar - fInt; res *= fraction; res *= Math.pow( 10.0, -Math.ceil( Math.log( fraction ) / Math.log( 10 ) ) ); res += fInt; return res; } oParser = new parserFormula( "DOLLARFR(1.125,16)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), dollarde( 1.125,16 ) ); oParser = new parserFormula( "DOLLARFR(1.125,32)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), dollarde( 1.125,32 ) ); testArrayFormula2("DOLLARFR", 2, 2, true); } ); test( "Test: \"RECEIVED\"", function () { function received( settlement, maturity, investment, discount, basis ){ if( settlement >= maturity || investment <= 0 || discount <= 0 || basis < 0 || basis > 4 ) return "#NUM!" return investment / ( 1 - ( discount * AscCommonExcel.yearFrac( settlement, maturity, basis) ) ) } oParser = new parserFormula( "RECEIVED(DATE(2008,2,15),DATE(2008,5,15),1000000,0.0575,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), received( new cDate(2008,1,15),new cDate(2008,4,15),1000000,0.0575,2 ) ); testArrayFormula2("RECEIVED", 4, 5, true); } ); test( "Test: \"RATE\"", function () { function RateIteration( fNper, fPayment, fPv, fFv, fPayType, fGuess ) { function approxEqual( a, b ) { if ( a == b ) return true; var x = a - b; return (x < 0.0 ? -x : x) < ((a < 0.0 ? -a : a) * (1.0 / (16777216.0 * 16777216.0))); } var bValid = true, bFound = false, fX, fXnew, fTerm, fTermDerivation, fGeoSeries, fGeoSeriesDerivation; var nIterationsMax = 150, nCount = 0, fEpsilonSmall = 1.0E-14, SCdEpsilon = 1.0E-7; fFv = fFv - fPayment * fPayType; fPv = fPv + fPayment * fPayType; if ( fNper == Math.round( fNper ) ) { fX = fGuess.fGuess; var fPowN, fPowNminus1; while ( !bFound && nCount < nIterationsMax ) { fPowNminus1 = Math.pow( 1.0 + fX, fNper - 1.0 ); fPowN = fPowNminus1 * (1.0 + fX); if ( approxEqual( Math.abs( fX ), 0.0 ) ) { fGeoSeries = fNper; fGeoSeriesDerivation = fNper * (fNper - 1.0) / 2.0; } else { fGeoSeries = (fPowN - 1.0) / fX; fGeoSeriesDerivation = fNper * fPowNminus1 / fX - fGeoSeries / fX; } fTerm = fFv + fPv * fPowN + fPayment * fGeoSeries; fTermDerivation = fPv * fNper * fPowNminus1 + fPayment * fGeoSeriesDerivation; if ( Math.abs( fTerm ) < fEpsilonSmall ) bFound = true; else { if ( approxEqual( Math.abs( fTermDerivation ), 0.0 ) ) fXnew = fX + 1.1 * SCdEpsilon; else fXnew = fX - fTerm / fTermDerivation; nCount++; bFound = (Math.abs( fXnew - fX ) < SCdEpsilon); fX = fXnew; } } bValid =(fX >=-1.0); } else { fX = (fGuess.fGuest < -1.0) ? -1.0 : fGuess.fGuest; while ( bValid && !bFound && nCount < nIterationsMax ) { if ( approxEqual( Math.abs( fX ), 0.0 ) ) { fGeoSeries = fNper; fGeoSeriesDerivation = fNper * (fNper - 1.0) / 2.0; } else { fGeoSeries = (Math.pow( 1.0 + fX, fNper ) - 1.0) / fX; fGeoSeriesDerivation = fNper * Math.pow( 1.0 + fX, fNper - 1.0 ) / fX - fGeoSeries / fX; } fTerm = fFv + fPv * pow( 1.0 + fX, fNper ) + fPayment * fGeoSeries; fTermDerivation = fPv * fNper * Math.pow( 1.0 + fX, fNper - 1.0 ) + fPayment * fGeoSeriesDerivation; if ( Math.abs( fTerm ) < fEpsilonSmall ) bFound = true; else { if ( approxEqual( Math.abs( fTermDerivation ), 0.0 ) ) fXnew = fX + 1.1 * SCdEpsilon; else fXnew = fX - fTerm / fTermDerivation; nCount++; bFound = (Math.abs( fXnew - fX ) < SCdEpsilon); fX = fXnew; bValid = (fX >= -1.0); } } } fGuess.fGuess = fX; return bValid && bFound; } function rate(nper, pmt, pv, fv, type, quess){ if ( fv === undefined ) fv = 0; if ( type === undefined ) type = 0; if ( quess === undefined ) quess = 0.1; var res = {fGuess:0}; if( RateIteration(nper, pmt, pv, fv, type, res) ) return res.fGuess; return "#VALUE!" } oParser = new parserFormula( "RATE(4*12,-200,8000)", "A2", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), rate(4*12,-200,8000) ), true ); oParser = new parserFormula( "RATE(4*12,-200,8000)*12", "A2", ws ); ok( oParser.parse() ); strictEqual( difBetween( oParser.calculate().getValue(), rate(4*12,-200,8000)*12 ), true ); testArrayFormula2("RATE", 3, 6, true); } ); test( "Test: \"RRI\"", function () { oParser = new parserFormula( "RRI(96, 10000, 11000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0009933 ); oParser = new parserFormula( "RRI(0, 10000, 11000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "RRI(-10, 10000, 11000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "RRI(10, 10000, -11000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "RRI(1, 1, -1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -2 ); testArrayFormula2("RRI", 3, 3); } ); test( "Test: \"INTRATE\"", function () { function intrate( settlement, maturity, investment, redemption, basis ){ if( settlement >= maturity || investment <= 0 || redemption <= 0 || basis < 0 || basis > 4 ) return "#NUM!" return ( ( redemption / investment ) - 1 ) / AscCommonExcel.yearFrac( settlement, maturity, basis ) } oParser = new parserFormula( "INTRATE(DATE(2008,2,15),DATE(2008,5,15),1000000,1014420,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), intrate( new cDate(2008,1,15),new cDate(2008,4,15),1000000,1014420,2 ) ); testArrayFormula2("INTRATE", 4, 5, true); } ); test( "Test: \"TBILLEQ\"", function () { function tbilleq( settlement, maturity, discount ){ maturity = cDate.prototype.getDateFromExcel(maturity.getExcelDate() + 1); var d1 = settlement, d2 = maturity; var date1 = d1.getDate(), month1 = d1.getMonth(), year1 = d1.getFullYear(), date2 = d2.getDate(), month2 = d2.getMonth(), year2 = d2.getFullYear(); var nDiff = GetDiffDate360( date1, month1, year1, date2, month2, year2, true ); if( settlement >= maturity || discount <= 0 || nDiff > 360 ) return "#NUM!"; return ( 365 * discount ) / ( 360 - discount * nDiff ); } oParser = new parserFormula( "TBILLEQ(DATE(2008,3,31),DATE(2008,6,1),0.0914)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), tbilleq( new cDate(Date.UTC(2008,2,31)), new cDate(Date.UTC(2008,5,1)), 0.0914 ) ); testArrayFormula2("TBILLEQ", 3, 3, true); } ); test( "Test: \"TBILLPRICE\"", function () { function tbillprice( settlement, maturity, discount ){ maturity = cDate.prototype.getDateFromExcel(maturity.getExcelDate() + 1) var d1 = settlement var d2 = maturity var fFraction = AscCommonExcel.yearFrac(d1, d2, 0); if( fFraction - Math.floor( fFraction ) == 0 ) return "#NUM!"; return 100 * ( 1 - discount * fFraction ); } oParser = new parserFormula( "TBILLPRICE(DATE(2008,3,31),DATE(2008,6,1),0.09)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), tbillprice( new cDate(Date.UTC(2008,2,31)), new cDate(Date.UTC(2008,5,1)), 0.09 ) ); testArrayFormula2("TBILLPRICE", 3, 3, true); } ); test( "Test: \"TBILLYIELD\"", function () { function tbillyield( settlement, maturity, pr ){ var d1 = settlement; var d2 = maturity; var date1 = d1.getDate(), month1 = d1.getMonth(), year1 = d1.getFullYear(), date2 = d2.getDate(), month2 = d2.getMonth(), year2 = d2.getFullYear(); var nDiff = GetDiffDate360( date1, month1, year1, date2, month2, year2, true ); nDiff++; if( settlement >= maturity || pr <= 0 || nDiff > 360 ) return "#NUM!"; return ( ( 100 - pr ) / pr) * (360 / nDiff); } oParser = new parserFormula( "TBILLYIELD(DATE(2008,3,31),DATE(2008,6,1),98.45)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), tbillyield( new cDate(2008,2,31), new cDate(2008,5,1), 98.45 ) ); } ); test( "Test: \"COUPDAYBS\"", function () { function coupdaybs( settlement, maturity, frequency, basis ){ basis = ( basis !== undefined ? basis : 0 ); return _getcoupdaybs(settlement, maturity, frequency, basis) } oParser = new parserFormula( "COUPDAYBS(DATE(2007,1,25),DATE(2008,11,15),2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 71 ); oParser = new parserFormula( "COUPDAYBS(DATE(2007,1,25),DATE(2008,11,15),2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), coupdaybs( new cDate(2007,0,25), new cDate(2008,10,15), 2 ) ); testArrayFormula2("COUPDAYBS", 3, 4, true); } ); test( "Test: \"COUPDAYS\"", function () { function coupdays( settlement, maturity, frequency, basis ){ basis = ( basis !== undefined ? basis : 0 ); return _getcoupdays(settlement, maturity, frequency, basis) } oParser = new parserFormula( "COUPDAYS(DATE(2007,1,25),DATE(2008,11,15),2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), coupdays( new cDate(2007,0,25), new cDate(2008,10,15), 2, 1 ) ); oParser = new parserFormula( "COUPDAYS(DATE(2007,1,25),DATE(2008,11,15),2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), coupdays( new cDate(2007,0,25), new cDate(2008,10,15), 2 ) ); testArrayFormula2("COUPDAYS", 3, 4, true); } ); test( "Test: \"COUPDAYSNC\"", function () { function coupdaysnc( settlement, maturity, frequency, basis ) { basis = ( basis !== undefined ? basis : 0 ); if ( (basis != 0) && (basis != 4) ) { _lcl_GetCoupncd( settlement, maturity, frequency ); return _diffDate( settlement, maturity, basis ); } return _getcoupdays( new cDate( settlement ), new cDate( maturity ), frequency, basis ) - _getcoupdaybs( new cDate( settlement ), new cDate( maturity ), frequency, basis ); } oParser = new parserFormula( "COUPDAYSNC(DATE(2007,1,25),DATE(2008,11,15),2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 110 ); oParser = new parserFormula( "COUPDAYSNC(DATE(2007,1,25),DATE(2008,11,15),2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), coupdaysnc( new cDate(2007,0,25), new cDate(2008,10,15), 2 ) ); testArrayFormula2("COUPDAYSNC", 3, 4, true); } ); test( "Test: \"COUPNCD\"", function () { function coupncd( settlement, maturity, frequency, basis ) { basis = ( basis !== undefined ? basis : 0 ); _lcl_GetCoupncd( settlement, maturity, frequency ); return maturity.getExcelDate(); } oParser = new parserFormula( "COUPNCD(DATE(2007,1,25),DATE(2008,11,15),2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), coupncd( new cDate(Date.UTC(2007,0,25)), new cDate(Date.UTC(2008,10,15)), 2, 1 ) ); testArrayFormula2("COUPNCD", 3, 4, true); } ); test( "Test: \"COUPNUM\"", function () { oParser = new parserFormula( "COUPNUM(DATE(2007,1,25),DATE(2008,11,15),2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _coupnum( new cDate(2007,0,25), new cDate(2008,10,15), 2, 1 ) ); testArrayFormula2("COUPNUM", 3, 4, true); } ); test( "Test: \"COUPPCD\"", function () { function couppcd( settlement, maturity, frequency, basis ) { basis = ( basis !== undefined ? basis : 0 ); _lcl_GetCouppcd( settlement, maturity, frequency ); return maturity.getExcelDate(); } oParser = new parserFormula( "COUPPCD(DATE(2007,1,25),DATE(2008,11,15),2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), couppcd( new cDate(Date.UTC(2007,0,25)), new cDate(Date.UTC(2008,10,15)), 2, 1 ) ); testArrayFormula2("COUPPCD", 3, 4, true); } ); test( "Test: \"CONVERT\"", function () { oParser = new parserFormula( 'CONVERT(68, "F", "C")', "A2", ws ); ok( oParser.parse(), 'CONVERT(68, "F", "C")' ); strictEqual( oParser.calculate().getValue(), 20, 'CONVERT(68, "F", "C")' ); oParser = new parserFormula( 'CONVERT(2.5, "ft", "sec")', "A2", ws ); ok( oParser.parse(), 'CONVERT(2.5, "ft", "sec")' ); strictEqual( oParser.calculate().getValue(), "#N/A", 'CONVERT(2.5, "ft", "sec")' ); oParser = new parserFormula( 'CONVERT(CONVERT(100,"ft","m"),"ft","m")', "A2", ws ); ok( oParser.parse(), 'CONVERT(CONVERT(100,"ft","m"),"ft","m")' ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 9.290304, 'CONVERT(CONVERT(100,"ft","m"),"ft","m")' ); oParser = new parserFormula( 'CONVERT(7,"bit","byte")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(3) - 0, 0.875 ); oParser = new parserFormula( 'CONVERT(7,"admkn","kn")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14) - 0, 6.99999939524838 ); oParser = new parserFormula( 'CONVERT(7,"admkn","m/s")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 3.6011108 ); oParser = new parserFormula( 'CONVERT(7,"admkn","mph")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 8.0554554 ); oParser = new parserFormula( 'CONVERT(7,"m/h","m/sec")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0019444 ); oParser = new parserFormula( 'CONVERT(7,"m/hr","mph")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0043496 ); oParser = new parserFormula( 'CONVERT(7,"m","mi")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0043496 ); oParser = new parserFormula( 'CONVERT(7,"m","Pica")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 19842.5196850 ); oParser = new parserFormula( 'CONVERT(7,"m","pica")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 1653.5433071 ); oParser = new parserFormula( 'CONVERT(7,"Nmi","pica")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 3062362.2047251 ); oParser = new parserFormula( 'CONVERT(7,"yr","day")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 2556.75 ); oParser = new parserFormula( 'CONVERT(7,"yr","min")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3681720 ); oParser = new parserFormula( 'CONVERT(7,"day","min")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 10080 ); oParser = new parserFormula( 'CONVERT(7,"hr","sec")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 25200 ); oParser = new parserFormula( 'CONVERT(7,"min","sec")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 420 ); oParser = new parserFormula( 'CONVERT(7,"Pa","mmHg")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0525043 ); oParser = new parserFormula( 'CONVERT(7,"Pa","psi")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0010153 ); oParser = new parserFormula( 'CONVERT(7,"Pa","Torr")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0525045 ); oParser = new parserFormula( 'CONVERT(7,"g","sg")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0004797 ); oParser = new parserFormula( 'CONVERT(7,"g","lbm")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.0154324 ); oParser = new parserFormula( 'CONVERT(1, "lbm", "kg")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(7) - 0, 0.4535924 ); oParser = new parserFormula( 'CONVERT(1, "lbm", "mg")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(0) - 0, 453592 ); oParser = new parserFormula( 'CONVERT(1, "klbm", "mg")', "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A" ); testArrayFormula2("CONVERT", 3, 3, true); } ); test( "Test: \"PRICE\"", function () { oParser = new parserFormula( "PRICE(DATE(2008,2,15),DATE(2017,11,15),0.0575,0.065,100,2,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _getprice( new cDate( Date.UTC(2008, 1, 15 )), new cDate( Date.UTC(2017, 10, 15 )), 0.0575, 0.065, 100, 2, 0 ) ); testArrayFormula2("PRICE", 6, 7, true); } ); test( "Test: \"PRICEDISC\"", function () { function pricedisc(settl, matur, discount, redemption, basis){ return redemption * ( 1.0 - discount * _getdiffdate( settl, matur, basis ) ); } oParser = new parserFormula( "PRICEDISC(DATE(2008,2,16),DATE(2008,3,1),0.0525,100,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), pricedisc( new cDate(2008,1,16), new cDate(2008,2,1),0.0525,100,2 ) ); testArrayFormula2("PMT", 4, 5, true); } ); test( "Test: \"PRICEMAT\"", function () { function pricemat( settl, matur, iss, rate, yld, basis ) { var fIssMat = _yearFrac( new cDate(iss), new cDate(matur), basis ); var fIssSet = _yearFrac( new cDate(iss), new cDate(settl), basis ); var fSetMat = _yearFrac( new cDate(settl), new cDate(matur), basis ); var res = 1.0 + fIssMat * rate; res /= 1.0 + fSetMat * yld; res -= fIssSet * rate; res *= 100.0; return res; } oParser = new parserFormula( "PRICEMAT(DATE(2008,2,15),DATE(2008,4,13),DATE(2007,11,11),0.061,0.061,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), pricemat( new cDate(2008,1,15),new cDate(2008,3,13),new cDate(2007,10,11),0.061,0.061,0 ) ); testArrayFormula2("PRICEMAT", 5, 6, true); } ); test( "Test: \"YIELD\"", function () { oParser = new parserFormula( "YIELD(DATE(2008,2,15),DATE(2016,11,15),0.0575,95.04287,100,2,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _getYield( new cDate(Date.UTC(2008,1,15)), new cDate(Date.UTC(2016,10,15)),0.0575,95.04287,100,2,0 ) ); testArrayFormula2("YIELD", 6, 7, true); } ); test( "Test: \"YIELDDISC\"", function () { function yielddisc( settlement, maturity, pr, redemption, basis ){ var fRet = ( redemption / pr ) - 1.0; fRet /= _yearFrac( settlement, maturity, basis ); return fRet; } oParser = new parserFormula( "YIELDDISC(DATE(2008,2,16),DATE(2008,3,1),99.795,100,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), yielddisc( new cDate( 2008, 1, 16 ), new cDate( 2008, 2, 1 ), 99.795, 100, 2 ) ); testArrayFormula2("YIELDDISC", 4, 5, true); } ); test( "Test: \"YIELDMAT\"", function () { oParser = new parserFormula( "YIELDMAT(DATE(2008,3,15),DATE(2008,11,3),DATE(2007,11,8),0.0625,100.0123,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _getyieldmat( new cDate( 2008, 2, 15 ), new cDate( 2008, 10, 3 ), new cDate( 2007, 10, 8 ), 0.0625, 100.0123, 0 ) ); testArrayFormula2("YIELDMAT", 5, 6, true); } ); test( "Test: \"ODD\"", function () { oParser = new parserFormula( "ODD(1.5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "ODD(3)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "ODD(2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 3 ); oParser = new parserFormula( "ODD(-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -1 ); oParser = new parserFormula( "ODD(-2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -3 ); testArrayFormula("ODD"); } ); test( "Test: \"ODDLPRICE\"", function () { function oddlprice( settlement, maturity, last_interest, rate, yld, redemption, frequency, basis ){ var fDCi = _yearFrac( last_interest, maturity, basis ) * frequency; var fDSCi = _yearFrac( settlement, maturity, basis ) * frequency; var fAi = _yearFrac( last_interest, settlement, basis ) * frequency; var res = redemption + fDCi * 100.0 * rate / frequency; res /= fDSCi * yld / frequency + 1.0; res -= fAi * 100.0 * rate / frequency; return res; } oParser = new parserFormula( "ODDLPRICE(DATE(2008,11,11),DATE(2021,3,1),DATE(2008,10,15),0.0785,0.0625,100,2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), oddlprice( new cDate(Date.UTC(2008,10,11)), new cDate(Date.UTC(2021,2,1)), new cDate(Date.UTC(2008,9,15)), 0.0785, 0.0625, 100, 2, 1 ) ); testArrayFormula2("ODDLPRICE", 7, 8, true); } ); test( "Test: \"ODDLYIELD\"", function () { function oddlyield( settlement, maturity, last_interest, rate, pr, redemption, frequency, basis ){ var fDCi = _yearFrac( last_interest, maturity, basis ) * frequency; var fDSCi = _yearFrac( settlement, maturity, basis ) * frequency; var fAi = _yearFrac( last_interest, settlement, basis ) * frequency; var res = redemption + fDCi * 100.0 * rate / frequency; res /= pr + fAi * 100.0 * rate / frequency; res--; res *= frequency / fDSCi; return res; } oParser = new parserFormula( "ODDLYIELD(DATE(2008,11,11),DATE(2021,3,1),DATE(2008,10,15),0.0575,84.5,100,2,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), oddlyield( new cDate(2008,10,11), new cDate(2021,2,1), new cDate(2008,9,15), 0.0575, 84.5, 100, 2, 0 ) ); testArrayFormula2("ODDLYIELD", 7, 8, true); } ); test( "Test: \"DURATION\"", function () { oParser = new parserFormula( "DURATION(DATE(2008,1,1),DATE(2016,1,1),0.08,0.09,2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _duration( new cDate(Date.UTC(2008,0,1)), new cDate(Date.UTC(2016,0,1)), 0.08, 0.09, 2, 1 ) ); oParser = new parserFormula( "DURATION(DATE(2008,1,1),DATE(2016,1,1),-0.08,0.09,2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _duration( new cDate(Date.UTC(2008,0,1)), new cDate(Date.UTC(2016,0,1)), -0.08, 0.09, 2, 1 ) ); oParser = new parserFormula( "DURATION(DATE(2008,1,1),DATE(2016,1,1),-0.08,0.09,5,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), _duration( new cDate(Date.UTC(2008,0,1)), new cDate(Date.UTC(2016,0,1)), -0.08, 0.09, 5, 1 ) ); testArrayFormula2("DURATION", 5, 6, true); } ); test( "Test: \"MDURATION\"", function () { function mduration(settl, matur, coupon, yld, frequency, basis){ return _duration( settl, matur, coupon, yld, frequency, basis ) / (1 + yld/frequency); } oParser = new parserFormula( "MDURATION(DATE(2008,1,1),DATE(2016,1,1),0.08,0.09,2,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), mduration( new cDate(Date.UTC(2008,0,1)), new cDate(Date.UTC(2016,0,1)), 0.08, 0.09, 2, 1 ) ); testArrayFormula2("MDURATION", 5, 6, true); } ); test( "Test: \"MDETERM\"", function () { ws.getRange2( "A2" ).setValue( "1" ); ws.getRange2( "A3" ).setValue( "1" ); ws.getRange2( "A4" ).setValue( "1" ); ws.getRange2( "A5" ).setValue( "7" ); ws.getRange2( "B2" ).setValue( "3" ); ws.getRange2( "B3" ).setValue( "3" ); ws.getRange2( "B4" ).setValue( "1" ); ws.getRange2( "B5" ).setValue( "3" ); ws.getRange2( "C2" ).setValue( "8" ); ws.getRange2( "C3" ).setValue( "6" ); ws.getRange2( "C4" ).setValue( "1" ); ws.getRange2( "C5" ).setValue( "10" ); ws.getRange2( "D2" ).setValue( "5" ); ws.getRange2( "D3" ).setValue( "1" ); ws.getRange2( "D4" ).setValue( "0" ); ws.getRange2( "D5" ).setValue( "2" ); oParser = new parserFormula( "MDETERM(A2:D5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 88 ); oParser = new parserFormula( "MDETERM({3,6,1;1,1,0;3,10,2})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "MDETERM({3,6;1,1})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), -3 ); oParser = new parserFormula( "MDETERM({1,3,8,5;1,3,6,1})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); } ); test( "Test: \"SYD\"", function () { function syd( cost, salvage, life, per ){ if( life == -1 || life == 0 ) return "#NUM!"; var res = 2; res *= cost - salvage; res *= life+1-per; res /= (life+1)*life; return res < 0 ? "#NUM!" : res; } oParser = new parserFormula( "SYD(30000,7500,10,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), syd( 30000,7500,10,1 ) ); oParser = new parserFormula( "SYD(30000,7500,-1,10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), syd( 30000,7500,-1,10 ) ); oParser = new parserFormula( "SYD(30000,7500,-10,10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), syd( 30000,7500,-10,10 ) ); testArrayFormula2("SYD", 4, 4); } ); test( "Test: \"PPMT\"", function () { function ppmt( rate, per, nper, pv, fv, type ){ if( fv == undefined ) fv = 0; if( type == undefined ) type = 0; var fRmz = _getPMT(rate, nper, pv, fv, type); return fRmz - _getIPMT(rate, per, pv, type, fRmz); } oParser = new parserFormula( "PPMT(0.1/12,1,2*12,2000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ppmt( 0.1/12,1,2*12,2000 ) ); oParser = new parserFormula( "PPMT(0.08,10,10,200000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ppmt( 0.08,10,10,200000 ) ); testArrayFormula2("PPMT", 4, 6); } ); test( "Test: \"MIRR\"", function () { function mirr( valueArray, fRate1_invest, fRate1_reinvest ){ fRate1_invest = fRate1_invest + 1; fRate1_reinvest = fRate1_reinvest + 1; var fNPV_reinvest = 0, fPow_reinvest = 1, fNPV_invest = 0, fPow_invest = 1, fCellValue, wasNegative = false, wasPositive = false; for(var i = 0; i < valueArray.length; i++){ fCellValue = valueArray[i]; if( fCellValue > 0 ){ wasPositive = true; fNPV_reinvest += fCellValue * fPow_reinvest; } else if( fCellValue < 0 ){ wasNegative = true; fNPV_invest += fCellValue * fPow_invest; } fPow_reinvest /= fRate1_reinvest; fPow_invest /= fRate1_invest; } if( !( wasNegative && wasPositive ) ) return "#DIV/0!"; var fResult = -fNPV_reinvest / fNPV_invest; fResult *= Math.pow( fRate1_reinvest, valueArray.length - 1 ); fResult = Math.pow( fResult, 1 / (valueArray.length - 1) ); return fResult - 1; } oParser = new parserFormula( "MIRR({-120000,39000,30000,21000,37000,46000},0.1,0.12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), mirr( [-120000,39000,30000,21000,37000,46000],0.1,0.12 ) ); oParser = new parserFormula( "MIRR({-120000,39000,30000,21000},0.1,0.12)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), mirr( [-120000,39000,30000,21000],0.1,0.12 ) ); oParser = new parserFormula( "MIRR({-120000,39000,30000,21000,37000,46000},0.1,0.14)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), mirr( [-120000,39000,30000,21000,37000,46000],0.1,0.14 ) ); //testArrayFormula2("MIRR", 3, 3, null, true); } ); test( "Test: \"IPMT\"", function () { function ipmt( rate, per, nper, pv, fv, type ){ if( fv == undefined ) fv = 0; if( type == undefined ) type = 0; var res = AscCommonExcel.getPMT(rate, nper, pv, fv, type); res = AscCommonExcel.getIPMT(rate, per, pv, type, res); return res; } oParser = new parserFormula( "IPMT(0.1/12,1*3,3,8000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ipmt( 0.1/12,1*3,3,8000 ) ); oParser = new parserFormula( "IPMT(0.1,3,3,8000)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ipmt( 0.1,3,3,8000 ) ); testArrayFormula2("IPMT", 4, 6); } ); test( "Test: \"DB\"", function () { function db( cost, salvage, life, period, month ){ if ( salvage >= cost ) { return this.value = new AscCommonExcel.cNumber( 0 ); } if ( month < 1 || month > 12 || salvage < 0 || life <= 0 || period < 0 || life + 1 < period || cost < 0 ) { return "#NUM!"; } var nAbRate = 1 - Math.pow( salvage / cost, 1 / life ); nAbRate = Math.floor( (nAbRate * 1000) + 0.5 ) / 1000; var nErsteAbRate = cost * nAbRate * month / 12; var res = 0; if ( Math.floor( period ) == 1 ) res = nErsteAbRate; else { var nSummAbRate = nErsteAbRate, nMin = life; if ( nMin > period ) nMin = period; var iMax = Math.floor( nMin ); for ( var i = 2; i <= iMax; i++ ) { res = (cost - nSummAbRate) * nAbRate; nSummAbRate += res; } if ( period > life ) res = ((cost - nSummAbRate) * nAbRate * (12 - month)) / 12; } return res } oParser = new parserFormula( "DB(1000000,100000,6,1,7)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), db(1000000,100000,6,1,7) ); oParser = new parserFormula( "DB(1000000,100000,6,2,7)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), db(1000000,100000,6,2,7) ); oParser = new parserFormula( "DB(1000000,100000,6,3,7)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), db(1000000,100000,6,3,7) ); oParser = new parserFormula( "DB(1000000,100000,6,4,7)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), db(1000000,100000,6,4,7) ); oParser = new parserFormula( "DB(1000000,100000,6,5,7)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), db(1000000,100000,6,5,7) ); oParser = new parserFormula( "DB(1000000,100000,6,6,7)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), db(1000000,100000,6,6,7) ); oParser = new parserFormula( "DB(1000000,100000,6,7,7)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), db(1000000,100000,6,7,7) ); testArrayFormula2("DB",4,5); } ); test( "Test: \"DDB\"", function () { function ddb( cost, salvage, life, period, factor ){ if( factor === undefined || factor === null ) factor = 2; return _getDDB(cost, salvage, life, period, factor); } oParser = new parserFormula( "DDB(2400,300,10*365,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ddb(2400,300,10*365,1) ); oParser = new parserFormula( "DDB(2400,300,10*12,1,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ddb(2400,300,10*12,1,2) ); oParser = new parserFormula( "DDB(2400,300,10,1,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ddb(2400,300,10,1,2) ); oParser = new parserFormula( "DDB(2400,300,10,2,1.5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ddb(2400,300,10,2,1.5) ); oParser = new parserFormula( "DDB(2400,300,10,10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), ddb(2400,300,10,10) ); //TODO format $ ws.getRange2( "A102" ).setValue( "2400" ); ws.getRange2( "A103" ).setValue( "300" ); ws.getRange2( "A104" ).setValue( "10" ); oParser = new parserFormula( "DDB(A102,A103,A104*365,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 1.32 ); oParser = new parserFormula( "DDB(A102,A103,A104*12,1,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 40 ); oParser = new parserFormula( "DDB(A102,A103,A104,1,2)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 480 ); oParser = new parserFormula( "DDB(A102,A103,A104,2,1.5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(0) - 0, 306 ); oParser = new parserFormula( "DDB(A102,A103,A104,10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 22.12 ); oParser = new parserFormula( "DDB(A102,A103,0,10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("DDB",4,5); } ); test( "Test: \"SLN\"", function () { function sln( cost, salvage, life ){ if ( life == 0 ) return "#NUM!"; return ( cost - salvage ) / life; } oParser = new parserFormula( "SLN(30000,7500,10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), sln(30000,7500,10) ); testArrayFormula2("SLN", 3, 3); } ); test( "Test: \"XIRR\"", function () { function lcl_sca_XirrResult( rValues, rDates, fRate ) { var D_0 = rDates[0]; var r = fRate + 1; var fResult = rValues[0]; for ( var i = 1, nCount = rValues.length; i < nCount; ++i ) fResult += rValues[i] / Math.pow( r, (rDates[i] - D_0) / 365 ); return fResult; } function lcl_sca_XirrResult_Deriv1( rValues, rDates, fRate ) { var D_0 = rDates[0]; var r = fRate + 1; var fResult = 0; for ( var i = 1, nCount = rValues.length; i < nCount; ++i ) { var E_i = (rDates[i] - D_0) / 365; fResult -= E_i * rValues[i] / Math.pow( r, E_i + 1 ); } return fResult; } function xirr( valueArray, dateArray, rate ) { var res = rate if ( res <= -1 ) return "#NUM!" var fMaxEps = 1e-6, maxIter = 100; var newRate, eps, xirrRes, bContLoop; do { xirrRes = lcl_sca_XirrResult( valueArray, dateArray, res ); newRate = res - xirrRes / lcl_sca_XirrResult_Deriv1( valueArray, dateArray, res ); eps = Math.abs( newRate - res ); res = newRate; bContLoop = (eps > fMaxEps) && (Math.abs( xirrRes ) > fMaxEps); } while ( --maxIter && bContLoop ); if ( bContLoop ) return "#NUM!"; return res; } ws.getRange2( "F100" ).setValue( "1/1/2008" ); ws.getRange2( "G100" ).setValue( "3/1/2008" ); ws.getRange2( "H100" ).setValue( "10/30/2008" ); ws.getRange2( "I100" ).setValue( "2/15/2009" ); ws.getRange2( "J100" ).setValue( "4/1/2009" ); oParser = new parserFormula( "XIRR({-10000,2750,4250,3250,2750},F100:J100,0.1)", "A2", ws ); ok( oParser.parse() ); ok( difBetween( oParser.calculate().getValue(), 0.3733625335188316 ) ); ws.getRange2( "F100" ).setValue( 0 ); ok( oParser.parse() ); ok( difBetween( oParser.calculate().getValue(), 0.0024114950175866895 ) ); } ); test( "Test: \"VDB\"", function () { function _getVDB( cost, salvage, life, life1, startperiod, factor){ var fVdb=0, nLoopEnd = end = Math.ceil(startperiod), fTerm, fLia = 0, fRestwert = cost - salvage, bNowLia = false, fGda; for ( var i = 1; i <= nLoopEnd; i++){ if(!bNowLia){ fGda = _getDDB(cost, salvage, life, i, factor); fLia = fRestwert/ (life1 - (i-1)); if (fLia > fGda){ fTerm = fLia; bNowLia = true; } else{ fTerm = fGda; fRestwert -= fGda; } } else{ fTerm = fLia; } if ( i == nLoopEnd) fTerm *= ( startperiod + 1.0 - end ); fVdb += fTerm; } return fVdb; } function vdb( cost, salvage, life, startPeriod, endPeriod, factor, flag ) { if( factor === undefined || factor === null ) factor = 2; if( flag === undefined || flag === null ) flag = false; var start = Math.floor(startPeriod), end = Math.ceil(endPeriod), loopStart = start, loopEnd = end; var res = 0; if ( flag ) { for ( var i = loopStart + 1; i <= loopEnd; i++ ) { var ddb = _getDDB( cost, salvage, life, i, factor ); if ( i == loopStart + 1 ) ddb *= ( Math.min( endPeriod, start + 1 ) - startPeriod ); else if ( i == loopEnd ) ddb *= ( endPeriod + 1 - end ); res += ddb; } } else { var life1 = life; if ( !Math.approxEqual( startPeriod, Math.floor( startPeriod ) ) ) { if ( factor > 1 ) { if ( startPeriod > life / 2 || Math.approxEqual( startPeriod, life / 2 ) ) { var fPart = startPeriod - life / 2; startPeriod = life / 2; endPeriod -= fPart; life1 += 1; } } } cost -= _getVDB( cost, salvage, life, life1, startPeriod, factor ); res = _getVDB( cost, salvage, life, life - startPeriod, endPeriod - startPeriod, factor ); } return res; } oParser = new parserFormula( "VDB(2400,300,10*365,0,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), vdb(2400,300,10*365,0,1) ); oParser = new parserFormula( "VDB(2400,300,10*12,0,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), vdb(2400,300,10*12,0,1) ); oParser = new parserFormula( "VDB(2400,300,10*12,6,18)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), vdb(2400,300,10*12,6,18) ); oParser = new parserFormula( "VDB(0,0,0,0,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#DIV/0!" ); testArrayFormula2("VDB", 5, 7); } ); test( "Test: \"ODDFPRICE\"", function () { oParser = new parserFormula( "ODDFPRICE(DATE(1999,2,28),DATE(2016,1,1),DATE(1998,2,28),DATE(2015,1,1),7%,0,100,2,1)", "A2", ws ); ok( oParser.parse() ); ok( difBetween(oParser.calculate().getValue(), 217.878453038674) ); oParser = new parserFormula( "ODDFPRICE(DATE(2008,11,11),DATE(2021,3,1),DATE(2008,10,15),DATE(2009,3,1),0.0785,0.0625,100,2,1)", "A2", ws ); ok( oParser.parse() ); ok( difBetween(oParser.calculate().getValue(), 113.597717474079) ); oParser = new parserFormula( "ODDFPRICE(DATE(1990,6,1),DATE(1995,12,31),DATE(1990,1,1),DATE(1990,12,31),6%,5%,1000,1,1)", "A2", ws ); ok( oParser.parse() ); ok( difBetween(oParser.calculate().getValue(), 790.11323221867) ); testArrayFormula2("ODDFPRICE", 8, 9, true); } ); test( "Test: \"ODDFYIELD\"", function () { oParser = new parserFormula( "ODDFYIELD(DATE(1990,6,1),DATE(1995,12,31),DATE(1990,1,1),DATE(1990,12,31),6%,790,100,1,1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "ODDFYIELD(DATE(1990,6,1),DATE(1995,12,31),DATE(1990,1,1),DATE(1990,12,31),6%,790,100,1,1)" ); ok( difBetween(oParser.calculate().getValue(),-0.2889178784774840 ) ); oParser = new parserFormula( "ODDFYIELD(DATE(2008,11,11),DATE(2021,3,1),DATE(2008,10,15),DATE(2009,3,1),0.0575,84.5,100,2,0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "ODDFYIELD(DATE(2008,11,11),DATE(2021,3,1),DATE(2008,10,15),DATE(2009,3,1),0.0575,84.5,100,2,0)" ); ok( difBetween(oParser.calculate().getValue(), 0.0772455415972989 ) ); oParser = new parserFormula( "ODDFYIELD(DATE(2008,12,11),DATE(2021,4,1),DATE(2008,10,15),DATE(2009,4,1),6%,100,100,4,1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "ODDFYIELD(DATE(2008,12,11),DATE(2021,4,1),DATE(2008,10,15),DATE(2009,4,1),6%,100,100,4,1)" ); ok( difBetween(oParser.calculate().getValue(), 0.0599769985558904 ) ); testArrayFormula2("ODDFYIELD", 8, 9, true); } ); /* * Engineering * */ test( "Test: \"BIN2DEC\"", function () { oParser = new parserFormula( "BIN2DEC(101010)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2DEC(101010)" ); strictEqual( oParser.calculate().getValue(), 42 ); oParser = new parserFormula( "BIN2DEC(\"101010\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2DEC(\"101010\")" ); strictEqual( oParser.calculate().getValue(), 42 ); oParser = new parserFormula( "BIN2DEC(111111111)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2DEC(111111111)" ); strictEqual( oParser.calculate().getValue(), 511 ); oParser = new parserFormula( "BIN2DEC(1000000000)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2DEC(1000000000)" ); strictEqual( oParser.calculate().getValue(), -512 ); oParser = new parserFormula( "BIN2DEC(1111111111)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2DEC(1111111111)" ); strictEqual( oParser.calculate().getValue(), -1 ); oParser = new parserFormula( "BIN2DEC(1234567890)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2DEC(1234567890)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2DEC(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2DEC(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("BIN2DEC",1,1,true); }); test( "Test: \"BIN2HEX\"", function () { oParser = new parserFormula( "BIN2HEX(101010)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010)" ); strictEqual( oParser.calculate().getValue(), "2A" ); oParser = new parserFormula( "BIN2HEX(\"101010\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(\"101010\")" ); strictEqual( oParser.calculate().getValue(), "2A" ); oParser = new parserFormula( "BIN2HEX(111111111)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(111111111)" ); strictEqual( oParser.calculate().getValue(), "1FF" ); oParser = new parserFormula( "BIN2HEX(1000000000)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(1000000000)" ); strictEqual( oParser.calculate().getValue(), "FFFFFFFE00" ); oParser = new parserFormula( "BIN2HEX(1111111111)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(1111111111)" ); strictEqual( oParser.calculate().getValue(), "FFFFFFFFFF" ); oParser = new parserFormula( "BIN2HEX(101010,2)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010,2)" ); strictEqual( oParser.calculate().getValue(), "2A" ); oParser = new parserFormula( "BIN2HEX(101010,4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010,4)" ); strictEqual( oParser.calculate().getValue(), "002A" ); oParser = new parserFormula( "BIN2HEX(101010,4.5)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010,4.5)" ); strictEqual( oParser.calculate().getValue(), "002A" ); oParser = new parserFormula( "BIN2HEX(1234567890)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(1234567890)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2HEX(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2HEX(101010101010)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010101010)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2HEX(101010,1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010,1)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2HEX(101010,-4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010,-4)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2HEX(101010, \"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2HEX(101010,\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("BIN2HEX", 1, 2, true) }); test( "Test: \"BIN2OCT\"", function () { oParser = new parserFormula( "BIN2OCT(101010)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010)" ); strictEqual( oParser.calculate().getValue(), "52" ); oParser = new parserFormula( "BIN2OCT(\"101010\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(\"101010\")" ); strictEqual( oParser.calculate().getValue(), "52" ); oParser = new parserFormula( "BIN2OCT(111111111)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(111111111)" ); strictEqual( oParser.calculate().getValue(), "777" ); oParser = new parserFormula( "BIN2OCT(1000000000)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(1000000000)" ); strictEqual( oParser.calculate().getValue(), "7777777000" ); oParser = new parserFormula( "BIN2OCT(1111111111)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(1111111111)" ); strictEqual( oParser.calculate().getValue(), "7777777777" ); oParser = new parserFormula( "BIN2OCT(101010, 2)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010,2)" ); strictEqual( oParser.calculate().getValue(), "52" ); oParser = new parserFormula( "BIN2OCT(101010, 4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010,4)" ); strictEqual( oParser.calculate().getValue(), "0052" ); oParser = new parserFormula( "BIN2OCT(101010, 4.5)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010,4.5)" ); strictEqual( oParser.calculate().getValue(), "0052" ); oParser = new parserFormula( "BIN2OCT(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2OCT(1234567890)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(1234567890)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2OCT(101010101010)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010101010)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2OCT(101010, 1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010,1)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2OCT(101010, -4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010,-4)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "BIN2OCT(101010, \"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "BIN2OCT(101010,\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("BIN2OCT", 1, 2, true); }); test( "Test: \"DEC2BIN\"", function () { oParser = new parserFormula( "DEC2BIN(42)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(42)" ); strictEqual( oParser.calculate().getValue(), "101010" ); oParser = new parserFormula( "DEC2BIN(\"42\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(\"42\")" ); strictEqual( oParser.calculate().getValue(), "101010" ); oParser = new parserFormula( "DEC2BIN(-512)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(-512)" ); strictEqual( oParser.calculate().getValue(), "1000000000" ); oParser = new parserFormula( "DEC2BIN(-511)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(-511)" ); strictEqual( oParser.calculate().getValue(), "1000000001" ); oParser = new parserFormula( "DEC2BIN(-1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(-1)" ); strictEqual( oParser.calculate().getValue(), "1111111111" ); oParser = new parserFormula( "DEC2BIN(0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(0)" ); strictEqual( oParser.calculate().getValue(), "0" ); oParser = new parserFormula( "DEC2BIN(1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(1)" ); strictEqual( oParser.calculate().getValue(), "1" ); oParser = new parserFormula( "DEC2BIN(510)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(510)" ); strictEqual( oParser.calculate().getValue(), "111111110" ); oParser = new parserFormula( "DEC2BIN(511)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(511)" ); strictEqual( oParser.calculate().getValue(), "111111111" ); oParser = new parserFormula( "DEC2BIN(42, 6)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(42,6)" ); strictEqual( oParser.calculate().getValue(), "101010" ); oParser = new parserFormula( "DEC2BIN(42, 8)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(42,8)" ); strictEqual( oParser.calculate().getValue(), "00101010" ); oParser = new parserFormula( "DEC2BIN(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "DEC2BIN(\"2a\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(\"2a\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "DEC2BIN(-513)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(-513)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "DEC2BIN(512)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(512)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "DEC2BIN(42, -8)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2BIN(42,-8)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("DEC2BIN", 1, 2, true) }); test( "Test: \"DEC2HEX\"", function () { oParser = new parserFormula( "DEC2HEX(42)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(42)" ); strictEqual( oParser.calculate().getValue(), "2A" ); oParser = new parserFormula( "DEC2HEX(\"42\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(\"42\")" ); strictEqual( oParser.calculate().getValue(), "2A" ); oParser = new parserFormula( "DEC2HEX(-549755813888)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(-549755813888)" ); strictEqual( oParser.calculate().getValue(), "8000000000" ); oParser = new parserFormula( "DEC2HEX(-549755813887)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(-549755813887)" ); strictEqual( oParser.calculate().getValue(), "8000000001" ); oParser = new parserFormula( "DEC2HEX(-1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(-1)" ); strictEqual( oParser.calculate().getValue(), "FFFFFFFFFF" ); oParser = new parserFormula( "DEC2HEX(0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(0)" ); strictEqual( oParser.calculate().getValue(), "0" ); oParser = new parserFormula( "DEC2HEX(1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(1)" ); strictEqual( oParser.calculate().getValue(), "1" ); oParser = new parserFormula( "DEC2HEX(549755813886)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(549755813886)" ); strictEqual( oParser.calculate().getValue(), "7FFFFFFFFE" ); oParser = new parserFormula( "DEC2HEX(549755813887)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(549755813887)" ); strictEqual( oParser.calculate().getValue(), "7FFFFFFFFF" ); oParser = new parserFormula( "DEC2HEX(42, 2)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(42,2)" ); strictEqual( oParser.calculate().getValue(), "2A" ); oParser = new parserFormula( "DEC2HEX(42, 4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(42,4)" ); strictEqual( oParser.calculate().getValue(), "002A" ); oParser = new parserFormula( "DEC2HEX(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "DEC2HEX(\"2a\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2HEX(\"2a\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("DEC2HEX", 1, 2, true); }); test( "Test: \"DEC2OCT\"", function () { oParser = new parserFormula( "DEC2OCT(42)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(42)" ); strictEqual( oParser.calculate().getValue(), "52" ); oParser = new parserFormula( "DEC2OCT(\"42\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(\"42\")" ); strictEqual( oParser.calculate().getValue(), "52" ); oParser = new parserFormula( "DEC2OCT(-536870912)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(-536870912)" ); strictEqual( oParser.calculate().getValue(), "4000000000" ); oParser = new parserFormula( "DEC2OCT(-536870911)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(-536870911)" ); strictEqual( oParser.calculate().getValue(), "4000000001" ); oParser = new parserFormula( "DEC2OCT(-1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(-1)" ); strictEqual( oParser.calculate().getValue(), "7777777777" ); oParser = new parserFormula( "DEC2OCT(0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(0)" ); strictEqual( oParser.calculate().getValue(), "0" ); oParser = new parserFormula( "DEC2OCT(-0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(-0)" ); strictEqual( oParser.calculate().getValue(), "0" ); oParser = new parserFormula( "DEC2OCT(1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(1)" ); strictEqual( oParser.calculate().getValue(), "1" ); oParser = new parserFormula( "DEC2OCT(536870910)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(536870910)" ); strictEqual( oParser.calculate().getValue(), "3777777776" ); oParser = new parserFormula( "DEC2OCT(536870911)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(536870911)" ); strictEqual( oParser.calculate().getValue(), "3777777777" ); oParser = new parserFormula( "DEC2OCT(42, 2)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(42,2)" ); strictEqual( oParser.calculate().getValue(), "52" ); oParser = new parserFormula( "DEC2OCT(42, 4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(42,4)" ); strictEqual( oParser.calculate().getValue(), "0052" ); oParser = new parserFormula( "DEC2OCT(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "DEC2OCT(\"2a\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(\"2a\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); oParser = new parserFormula( "DEC2OCT(-536870913)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(-536870913)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "DEC2OCT(536870912)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(536870912)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "DEC2OCT(42, 1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "DEC2OCT(42,1)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); testArrayFormula2("DEC2OCT", 1, 2, true); }); test( "Test: \"HEX2BIN\"", function () { oParser = new parserFormula( "HEX2BIN(\"2a\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"2a\")" ); strictEqual( oParser.calculate().getValue(), "101010" ); oParser = new parserFormula( "HEX2BIN(\"fffffffe00\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"fffffffe00\")" ); strictEqual( oParser.calculate().getValue(), "1000000000" ); oParser = new parserFormula( "HEX2BIN(\"fffffffe01\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"fffffffe01\")" ); strictEqual( oParser.calculate().getValue(), "1000000001" ); oParser = new parserFormula( "HEX2BIN(\"ffffffffff\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"ffffffffff\")" ); strictEqual( oParser.calculate().getValue(), "1111111111" ); oParser = new parserFormula( "HEX2BIN(0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(0)" ); strictEqual( oParser.calculate().getValue(), "0" ); oParser = new parserFormula( "HEX2BIN(1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(1)" ); strictEqual( oParser.calculate().getValue(), "1" ); oParser = new parserFormula( "HEX2BIN(\"1fe\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"1fe\")" ); strictEqual( oParser.calculate().getValue(), "111111110" ); oParser = new parserFormula( "HEX2BIN(\"1ff\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"1ff\")" ); strictEqual( oParser.calculate().getValue(), "111111111" ); oParser = new parserFormula( "HEX2BIN(\"2a\",6)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"2a\",6)" ); strictEqual( oParser.calculate().getValue(), "101010" ); oParser = new parserFormula( "HEX2BIN(\"2a\",8)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"2a\",8)" ); strictEqual( oParser.calculate().getValue(), "00101010" ); oParser = new parserFormula( "HEX2BIN(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "HEX2BIN(\"fffffffdff\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"fffffffdff\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "HEX2BIN(\"200\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"200\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "HEX2BIN(\"2a\", 5)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"2a\",5)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "HEX2BIN(\"2a\", -8)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"2a\",-8)" ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); oParser = new parserFormula( "HEX2BIN(\"2a\", \"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2BIN(\"2a\",\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); testArrayFormula2("HEX2BIN", 1, 2, true); }); test( "Test: \"HEX2DEC\"", function () { oParser = new parserFormula( "HEX2DEC(\"2a\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(\"2a\")" ); strictEqual( oParser.calculate().getValue(), 42); oParser = new parserFormula( "HEX2DEC(\"8000000000\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(\"8000000000\")" ); strictEqual( oParser.calculate().getValue(), -549755813888); oParser = new parserFormula( "HEX2DEC(\"ffffffffff\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(\"ffffffffff\")" ); strictEqual( oParser.calculate().getValue(), -1); oParser = new parserFormula( "HEX2DEC(\"0\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(\"0\")" ); strictEqual( oParser.calculate().getValue(), 0); oParser = new parserFormula( "HEX2DEC(\"1\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(\"1\")" ); strictEqual( oParser.calculate().getValue(), 1); oParser = new parserFormula( "HEX2DEC(0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(0)" ); strictEqual( oParser.calculate().getValue(), 0); oParser = new parserFormula( "HEX2DEC(1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(1)" ); strictEqual( oParser.calculate().getValue(), 1); oParser = new parserFormula( "HEX2DEC(\"7fffffffff\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2DEC(\"7fffffffff\")" ); strictEqual( oParser.calculate().getValue(), 549755813887); testArrayFormula2("HEX2DEC", 1, 1, true); }); test( "Test: \"HEX2OCT\"", function () { oParser = new parserFormula( "HEX2OCT(\"2a\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"2a\")" ); strictEqual( oParser.calculate().getValue(), "52"); oParser = new parserFormula( "HEX2OCT(\"ffe0000000\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"ffe0000000\")" ); strictEqual( oParser.calculate().getValue(), "4000000000"); oParser = new parserFormula( "HEX2OCT(\"ffe0000001\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"ffe0000001\")" ); strictEqual( oParser.calculate().getValue(), "4000000001"); oParser = new parserFormula( "HEX2OCT(0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(0)" ); strictEqual( oParser.calculate().getValue(), "0"); oParser = new parserFormula( "HEX2OCT(1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(1)" ); strictEqual( oParser.calculate().getValue(), "1"); oParser = new parserFormula( "HEX2OCT(\"1ffffffe\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"1ffffffe\")" ); strictEqual( oParser.calculate().getValue(), "3777777776"); oParser = new parserFormula( "HEX2OCT(\"1fffffff\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"1fffffff\")" ); strictEqual( oParser.calculate().getValue(), "3777777777"); oParser = new parserFormula( "HEX2OCT(\"2a\",2)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"2a\",2)" ); strictEqual( oParser.calculate().getValue(), "52"); oParser = new parserFormula( "HEX2OCT(\"2a\",4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"2a\",4)" ); strictEqual( oParser.calculate().getValue(), "0052"); oParser = new parserFormula( "HEX2OCT(\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "HEX2OCT(\"ffdfffffff\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"ffdfffffff\")" ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "HEX2OCT(\"2a\", 1)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "HEX2OCT(\"2a\",1)" ); strictEqual( oParser.calculate().getValue(), "#NUM!"); testArrayFormula2("HEX2OCT", 1, 2, true); }); test( "Test: \"OCT2BIN\"", function () { oParser = new parserFormula( "OCT2BIN(\"52\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"52\")" ); strictEqual( oParser.calculate().getValue(), "101010"); oParser = new parserFormula( "OCT2BIN(\"7777777000\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"7777777000\")" ); strictEqual( oParser.calculate().getValue(), "1000000000"); oParser = new parserFormula( "OCT2BIN(\"7777777001\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"7777777001\")" ); strictEqual( oParser.calculate().getValue(), "1000000001"); oParser = new parserFormula( "OCT2BIN(\"7777777777\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"7777777777\")" ); strictEqual( oParser.calculate().getValue(), "1111111111"); oParser = new parserFormula( "OCT2BIN(\"0\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"0\")" ); strictEqual( oParser.calculate().getValue(), "0"); oParser = new parserFormula( "OCT2BIN(\"1\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"1\")" ); strictEqual( oParser.calculate().getValue(), "1"); oParser = new parserFormula( "OCT2BIN(\"776\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"776\")" ); strictEqual( oParser.calculate().getValue(), "111111110"); oParser = new parserFormula( "OCT2BIN(\"777\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"777\")" ); strictEqual( oParser.calculate().getValue(), "111111111"); oParser = new parserFormula( "OCT2BIN(\"52\", 6)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"52\",6)" ); strictEqual( oParser.calculate().getValue(), "101010"); oParser = new parserFormula( "OCT2BIN(\"52\", 8)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"52\",8)" ); strictEqual( oParser.calculate().getValue(), "00101010"); oParser = new parserFormula( "OCT2BIN(\"Hello World!\", 8)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"Hello World!\",8)" ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "OCT2BIN(\"52\",\"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2BIN(\"52\",\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!"); testArrayFormula2("OCT2BIN", 1, 2, true) }); test( "Test: \"OCT2DEC\"", function () { oParser = new parserFormula( "OCT2DEC(\"52\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"52\")" ); strictEqual( oParser.calculate().getValue(), 42); oParser = new parserFormula( "OCT2DEC(\"4000000000\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"4000000000\")" ); strictEqual( oParser.calculate().getValue(), -536870912); oParser = new parserFormula( "OCT2DEC(\"7777777777\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"7777777777\")" ); strictEqual( oParser.calculate().getValue(), -1); oParser = new parserFormula( "OCT2DEC(\"0\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"0\")" ); strictEqual( oParser.calculate().getValue(), 0); oParser = new parserFormula( "OCT2DEC(\"1\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"1\")" ); strictEqual( oParser.calculate().getValue(), 1); oParser = new parserFormula( "OCT2DEC(\"3777777776\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"3777777776\")" ); strictEqual( oParser.calculate().getValue(), 536870910); oParser = new parserFormula( "OCT2DEC(\"3777777777\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"3777777777\")" ); strictEqual( oParser.calculate().getValue(), 536870911); oParser = new parserFormula( "OCT2DEC(\"3777777777\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2DEC(\"3777777777\")" ); strictEqual( oParser.calculate().getValue(), 536870911); testArrayFormula2("OCT2DEC",1,1,true); }); test( "Test: \"OCT2HEX\"", function () { oParser = new parserFormula( "OCT2HEX(\"52\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"52\")" ); strictEqual( oParser.calculate().getValue(), "2A"); oParser = new parserFormula( "OCT2HEX(\"4000000000\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"4000000000\")" ); strictEqual( oParser.calculate().getValue(), "FFE0000000"); oParser = new parserFormula( "OCT2HEX(\"4000000001\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"4000000001\")" ); strictEqual( oParser.calculate().getValue(), "FFE0000001"); oParser = new parserFormula( "OCT2HEX(\"7777777777\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"7777777777\")" ); strictEqual( oParser.calculate().getValue(), "FFFFFFFFFF"); oParser = new parserFormula( "OCT2HEX(\"0\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"0\")" ); strictEqual( oParser.calculate().getValue(), "0"); oParser = new parserFormula( "OCT2HEX(\"1\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"1\")" ); strictEqual( oParser.calculate().getValue(), "1"); oParser = new parserFormula( "OCT2HEX(\"3777777776\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"3777777776\")" ); strictEqual( oParser.calculate().getValue(), "1FFFFFFE"); oParser = new parserFormula( "OCT2HEX(\"3777777777\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"3777777777\")" ); strictEqual( oParser.calculate().getValue(), "1FFFFFFF"); oParser = new parserFormula( "OCT2HEX(\"52\", 2)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"52\",2)" ); strictEqual( oParser.calculate().getValue(), "2A"); oParser = new parserFormula( "OCT2HEX(\"52\", 4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"52\",4)" ); strictEqual( oParser.calculate().getValue(), "002A"); oParser = new parserFormula( "OCT2HEX(\"Hello World!\", 4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"Hello World!\",4)" ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "OCT2HEX(\"52\", -4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"52\",-4)" ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "OCT2HEX(\"52\", \"Hello World!\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "OCT2HEX(\"52\",\"Hello World!\")" ); strictEqual( oParser.calculate().getValue(), "#VALUE!"); testArrayFormula2("OCT2HEX", 1, 2, true) }); test( "Test: \"COMPLEX\"", function () { oParser = new parserFormula( "COMPLEX(-3.5,19.6)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "COMPLEX(-3.5,19.6)" ); strictEqual( oParser.calculate().getValue(), "-3.5+19.6i"); oParser = new parserFormula( "COMPLEX(3.5,-19.6,\"j\")", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "COMPLEX(3.5,-19.6,\"j\")" ); strictEqual( oParser.calculate().getValue(), "3.5-19.6j"); oParser = new parserFormula( "COMPLEX(3.5,0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "COMPLEX(3.5,0)" ); strictEqual( oParser.calculate().getValue(), "3.5"); oParser = new parserFormula( "COMPLEX(0,2.4)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "COMPLEX(0,2.4)" ); strictEqual( oParser.calculate().getValue(), "2.4i"); oParser = new parserFormula( "COMPLEX(0,0)", "A2", ws ); ok( oParser.parse() ); ok( oParser.assemble() == "COMPLEX(0,0)" ); strictEqual( oParser.calculate().getValue(), "0"); testArrayFormula2("COMPLEX", 2, 3, true); }); test( "Test: \"DELTA\"", function () { oParser = new parserFormula( "DELTA(10.5,10.5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1); oParser = new parserFormula( "DELTA(10.5,10.6)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0); oParser = new parserFormula( "DELTA(10.5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0); oParser = new parserFormula( "DELTA(0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1); testArrayFormula2("DELTA", 1, 2, true); }); test( "Test: \"ERF\"", function () { oParser = new parserFormula( "ERF(1.234,4.5432)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.08096058291050978.toFixed(14)-0 ); oParser = new parserFormula( "ERF(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.8427007929497149.toFixed(14)-0 ); oParser = new parserFormula( "ERF(0,1.345)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.9428441710878559.toFixed(14)-0 ); oParser = new parserFormula( "ERF(1.234)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.9190394169576684.toFixed(14)-0 ); testArrayFormula2("ERF", 1, 2, true); }); test( "Test: \"GESTEP\"", function () { oParser = new parserFormula( "GESTEP(5, 4)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1); oParser = new parserFormula( "GESTEP(5, 5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1); oParser = new parserFormula( "GESTEP(-4, -5)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1); oParser = new parserFormula( "GESTEP(-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0); testArrayFormula2("GESTEP", 1, 2, true); }); test( "Test: \"ERF.PRECISE\"", function () { oParser = new parserFormula( "ERF.PRECISE(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.8427007929497149.toFixed(14)-0 ); oParser = new parserFormula( "ERF.PRECISE(1.234)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.9190394169576684.toFixed(14)-0 ); oParser = new parserFormula( "ERF.PRECISE(0.745)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.70792892 ); oParser = new parserFormula( "ERF.PRECISE(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 0.84270079 ); testArrayFormula2("ERF.PRECISE",1,1,true); }); test( "Test: \"ERFC\"", function () { oParser = new parserFormula( "ERFC(1.234)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.08096058304233157.toFixed(14)-0 ); oParser = new parserFormula( "ERFC(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.15729920705028513.toFixed(14)-0 ); oParser = new parserFormula( "ERFC(0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "ERFC(-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 1.8427007929497148.toFixed(14)-0 ); testArrayFormula2("ERFC",1,1,true); }); test( "Test: \"ERFC.PRECISE\"", function () { oParser = new parserFormula( "ERFC.PRECISE(1.234)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.08096058304233157.toFixed(14)-0 ); oParser = new parserFormula( "ERFC.PRECISE(1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 0.15729920705028513.toFixed(14)-0 ); oParser = new parserFormula( "ERFC.PRECISE(0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( "ERFC.PRECISE(-1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(14)-0, 1.8427007929497148.toFixed(14)-0 ); }); test( "Test: \"BITAND\"", function () { oParser = new parserFormula( 'BITAND(1,5)', "AA2", ws ); ok( oParser.parse(), 'BITAND(1,5)' ); strictEqual( oParser.calculate().getValue(), 1, 'BITAND(1,5)' ); oParser = new parserFormula( 'BITAND(13,25)', "AA2", ws ); ok( oParser.parse(), 'BITAND(13,25)' ); strictEqual( oParser.calculate().getValue(), 9, 'BITAND(13,25)' ); testArrayFormula2("BITAND", 2, 2); }); test( "Test: \"BITOR\"", function () { oParser = new parserFormula( 'BITOR(23,10)', "AA2", ws ); ok( oParser.parse()); strictEqual( oParser.calculate().getValue(), 31 ); testArrayFormula2("BITOR", 2, 2); }); test( "Test: \"BITXOR\"", function () { oParser = new parserFormula( 'BITXOR(5,3)', "AA2", ws ); ok( oParser.parse()); strictEqual( oParser.calculate().getValue(), 6 ); testArrayFormula2("BITXOR", 2, 2); }); test( "Test: \"BITRSHIFT\"", function () { oParser = new parserFormula( 'BITRSHIFT(13,2)', "AA2", ws ); ok( oParser.parse()); strictEqual( oParser.calculate().getValue(), 3 ); testArrayFormula2("BITRSHIFT", 2, 2); }); test( "Test: \"BITLSHIFT\"", function () { oParser = new parserFormula( 'BITLSHIFT(4,2)', "AA2", ws ); ok( oParser.parse()); strictEqual( oParser.calculate().getValue(), 16 ); testArrayFormula2("BITLSHIFT", 2, 2); }); function putDataForDatabase(){ ws.getRange2( "A1" ).setValue( "Tree" ); ws.getRange2( "A2" ).setValue( "Apple" ); ws.getRange2( "A3" ).setValue( "Pear" ); ws.getRange2( "A4" ).setValue( "Tree" ); ws.getRange2( "A5" ).setValue( "Apple" ); ws.getRange2( "A6" ).setValue( "Pear" ); ws.getRange2( "A7" ).setValue( "Cherry" ); ws.getRange2( "A8" ).setValue( "Apple" ); ws.getRange2( "A9" ).setValue( "Pear" ); ws.getRange2( "A10" ).setValue( "Apple" ); ws.getRange2( "B1" ).setValue( "Height" ); ws.getRange2( "B2" ).setValue( ">10" ); ws.getRange2( "B3" ).setValue( "" ); ws.getRange2( "B4" ).setValue( "Height" ); ws.getRange2( "B5" ).setValue( "18" ); ws.getRange2( "B6" ).setValue( "12" ); ws.getRange2( "B7" ).setValue( "13" ); ws.getRange2( "B8" ).setValue( "14" ); ws.getRange2( "B9" ).setValue( "9" ); ws.getRange2( "B10" ).setValue( "8" ); ws.getRange2( "C1" ).setValue( "Age" ); ws.getRange2( "C2" ).setValue( "" ); ws.getRange2( "C3" ).setValue( "" ); ws.getRange2( "C4" ).setValue( "Age" ); ws.getRange2( "C5" ).setValue( "20" ); ws.getRange2( "C6" ).setValue( "12" ); ws.getRange2( "C7" ).setValue( "14" ); ws.getRange2( "C8" ).setValue( "15" ); ws.getRange2( "C9" ).setValue( "8" ); ws.getRange2( "C10" ).setValue( "9" ); ws.getRange2( "C1" ).setValue( "Age" ); ws.getRange2( "C2" ).setValue( "" ); ws.getRange2( "C3" ).setValue( "" ); ws.getRange2( "C4" ).setValue( "Age" ); ws.getRange2( "C5" ).setValue( "20" ); ws.getRange2( "C6" ).setValue( "12" ); ws.getRange2( "C7" ).setValue( "14" ); ws.getRange2( "C8" ).setValue( "15" ); ws.getRange2( "C9" ).setValue( "8" ); ws.getRange2( "C10" ).setValue( "9" ); ws.getRange2( "D1" ).setValue( "Yield" ); ws.getRange2( "D2" ).setValue( "" ); ws.getRange2( "D3" ).setValue( "" ); ws.getRange2( "D4" ).setValue( "Yield" ); ws.getRange2( "D5" ).setValue( "14" ); ws.getRange2( "D6" ).setValue( "10" ); ws.getRange2( "D7" ).setValue( "9" ); ws.getRange2( "D8" ).setValue( "10" ); ws.getRange2( "D9" ).setValue( "8" ); ws.getRange2( "D10" ).setValue( "6" ); ws.getRange2( "E1" ).setValue( "Profit" ); ws.getRange2( "E2" ).setValue( "" ); ws.getRange2( "E3" ).setValue( "" ); ws.getRange2( "E4" ).setValue( "Profit" ); ws.getRange2( "E5" ).setValue( "105" ); ws.getRange2( "E6" ).setValue( "96" ); ws.getRange2( "E7" ).setValue( "105" ); ws.getRange2( "E8" ).setValue( "75" ); ws.getRange2( "E9" ).setValue( "76.8" ); ws.getRange2( "E10" ).setValue( "45" ); ws.getRange2( "F1" ).setValue( "Height" ); ws.getRange2( "F2" ).setValue( "<16" ); ws.getRange2( "F3" ).setValue( "" ); } //database formulas test( "Test: \"DAVERAGE\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DAVERAGE(A4:E10, "Yield", A1:B2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 12 ); oParser = new parserFormula( 'DAVERAGE(A4:E10, 3, A4:E10)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 13 ); }); test( "Test: \"DCOUNT\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DCOUNT(A4:E10, "Age", A1:F2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( 'DCOUNT(A4:E10,, A1:F2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( 'DCOUNT(A4:E10,"", A1:F2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); }); test( "Test: \"DCOUNTA\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DCOUNTA(A4:E10, "Profit", A1:F2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( 'DCOUNTA(A4:E10,, A1:F2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 1 ); oParser = new parserFormula( 'DCOUNTA(A4:E10,"", A1:F2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); }); test( "Test: \"DGET\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DGET(A4:E10, "Yield", A1:A3)', "AA2", ws ); ok( oParser.parse(), 'DGET(A4:E10, "Yield", A1:A3)' ); strictEqual( oParser.calculate().getValue(), "#NUM!", 'DGET(A4:E10, "Yield", A1:A3)' ); oParser = new parserFormula( 'DGET(A4:E10, "Yield", A1:F2)', "AA2", ws ); ok( oParser.parse(), 'DGET(A4:E10, "Yield", A1:F2)' ); strictEqual( oParser.calculate().getValue(), 10, 'DGET(A4:E10, "Yield", A1:F2)' ); }); test( "Test: \"DMAX\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DMAX(A4:E10, "Profit", A1:F3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 96 ); }); test( "Test: \"DMIN\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DMIN(A4:E10, "Profit", A1:F3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 75 ); }); test( "Test: \"DPRODUCT\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DPRODUCT(A4:E10, "Yield", A1:F3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 800 ); }); test( "Test: \"DSTDEV\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DSTDEV(A4:E10, "Yield", A1:F3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(4) - 0, 1.1547); }); test( "Test: \"DSTDEVP\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DSTDEVP(A4:E10, "Yield", A1:F3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(6) - 0, 0.942809); }); test( "Test: \"STDEVPA\"", function () { ws.getRange2( "A103" ).setValue( "1345" ); ws.getRange2( "A104" ).setValue( "1301" ); ws.getRange2( "A105" ).setValue( "1368" ); ws.getRange2( "A106" ).setValue( "1322" ); ws.getRange2( "A107" ).setValue( "1310" ); ws.getRange2( "A108" ).setValue( "1370" ); ws.getRange2( "A109" ).setValue( "1318" ); ws.getRange2( "A110" ).setValue( "1350" ); ws.getRange2( "A111" ).setValue( "1303" ); ws.getRange2( "A112" ).setValue( "1299" ); oParser = new parserFormula( 'STDEVPA(A103:A112)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 26.05456); testArrayFormula2("STDEVPA", 1, 8, null, true); }); test( "Test: \"STDEVP\"", function () { ws.getRange2( "A103" ).setValue( "1345" ); ws.getRange2( "A104" ).setValue( "1301" ); ws.getRange2( "A105" ).setValue( "1368" ); ws.getRange2( "A106" ).setValue( "1322" ); ws.getRange2( "A107" ).setValue( "1310" ); ws.getRange2( "A108" ).setValue( "1370" ); ws.getRange2( "A109" ).setValue( "1318" ); ws.getRange2( "A110" ).setValue( "1350" ); ws.getRange2( "A111" ).setValue( "1303" ); ws.getRange2( "A112" ).setValue( "1299" ); oParser = new parserFormula( 'STDEVP(A103:A112)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 26.05456); testArrayFormula2("STDEVP", 1, 8, null, true); }); test( "Test: \"STDEV\"", function () { ws.getRange2( "A103" ).setValue( "1345" ); ws.getRange2( "A104" ).setValue( "1301" ); ws.getRange2( "A105" ).setValue( "1368" ); ws.getRange2( "A106" ).setValue( "1322" ); ws.getRange2( "A107" ).setValue( "1310" ); ws.getRange2( "A108" ).setValue( "1370" ); ws.getRange2( "A109" ).setValue( "1318" ); ws.getRange2( "A110" ).setValue( "1350" ); ws.getRange2( "A111" ).setValue( "1303" ); ws.getRange2( "A112" ).setValue( "1299" ); oParser = new parserFormula( 'STDEV(A103:A112)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(5) - 0, 27.46392); testArrayFormula2("STDEV", 1, 8, null, true); }); test( "Test: \"DSUM\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DSUM(A4:E10,"Profit",A1:A2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 225); oParser = new parserFormula( 'DSUM(A4:E10,"Profit", A1:F3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 247.8); }); test( "Test: \"DVAR\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DVAR(A4:E10, "Yield", A1:A3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(1) - 0, 8.8); }); test( "Test: \"DVARP\"", function () { putDataForDatabase(); oParser = new parserFormula( 'DVARP(A4:E10, "Yield", A1:A3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 7.04); }); test( "Test: \"UNICODE\"", function () { oParser = new parserFormula( 'UNICODE(" ")', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 32); oParser = new parserFormula( 'UNICODE("B")', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 66); oParser = new parserFormula( 'UNICODE(0)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 48); oParser = new parserFormula( 'UNICODE(1)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 49); oParser = new parserFormula( 'UNICODE("true")', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 116); oParser = new parserFormula( 'UNICODE(#N/A)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A"); }); test( "Test: \"UNICHAR\"", function () { oParser = new parserFormula( 'UNICHAR(66)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "B"); oParser = new parserFormula( 'UNICHAR(32)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), " "); oParser = new parserFormula( 'UNICHAR(0)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!"); oParser = new parserFormula( 'UNICHAR(48)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "0"); oParser = new parserFormula( 'UNICHAR(49)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "1"); }); test( "Test: \"UPPER\"", function () { ws.getRange2( "A2" ).setValue( "total" ); ws.getRange2( "A3" ).setValue( "Yield" ); oParser = new parserFormula( 'UPPER(A2)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TOTAL"); oParser = new parserFormula( 'UPPER(A3)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "YIELD"); testArrayFormula2("UPPER", 1, 1); }); test( "Test: \"UNIQUE \"", function () { ws.getRange2( "A101" ).setValue( "1" ); ws.getRange2( "A102" ).setValue( "2" ); ws.getRange2( "A103" ).setValue( "2" ); ws.getRange2( "A104" ).setValue( "-1" ); ws.getRange2( "A105" ).setValue( "-1" ); ws.getRange2( "A106" ).setValue( "ds" ); ws.getRange2( "A107" ).setValue( "ds" ); ws.getRange2( "A108" ).setValue( "#NUM!" ); ws.getRange2( "A109" ).setValue( "#NUM!" ); ws.getRange2( "B101" ).setValue( "1" ); ws.getRange2( "B102" ).setValue( "2" ); ws.getRange2( "B103" ).setValue( "2" ); ws.getRange2( "B104" ).setValue( "4" ); ws.getRange2( "B105" ).setValue( "5" ); ws.getRange2( "B106" ).setValue( "7" ); ws.getRange2( "B107" ).setValue( "7" ); ws.getRange2( "B108" ).setValue( "8" ); ws.getRange2( "B109" ).setValue( "8" ); ws.getRange2( "C101" ).setValue( "2" ); ws.getRange2( "C102" ).setValue( "2" ); ws.getRange2( "C103" ).setValue( "2" ); ws.getRange2( "C104" ).setValue( "1" ); ws.getRange2( "C105" ).setValue( "1" ); ws.getRange2( "C106" ).setValue( "2" ); ws.getRange2( "C107" ).setValue( "3" ); ws.getRange2( "C108" ).setValue( "8" ); ws.getRange2( "C109" ).setValue( "8" ); ws.getRange2( "D101" ).setValue( "2" ); ws.getRange2( "D102" ).setValue( "2" ); ws.getRange2( "D103" ).setValue( "2" ); ws.getRange2( "D104" ).setValue( "1" ); ws.getRange2( "D105" ).setValue( "1" ); ws.getRange2( "D106" ).setValue( "2" ); ws.getRange2( "D107" ).setValue( "3" ); ws.getRange2( "D108" ).setValue( "8" ); ws.getRange2( "D109" ).setValue( "8" ); oParser = new parserFormula( "UNIQUE(A101:A109)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 2 ); strictEqual( oParser.calculate().getElementRowCol(2,0).getValue(), -1 ); strictEqual( oParser.calculate().getElementRowCol(3,0).getValue(), "ds" ); strictEqual( oParser.calculate().getElementRowCol(4,0).getValue(), "#NUM!" ); oParser = new parserFormula( "UNIQUE(A101:A109)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue(), 2 ); strictEqual( oParser.calculate().getElementRowCol(2,0).getValue(), -1 ); strictEqual( oParser.calculate().getElementRowCol(3,0).getValue(), "ds" ); strictEqual( oParser.calculate().getElementRowCol(4,0).getValue(), "#NUM!" ); oParser = new parserFormula( "UNIQUE(A101:D101)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(0,2).getValue(), 2 ); strictEqual( oParser.calculate().getElementRowCol(0,3).getValue(), 2 ); oParser = new parserFormula( "UNIQUE(A101:D101, true)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), 1 ); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue(), 2 ); oParser = new parserFormula( "UNIQUE(A101:D101, true, true)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!" ); ws.getRange2( "F102" ).setValue( "test" ); ws.getRange2( "F103" ).setValue( "#VALUE!" ); ws.getRange2( "F104" ).setValue( "test" ); ws.getRange2( "F105" ).setValue( "#VALUE!" ); ws.getRange2( "F106" ).setValue( "2" ); ws.getRange2( "F107" ).setValue( "-3" ); ws.getRange2( "G102" ).setValue( "2" ); ws.getRange2( "G103" ).setValue( "yyy" ); ws.getRange2( "G104" ).setValue( "4" ); ws.getRange2( "G105" ).setValue( "yyy" ); ws.getRange2( "G106" ).setValue( "asd" ); ws.getRange2( "G107" ).setValue( "7" ); ws.getRange2( "H102" ).setValue( "test" ); ws.getRange2( "H103" ).setValue( "#VALUE!" ); ws.getRange2( "H104" ).setValue( "test" ); ws.getRange2( "H105" ).setValue( "#VALUE!" ); ws.getRange2( "H106" ).setValue( "2" ); ws.getRange2( "H107" ).setValue( "-3" ); ws.getRange2( "I102" ).setValue( "2" ); ws.getRange2( "I103" ).setValue( "123" ); ws.getRange2( "I104" ).setValue( "4" ); ws.getRange2( "I105" ).setValue( "123" ); ws.getRange2( "I106" ).setValue( "6" ); ws.getRange2( "I107" ).setValue( "4" ); oParser = new parserFormula( "UNIQUE(F102:I107)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,2).getValue(), "test" ); strictEqual( oParser.calculate().getElementRowCol(1,2).getValue(), "#VALUE!" ); strictEqual( oParser.calculate().getElementRowCol(2,2).getValue(), "test" ); strictEqual( oParser.calculate().getElementRowCol(3,2).getValue(), 2 ); strictEqual( oParser.calculate().getElementRowCol(4,2).getValue(), -3 ); oParser = new parserFormula( "UNIQUE(F102:I107, true)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,2).getValue(), 2 ); strictEqual( oParser.calculate().getElementRowCol(1,2).getValue(), 123 ); strictEqual( oParser.calculate().getElementRowCol(2,2).getValue(), 4 ); strictEqual( oParser.calculate().getElementRowCol(3,2).getValue(), 123 ); strictEqual( oParser.calculate().getElementRowCol(4,2).getValue(), 6 ); strictEqual( oParser.calculate().getElementRowCol(5,2).getValue(), 4 ); oParser = new parserFormula( "UNIQUE(F102:I107, false, true)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue(), "test" ); strictEqual( oParser.calculate().getElementRowCol(1,1).getValue(), 4 ); strictEqual( oParser.calculate().getElementRowCol(2,2).getValue(), 2 ); strictEqual( oParser.calculate().getElementRowCol(3,3).getValue(), 4 ); oParser = new parserFormula( "UNIQUE(F102:I107, true, true)", "F1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue(), 2 ); strictEqual( oParser.calculate().getElementRowCol(1,1).getValue(), 123 ); strictEqual( oParser.calculate().getElementRowCol(2,1).getValue(), 4 ); strictEqual( oParser.calculate().getElementRowCol(3,1).getValue(), 123 ); strictEqual( oParser.calculate().getElementRowCol(4,1).getValue(), 6 ); strictEqual( oParser.calculate().getElementRowCol(5,1).getValue(), 4 ); } ); test( "Test: \"GROWTH\"", function () { ws.getRange2( "A102" ).setValue( "11" ); ws.getRange2( "A103" ).setValue( "12" ); ws.getRange2( "A104" ).setValue( "13" ); ws.getRange2( "A105" ).setValue( "14" ); ws.getRange2( "A106" ).setValue( "15" ); ws.getRange2( "A107" ).setValue( "16" ); ws.getRange2( "B102" ).setValue( "33100" ); ws.getRange2( "B103" ).setValue( "47300" ); ws.getRange2( "B104" ).setValue( "69000" ); ws.getRange2( "B105" ).setValue( "102000" ); ws.getRange2( "B106" ).setValue( "150000" ); ws.getRange2( "B107" ).setValue( "220000" ); ws.getRange2( "C102" ).setValue( "32618" ); ws.getRange2( "C103" ).setValue( "47729" ); ws.getRange2( "C104" ).setValue( "69841" ); ws.getRange2( "C105" ).setValue( "102197" ); ws.getRange2( "C106" ).setValue( "149542" ); ws.getRange2( "C107" ).setValue( "218822" ); ws.getRange2( "A109" ).setValue( "17" ); ws.getRange2( "A110" ).setValue( "18" ); oParser = new parserFormula( "GROWTH(B102:B107,A102:A107,A109:A110)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(4) - 0, 320196.7184); oParser = new parserFormula( "GROWTH(B102:B107,A102:A107)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(5) - 0, 32618.20377); oParser = new parserFormula( "GROWTH(A102:C102,A103:C104,A105:C106,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 11.00782679); oParser = new parserFormula( "GROWTH(A102:C102,A103:C104,A105:C106,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 11.00782679); oParser = new parserFormula( "GROWTH(A103:C103,A104:C105,A106:C107,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 12.00187209); oParser = new parserFormula( "GROWTH(A103:C103,A104:C105,A106:C107,10)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 12.00187209); oParser = new parserFormula( "GROWTH(A103:C103,A104:C105,A106:C107,0)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.0017632); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(3) - 0, 12047829814.167); strictEqual( oParser.calculate().getElementRowCol(0,2).getValue().toFixed(3) - 0, 10705900594.962); oParser = new parserFormula( "GROWTH({1,2,3},A104:C105,A106:C107,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.00038318); oParser = new parserFormula( "GROWTH({1,2,3},A104:C105,A106:C107,A106:C107)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!"); oParser = new parserFormula( "GROWTH(A103:C103,A104:C105,A106:C107,1)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 12.00187209); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(3) - 0, 676231620.297); strictEqual( oParser.calculate().getElementRowCol(0,2).getValue().toFixed(3) - 0, 612512904.254) } ); test( "Test: \"LOGEST\"", function () { ws.getRange2( "A101" ).setValue( "1" ); ws.getRange2( "A102" ).setValue( "2" ); ws.getRange2( "A103" ).setValue( "3" ); ws.getRange2( "A104" ).setValue( "4" ); ws.getRange2( "A105" ).setValue( "5" ); ws.getRange2( "A106" ).setValue( "6" ); ws.getRange2( "A107" ).setValue( "7" ); ws.getRange2( "A108" ).setValue( "8" ); ws.getRange2( "A109" ).setValue( "9" ); ws.getRange2( "A110" ).setValue( "10" ); ws.getRange2( "A111" ).setValue( "11" ); ws.getRange2( "A112" ).setValue( "12" ); ws.getRange2( "B101" ).setValue( "133890" ); ws.getRange2( "B102" ).setValue( "135000" ); ws.getRange2( "B103" ).setValue( "135790" ); ws.getRange2( "B104" ).setValue( "137300" ); ws.getRange2( "B105" ).setValue( "138130" ); ws.getRange2( "B106" ).setValue( "139100" ); ws.getRange2( "B107" ).setValue( "139900" ); ws.getRange2( "B108" ).setValue( "141120" ); ws.getRange2( "B109" ).setValue( "141890" ); ws.getRange2( "B110" ).setValue( "143230" ); ws.getRange2( "B111" ).setValue( "144000" ); ws.getRange2( "B112" ).setValue( "145290" ); ws.getRange2( "A115" ).setValue( "13" ); ws.getRange2( "A116" ).setValue( "14" ); ws.getRange2( "A117" ).setValue( "15" ); ws.getRange2( "A118" ).setValue( "16" ); ws.getRange2( "A119" ).setValue( "17" ); oParser = new parserFormula( "LOGEST(B101:B112,A101:A112)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.00732561); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 133044.8167); oParser = new parserFormula( "LOGEST(B101:B112,A101:A112,,false)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.00732561); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 133044.8167); //todo необходимо перепроверить остальные значения в данном случае oParser = new parserFormula( "LOGEST(B101:B112,A101:A112,,true)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.00732561); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 133044.8167); oParser = new parserFormula( "LOGEST(B101:B112,A101:A112,true,true)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.00732561); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 133044.8167); //todo необходимо перепроверить остальные значения в данном случае oParser = new parserFormula( "LOGEST(B101:B112,A101:A112,false,true)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 4.15001464); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 1); oParser = new parserFormula( "LOGEST(A101:B105,A106:B110,FALSE,TRUE)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.0000838); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 1); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue().toFixed(8) - 0, 0.00000264); strictEqual( oParser.calculate().getElementRowCol(2,0).getValue().toFixed(4) - 0, 0.9911); strictEqual( oParser.calculate().getElementRowCol(3,0).getValue().toFixed(4) - 0, 1005.3131); strictEqual( oParser.calculate().getElementRowCol(4,0).getValue().toFixed(4) - 0, 698.5684); oParser = new parserFormula( "LOGEST(A101:B105,A106:B110,,)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.00007701); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 2.6063); oParser = new parserFormula( "LOGEST(A101:B105,A106:B110,false,false)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.0000838); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 1); //todo необходимо перепроверить остальные значения в данном случае oParser = new parserFormula( "LOGEST(A101:B105,A106:B110,true,true)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getElementRowCol(0,0).getValue().toFixed(8) - 0, 1.00007701); strictEqual( oParser.calculate().getElementRowCol(0,1).getValue().toFixed(4) - 0, 2.6063); strictEqual( oParser.calculate().getElementRowCol(1,0).getValue().toFixed(8) - 0, 0.00000205); strictEqual( oParser.calculate().getElementRowCol(2,0).getValue().toFixed(4) - 0, 0.9944); strictEqual( oParser.calculate().getElementRowCol(3,0).getValue().toFixed(4) - 0, 1416.4887); strictEqual( oParser.calculate().getElementRowCol(4,0).getValue().toFixed(4) - 0, 294.9627); } ); test( "Test: \"PDURATION\"", function () { oParser = new parserFormula( "PDURATION(2.5%,2000,2200)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 3.86); oParser = new parserFormula( "PDURATION(0.025/12,1000,1200)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(1) - 0, 87.6); oParser = new parserFormula( "PDURATION(0.025,1000,1200)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 7.38); oParser = new parserFormula( "PDURATION(-0.025,1000,1200)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "PDURATION(0.025,-1000,1200)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "PDURATION(0.025,1000,-1200)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!"); oParser = new parserFormula( "PDURATION({0.025},{1000},{1200})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 7.38); oParser = new parserFormula( "PDURATION(\"TEST\",1000,-1200)", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#VALUE!"); testArrayFormula2("PDURATION", 3, 3); }); test( "Test: \"IFS\"", function () { oParser = new parserFormula( 'IFS(1,"TEST")', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TEST"); oParser = new parserFormula( 'IFS(0,"TEST",1,"TEST2")', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TEST2"); oParser = new parserFormula( 'IFS(2<1,">3")', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A"); oParser = new parserFormula( 'IFS(2<1,">3",2>1)', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#N/A"); oParser = new parserFormula( 'IFS(2<1,"TEST",2<1,2,4>3,"TEST2")', "AA2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "TEST2"); testArrayFormulaEqualsValues("1,3.123,-4,#N/A;2,4,5,#N/A;#N/A,#N/A,#N/A,#N/A","IFS(A1:C2,A1:C2,A1:C2,A1:C2, A1:C2,A1:C2)"); }); test( "Test: \"IF\"", function () { oParser = new parserFormula('IF(1,"TEST")', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "TEST"); oParser = new parserFormula('IF(0,"TEST")', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "FALSE"); ws.getRange2( "A101" ).setValue( "1" ); oParser = new parserFormula('IF(A101=1,"Yes","No")', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "Yes"); oParser = new parserFormula('IF(A101=2,"Yes","No")', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), "No"); //TODO нужна другая функция для тестирования //testArrayFormula2("IF", 2, 3); }); test( "Test: \"COLUMN\"", function () { oParser = new parserFormula('COLUMN(B6)', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); oParser = new parserFormula('COLUMN(C16)', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 3); oParser = new parserFormula('COLUMN()', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 1); oParser = new parserFormula('COLUMN()+COLUMN()', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); testArrayFormulaEqualsValues("5,6,7,8;5,6,7,8;5,6,7,8", "COLUMN()"); testArrayFormulaEqualsValues("1,2,3,#N/A;1,2,3,#N/A;1,2,3,#N/A", "COLUMN(A1:C2)"); testArrayFormulaEqualsValues("1,2,#N/A,#N/A;1,2,#N/A,#N/A;1,2,#N/A,#N/A", "COLUMN(A1:B1)"); testArrayFormulaEqualsValues("1,1,1,1;1,1,1,1;1,1,1,1", "COLUMN(A1)"); }); test( "Test: \"COLUMNS\"", function () { oParser = new parserFormula('COLUMNS(C1:E4)', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 3); oParser = new parserFormula('COLUMNS({1,2,3;4,5,6})', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 3); //TODO нужна другая функция для тестирования //testArrayFormula2("COLUMNS", 1, 1); }); test( "Test: \"ROW\"", function () { oParser = new parserFormula('ROW(B6)', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 6); oParser = new parserFormula('ROW(C16)', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 16); oParser = new parserFormula('ROW()', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 1); oParser = new parserFormula('ROW()+ROW()', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); testArrayFormulaEqualsValues("6,6,6,6;7,7,7,7;8,8,8,8", "ROW()"); testArrayFormulaEqualsValues("1,1,1,1;2,2,2,2;#N/A,#N/A,#N/A,#N/A", "ROW(A1:C2)"); testArrayFormulaEqualsValues("1,1,1,1;1,1,1,1;1,1,1,1", "ROW(A1:B1)"); testArrayFormulaEqualsValues("1,1,1,1;1,1,1,1;1,1,1,1", "ROW(A1)"); }); test( "Test: \"ROWS\"", function () { oParser = new parserFormula('ROWS(C1:E4)', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 4); oParser = new parserFormula('ROWS({1,2,3;4,5,6})', "AA2", ws); ok(oParser.parse()); strictEqual(oParser.calculate().getValue(), 2); //TODO нужна другая функция для тестирования //testArrayFormula2("COLUMNS", 1, 1); }); test( "Test: \"SUBTOTAL\"", function () { ws.getRange2( "A102" ).setValue( "120" ); ws.getRange2( "A103" ).setValue( "10" ); ws.getRange2( "A104" ).setValue( "150" ); ws.getRange2( "A105" ).setValue( "23" ); oParser = new parserFormula( "SUBTOTAL(1,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(1,A102:A105)" ); strictEqual( oParser.calculate().getValue().toFixed(2) - 0, 75.75, "SUBTOTAL(1,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(2,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(2,A102:A105)" ); strictEqual( oParser.calculate().getValue(), 4, "SUBTOTAL(2,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(3,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(3,A102:A105)" ); strictEqual( oParser.calculate().getValue(), 4, "SUBTOTAL(3,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(4,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(4,A102:A105)" ); strictEqual( oParser.calculate().getValue(), 150, "SUBTOTAL(4,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(5,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(5,A102:A105)" ); strictEqual( oParser.calculate().getValue(), 10, "SUBTOTAL(5,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(6,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(6,A102:A105)" ); strictEqual( oParser.calculate().getValue(), 4140000, "SUBTOTAL(6,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(7,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(7,A102:A105)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 69.70592992, "SUBTOTAL(7,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(8,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(8,A102:A105)" ); strictEqual( oParser.calculate().getValue().toFixed(8) - 0, 60.36710611, "SUBTOTAL(8,A102:A105)"); oParser = new parserFormula( "SUBTOTAL(9,A102:A105)", "A2", ws ); ok( oParser.parse(), "SUBTOTAL(9,A102:A105)" ); strictEqual( oParser.calculate().getValue(), 303, "SUBTOTAL(9,A102:A105)"); } ); test( "Test: \"MID\"", function () { ws.getRange2( "A101" ).setValue( "Fluid Flow" ); oParser = new parserFormula( "MID(A101,1,5)", "A2", ws ); ok( oParser.parse(), "MID(A101,1,5)" ); strictEqual( oParser.calculate().getValue(), "Fluid", "MID(A101,1,5)"); oParser = new parserFormula( "MID(A101,7,20)", "A2", ws ); ok( oParser.parse(), "MID(A101,7,20)" ); strictEqual( oParser.calculate().getValue(), "Flow", "MID(A101,7,20)"); oParser = new parserFormula( "MID(A101,20,5)", "A2", ws ); ok( oParser.parse(), "MID(A101,20,5)" ); strictEqual( oParser.calculate().getValue(), "", "MID(A101,20,5))"); oParser = new parserFormula( "MID(TRUE,2,5)", "A2", ws ); ok( oParser.parse(), "MID(TRUE,2,5)" ); strictEqual( oParser.calculate().getValue(), "RUE", "MID(TRUE,2,5)"); testArrayFormula2("MID", 3, 3); } ); test( "Test: \"MIDB\"", function () { ws.getRange2( "A101" ).setValue( "Fluid Flow" ); oParser = new parserFormula( "MIDB(A101,1,5)", "A2", ws ); ok( oParser.parse(), "MIDB(A101,1,5)" ); strictEqual( oParser.calculate().getValue(), "Fluid", "MIDB(A101,1,5)"); oParser = new parserFormula( "MIDB(A101,7,20)", "A2", ws ); ok( oParser.parse(), "MIDB(A101,7,20)" ); strictEqual( oParser.calculate().getValue(), "Flow", "MIDB(A101,7,20)"); oParser = new parserFormula( "MIDB(A101,20,5)", "A2", ws ); ok( oParser.parse(), "MIDB(A101,20,5)" ); strictEqual( oParser.calculate().getValue(), "", "MIDB(A101,20,5))"); oParser = new parserFormula( "MIDB(TRUE,2,5)", "A2", ws ); ok( oParser.parse(), "MIDB(TRUE,2,5)" ); strictEqual( oParser.calculate().getValue(), "RUE", "MIDB(TRUE,2,5)"); } ); test( "Test: \"MINUTE\"", function () { ws.getRange2( "A202" ).setValue( "12:45:00 PM" ); ws.getRange2( "A203" ).setValue( "7/18/2011 7:45" ); ws.getRange2( "A204" ).setValue( "4/21/2012" ); oParser = new parserFormula( "MINUTE(A202)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 45 ); oParser = new parserFormula( "MINUTE(A203)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 45 ); oParser = new parserFormula( "MINUTE(A204)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); ws.getRange2( "A205" ).setValue( "06/30/2020 20:00" ); ws.getRange2( "A206" ).setValue( "06/30/2020 21:15" ); ws.getRange2( "A207" ).setValue( "06/30/2020 23:15" ); oParser = new parserFormula( "MINUTE(A206-A205)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 15 ); oParser = new parserFormula( "MINUTE(A207-A205)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 15 ); oParser = new parserFormula( "MINUTE(A207-A206)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); oParser = new parserFormula( "MINUTE(A207+A206)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 30 ); oParser = new parserFormula( "MINUTE(123.1231231 - 1.12334343)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 59 ); oParser = new parserFormula( "MINUTE(1.12334343 - 123.1231231)", "A1", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), "#NUM!" ); } ); /*test( "Test: \"MINVERSE\"", function () { ws.getRange2( "A202" ).setValue( "4" ); ws.getRange2( "A203" ).setValue( "2" ); ws.getRange2( "B202" ).setValue( "-1" ); ws.getRange2( "B203" ).setValue( "0" ); oParser = new parserFormula( "MINVERSE({4,-1;2,0})", "A2", ws ); ok( oParser.parse() ); strictEqual( oParser.calculate().getValue(), 0 ); } );*/ test( "Test: \"FIND\"", function () { ws.getRange2( "A101" ).setValue( "Miriam McGovern" ); oParser = new parserFormula( 'FIND("M",A101)', "A2", ws ); ok( oParser.parse(), 'FIND("M",A101)' ); strictEqual( oParser.calculate().getValue(), 1, 'FIND("M",A101)'); oParser = new parserFormula( 'FIND("m",A101)', "A2", ws ); ok( oParser.parse(), 'FIND("m",A101)' ); strictEqual( oParser.calculate().getValue(), 6, 'FIND("m",A101)'); oParser = new parserFormula( 'FIND("M",A101,3)', "A2", ws ); ok( oParser.parse(), 'FIND("M",A101,3)' ); strictEqual( oParser.calculate().getValue(), 8, 'FIND("M",A101,3)'); oParser = new parserFormula( 'FIND("U",TRUE)', "A2", ws ); ok( oParser.parse(), 'FIND("T",TRUE)' ); strictEqual( oParser.calculate().getValue(), 3, 'FIND("T",TRUE)'); testArrayFormula2("FIND", 2, 3); } ); test( "Test: \"FINDB\"", function () { ws.getRange2( "A101" ).setValue( "Miriam McGovern" ); oParser = new parserFormula( 'FINDB("M",A101)', "A2", ws ); ok( oParser.parse(), 'FINDB("M",A101)' ); strictEqual( oParser.calculate().getValue(), 1, 'FINDB("M",A101)'); oParser = new parserFormula( 'FINDB("m",A101)', "A2", ws ); ok( oParser.parse(), 'FINDB("m",A101)' ); strictEqual( oParser.calculate().getValue(), 6, 'FINDB("m",A101)'); oParser = new parserFormula( 'FINDB("M",A101,3)', "A2", ws ); ok( oParser.parse(), 'FINDB("M",A101,3)' ); strictEqual( oParser.calculate().getValue(), 8, 'FINDB("M",A101,3)'); oParser = new parserFormula( 'FINDB("U",TRUE)', "A2", ws ); ok( oParser.parse(), 'FINDB("T",TRUE)' ); strictEqual( oParser.calculate().getValue(), 3, 'FINDB("T",TRUE)'); } ); test( "Test: \">\"", function () { oParser = new parserFormula( '1.123>1.5', "A2", ws ); ok( oParser.parse(), '1.123>1.5' ); strictEqual( oParser.calculate().getValue(), "FALSE", '1.123>1.5'); oParser = new parserFormula( '1.555>1.5', "A2", ws ); ok( oParser.parse(), '1.555>1.5' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.555>1.5'); } ); test( "Test: \"<\"", function () { oParser = new parserFormula( '1.123<1.5', "A2", ws ); ok( oParser.parse(), '1.123<1.5' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.123<1.5'); oParser = new parserFormula( '1.555<1.5', "A2", ws ); ok( oParser.parse(), '1.555<1.5' ); strictEqual( oParser.calculate().getValue(), "FALSE", '1.555<1.5'); } ); test( "Test: \"=\"", function () { oParser = new parserFormula( '1.123=1.5', "A2", ws ); ok( oParser.parse(), '1.123=1.5' ); strictEqual( oParser.calculate().getValue(), "FALSE", '1.123=1.5'); oParser = new parserFormula( '1.555=1.555', "A2", ws ); ok( oParser.parse(), '1.555=1.555' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.555=1.555'); } ); test( "Test: \"<>\"", function () { oParser = new parserFormula( '1.123<>1.5', "A2", ws ); ok( oParser.parse(), '1.123<>1.5' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.123<>1.5'); oParser = new parserFormula( '1.555<>1.555', "A2", ws ); ok( oParser.parse(), '1.555<>1.555' ); strictEqual( oParser.calculate().getValue(), "FALSE", '1.555<>1.555'); } ); test( "Test: \">=\"", function () { oParser = new parserFormula( '1.123>=1.5', "A2", ws ); ok( oParser.parse(), '1.123>=1.5' ); strictEqual( oParser.calculate().getValue(), "FALSE", '1.123>=1.5'); oParser = new parserFormula( '1.555>=1.555', "A2", ws ); ok( oParser.parse(), '1.555>=1.555' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.555>=1.555'); oParser = new parserFormula( '1.557>=1.555', "A2", ws ); ok( oParser.parse(), '1.557>=1.555' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.557>=1.555'); } ); test( "Test: \"<=\"", function () { oParser = new parserFormula( '1.123<=1.5', "A2", ws ); ok( oParser.parse(), '1.123<=1.5' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.123<=1.5'); oParser = new parserFormula( '1.555<=1.555', "A2", ws ); ok( oParser.parse(), '1.555<=1.555' ); strictEqual( oParser.calculate().getValue(), "TRUE", '1.555<=1.555'); oParser = new parserFormula( '1.557<=1.555', "A2", ws ); ok( oParser.parse(), '1.557<=1.555' ); strictEqual( oParser.calculate().getValue(), "FALSE", '1.557<=1.555'); } ); test( "Test: \"ADDRESS\"", function () { oParser = new parserFormula( "ADDRESS(2,3,2)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,2)" ); strictEqual( oParser.calculate().getValue(), "C$2", "ADDRESS(2,3,2)"); oParser = new parserFormula( "ADDRESS(2,3,2,FALSE)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,2,FALSE)" ); strictEqual( oParser.calculate().getValue(), "R2C[3]", "ADDRESS(2,3,2,FALSE)"); oParser = new parserFormula( 'ADDRESS(2,3,1,FALSE,"[Book1]Sheet1")', "A2", ws ); ok( oParser.parse(), 'ADDRESS(2,3,1,FALSE,"[Book1]Sheet1")' ); strictEqual( oParser.calculate().getValue(), "'[Book1]Sheet1'!R2C3", 'ADDRESS(2,3,1,FALSE,"[Book1]Sheet1")'); oParser = new parserFormula( 'ADDRESS(2,3,1,FALSE,"EXCEL SHEET")', "A2", ws ); ok( oParser.parse(), 'ADDRESS(2,3,1,FALSE,"EXCEL SHEET")' ); strictEqual( oParser.calculate().getValue(), "'EXCEL SHEET'!R2C3", 'ADDRESS(2,3,1,FALSE,"EXCEL SHEET")'); ws.getRange2( "A101" ).setValue( "" ); oParser = new parserFormula( "ADDRESS(2,3,2,1,A101)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,2,1,A101" ); strictEqual( oParser.calculate().getValue(), "!C$2", "ADDRESS(2,3,2,1,A101"); ws.getRange2( "A101" ).setValue( "'" ); oParser = new parserFormula( "ADDRESS(2,3,2,1,A101)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,2,1,A101" ); strictEqual( oParser.calculate().getValue(), "!C$2", "ADDRESS(2,3,2,1,A101"); oParser = new parserFormula( 'ADDRESS(2,3,2,1,"")', "A2", ws ); ok( oParser.parse(), 'ADDRESS(2,3,2,1,"")' ); strictEqual( oParser.calculate().getValue(), "!C$2", 'ADDRESS(2,3,2,1,"")'); oParser = new parserFormula( "ADDRESS(2,3,2,1,\"'\")", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,2,1,\"'\")" ); strictEqual( oParser.calculate().getValue(), "''''!C$2", "ADDRESS(2,3,2,1,\"'\")"); oParser = new parserFormula( "ADDRESS(2,3,,,1)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,,,1)" ); strictEqual( oParser.calculate().getValue(), "'1'!$C$2", "ADDRESS(2,3,,,1)"); oParser = new parserFormula( "ADDRESS(2,3,1,,1)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,1,,1)" ); strictEqual( oParser.calculate().getValue(), "'1'!$C$2", "ADDRESS(2,3,1,,1)"); oParser = new parserFormula( "ADDRESS(2,3,2,,1)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,2,,1)" ); strictEqual( oParser.calculate().getValue(), "'1'!C$2", "ADDRESS(2,3,2,,1)"); oParser = new parserFormula( "ADDRESS(2,3,,TRUE,1)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,,TRUE,1)" ); strictEqual( oParser.calculate().getValue(), "'1'!$C$2", "ADDRESS(2,3,,TRUE,1)"); oParser = new parserFormula( "ADDRESS(2,3,,FALSE,1)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,,FALSE,1)" ); strictEqual( oParser.calculate().getValue(), "'1'!R2C3", "ADDRESS(2,3,,FALSE,1)"); oParser = new parserFormula( "ADDRESS(2,3,,FALSE,1)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2,3,,FALSE,1)" ); strictEqual( oParser.calculate().getValue(), "'1'!R2C3", "ADDRESS(2,3,,FALSE,1)"); oParser = new parserFormula( "ADDRESS(1,7,,)", "A2", ws ); ok( oParser.parse(), "ADDRESS(1,7,,)" ); strictEqual( oParser.calculate().getValue(), "$G$1", "ADDRESS(1,7,,)"); oParser = new parserFormula( "ADDRESS(1,7,,,)", "A2", ws ); ok( oParser.parse(), "ADDRESS(1,7,,,)" ); strictEqual( oParser.calculate().getValue(), "$G$1", "ADDRESS(1,7,,,)"); oParser = new parserFormula( "ADDRESS(2.123,3.3213,2)", "A2", ws ); ok( oParser.parse(), "ADDRESS(2.123,3.3213,2)" ); strictEqual( oParser.calculate().getValue(), "C$2", "ADDRESS(2.123,3.3213,2)"); testArrayFormula2("ADDRESS", 2, 5); } ); test( "Test: \"reference argument test\"", function () { ws.getRange2( "A1" ).setValue( "1" ); ws.getRange2( "A2" ).setValue( "2" ); ws.getRange2( "A3" ).setValue( "3" ); ws.getRange2( "A4" ).setValue( "4" ); ws.getRange2( "A5" ).setValue( "5" ); ws.getRange2( "A6" ).setValue( "6" ); ws.getRange2( "B1" ).setValue( "2" ); ws.getRange2( "B2" ).setValue( "" ); ws.getRange2( "B3" ).setValue( "3" ); ws.getRange2( "B4" ).setValue( "4" ); ws.getRange2( "B5" ).setValue( "5" ); ws.getRange2( "B6" ).setValue( "6" ); oParser = new parserFormula( 'IRR(SIN(A1:B4))', 'A2', ws ); ok( oParser.parse(),'IRR(SIN(A1:B4))' ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, -0.123554096,'IRR(SIN(A1:B4))'); oParser = new parserFormula( 'MIRR(SIN(A2:B4),1,1)', 'A2', ws ); ok( oParser.parse(),'MIRR(SIN(A2:B4),1,1)' ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0, 2.36894463,'MIRR(SIN(A2:B4),1,1)'); oParser = new parserFormula( 'COLUMN(INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'COLUMN(INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'COLUMN(INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'COLUMNS(SIN($A$1:$B$4))', 'A2', ws ); ok( oParser.parse(),'COLUMNS(SIN($A$1:$B$4))' ); strictEqual( oParser.calculate().getValue(),2,'COLUMNS(SIN($A$1:$B$4))'); oParser = new parserFormula( 'INDEX(SIN(A1:B3),1,1)', 'A2', ws ); ok( oParser.parse(),'INDEX(SIN(A1:B3),1,1)' ); strictEqual( oParser.calculate().getValue().toFixed(9) - 0,0.841470985,'INDEX(SIN(A1:B3),1,1)'); /*oParser = new parserFormula( 'OFFSET(INDEX(A1:B3,1,1),1,1)', 'A2', ws ); ok( oParser.parse(),'OFFSET(INDEX(A1:B3,1,1),1,1)' ); strictEqual( oParser.calculate().getValue(),0,'OFFSET(INDEX(A1:B3,1,1),1,1)');*/ oParser = new parserFormula( 'ROW(INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'ROW(INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'ROW(INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'ROWS(SIN(A1:B3))', 'A2', ws ); ok( oParser.parse(),'ROWS(SIN(A1:B3))' ); strictEqual( oParser.calculate().getValue(),3,'ROWS(SIN(A1:B3))'); oParser = new parserFormula( 'SUBTOTAL(1,INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'SUBTOTAL(1,INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'SUBTOTAL(1,INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'SUMIF(INDEX(A1:B3,1,1),1,INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'SUMIF(INDEX(A1:B3,1,1),1,INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'SUMIF(INDEX(A1:B3,1,1),1,INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'SUMIFS(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'SUMIFS(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'SUMIFS(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'AVERAGEIF(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'AVERAGEIF(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'AVERAGEIF(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'COUNTBLANK(INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'COUNTBLANK(INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),0,'COUNTBLANK(INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'COUNTIF(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'COUNTIF(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'COUNTIF(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))'); oParser = new parserFormula( 'COUNTIFS(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))', 'A2', ws ); ok( oParser.parse(),'COUNTIFS(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))' ); strictEqual( oParser.calculate().getValue(),1,'COUNTIFS(INDEX(A1:B3,1,1),INDEX(A1:B3,1,1))'); ws.getRange2( "A2" ).setValue( "qq" ); ws.getRange2( "A3" ).setValue( "ww" ); ws.getRange2( "A4" ).setValue( "ee" ); ws.getRange2( "A5" ).setValue( "qq" ); ws.getRange2( "A6" ).setValue( "qq" ); ws.getRange2( "A7" ).setValue( "ww" ); ws.getRange2( "A8" ).setValue( "ww" ); ws.getRange2( "A9" ).setValue( "ww" ); ws.getRange2( "A10" ).setValue( "eee" ); ws.getRange2( "B1" ).setValue( "qqqq" ); ws.getRange2( "B2" ).setValue( "ee" ); var _f = 'IFERROR(INDEX($A$2:$A$10,MATCH(0,INDEX(COUNTIF($B$1:B1,$A$2:$A$10)+(COUNTIF($A$2:$A$10,$A$2:$A$10)<>1),0,0),0)),"")'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue().getValue(),"ee",_f); _f = 'IFERROR(INDEX($A$2:$A$10,MATCH(0,INDEX(COUNTIF($B$1:B2,$A$2:$A$10)+(COUNTIF($A$2:$A$10,$A$2:$A$10)<>1),0,0),0)),"")'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue().getValue(),"eee",_f); _f = 'INDEX($A$2:$A$10,MATCH(0,INDEX(COUNTIF($B$1:B1,$A$2:$A$10)+(COUNTIF($A$2:$A$10,$A$2:$A$10)<>1),0,0),0))'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue().getValue(),"ee",_f); _f = 'MATCH(0,INDEX({1;1;0;1;1;1;1;1;0},0,0))'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue(),"#N/A",_f); _f = 'INDEX($A$2:$A$10,MATCH(0,INDEX({1;1;0;1;1;1;1;1;0},0,0),0))'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue().getValue(),"ee",_f); _f = 'INDEX($A$2:$A$10,3)'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue().getValue(),"ee",_f); _f = 'INDEX($A$2:$A$10,MATCH(0,{1;1;0;1;1;1;1;1;0},0))'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue().getValue(),"ee",_f); _f = 'MATCH(0,INDEX(COUNTIF($B$1:B1,$A$2:$A$10)+(COUNTIF($A$2:$A$10,$A$2:$A$10)<>1),0,0),0)'; oParser = new parserFormula( _f, 'A2', ws ); ok( oParser.parse(), _f ); strictEqual( oParser.calculate().getValue(),3,_f); } ); wb.dependencyFormulas.unlockRecal(); } );
[se] text test changes
cell/.unit-tests/FormulaTests.js
[se] text test changes
<ide><path>ell/.unit-tests/FormulaTests.js <ide> <ide> oParser = new parserFormula( "TEXT(123,\"основной\")", "A2", ws ); <ide> ok( oParser.parse() ); <del> strictEqual( oParser.calculate().getValue(), "General" ); <add> strictEqual( oParser.calculate().getValue(), "123" ); <ide> <ide> AscCommon.setCurrentCultureInfo(culturelciddefault); <ide> //____________________________________en_____________________________________________ <ide> <ide> oParser = new parserFormula( "TEXT(123,\"general\")", "A2", ws ); <ide> ok( oParser.parse() ); <del> strictEqual( oParser.calculate().getValue(), "General" ); <add> strictEqual( oParser.calculate().getValue(), "123" ); <ide> AscCommon.setCurrentCultureInfo(culturelciddefault); <ide> //__________________________________es________________________________________________ <ide> AscCommon.setCurrentCultureInfo(3082); <ide> ok( oParser.parse() ); <ide> strictEqual( oParser.calculate().getValue(), "00:00:00" ); <ide> <del> oParser = new parserFormula( "TEXT(123,\"estándar\")", "A2", ws ); <del> ok( oParser.parse() ); <del> strictEqual( oParser.calculate().getValue(), "General" ); <add> oParser = new parserFormula( "TEXT(127,\"Estándar\")", "A2", ws ); <add> ok( oParser.parse() ); <add> strictEqual( oParser.calculate().getValue(), "127" ); <ide> <ide> AscCommon.setCurrentCultureInfo(culturelciddefault); <ide> //__________________________________fi________________________________________________ <ide> <ide> oParser = new parserFormula( "TEXT(123,\"yleinen\")", "A2", ws ); <ide> ok( oParser.parse() ); <del> strictEqual( oParser.calculate().getValue(), "General" ); <add> strictEqual( oParser.calculate().getValue(), "123" ); <ide> <ide> oParser = new parserFormula( "TEXT(123,\"\")", "A2", ws ); <ide> ok( oParser.parse() ); <ide> AscCommon.setCurrentCultureInfo(culturelciddefault); <ide> <ide> AscCommon.setCurrentCultureInfo(1041); <del> oParser = new parserFormula( "TEXT(123,\"G/標準\")", "A2", ws ); <del> ok( oParser.parse() ); <del> strictEqual( oParser.calculate().getValue(), "General" ); <add> oParser = new parserFormula( "TEXT(124,\"G/標準\")", "A2", ws ); <add> ok( oParser.parse() ); <add> strictEqual( oParser.calculate().getValue(), "124" ); <ide> <ide> AscCommon.setCurrentCultureInfo(culturelciddefault); <ide> } );
Java
mit
0fdfacbe52a3866e4565bc50c1bc9e93de6b01e8
0
windy1/google-places-api-java,0x3333/google-places-api-java,OtoAnalytics/google-places-api-java,hughsoong/google-places-api-java,andreibalan/google-places-api-java,abouzek/google-places-api-java
package se.walkercrou.places; import org.json.JSONArray; import org.json.JSONObject; import se.walkercrou.places.exception.GooglePlacesException; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static se.walkercrou.places.GooglePlaces.*; /** * Represents a place returned by Google Places API_ */ public class Place { private final List<String> types = new ArrayList<>(); private final List<Photo> photos = new ArrayList<>(); private final List<Review> reviews = new ArrayList<>(); private final List<AddressComponent> addressComponents = new ArrayList<>(); private final List<AltId> altIds = new ArrayList<>(); private GooglePlaces client; private String placeId; private Scope scope; private double lat = -1, lng = -1; private JSONObject json; private String iconUrl; private InputStream icon; private String name; private String addr; private String vicinity; private double rating = -1; private Status status = Status.NONE; private Price price = Price.NONE; private String phone, internationalPhone; private String googleUrl, website; private Hours hours; private int utcOffset; private int accuracy; private String lang; protected Place() { } /** * Parses a detailed Place object. * * @param client api client * @param rawJson json to parse * @return a detailed place */ public static Place parseDetails(GooglePlaces client, String rawJson) { JSONObject json = new JSONObject(rawJson); JSONObject result = json.getJSONObject(OBJECT_RESULT); // easy stuff String name = result.getString(STRING_NAME); String id = result.getString(STRING_PLACE_ID); String address = result.optString(STRING_ADDRESS, null); String phone = result.optString(STRING_PHONE_NUMBER, null); String iconUrl = result.optString(STRING_ICON, null); String internationalPhone = result.optString(STRING_INTERNATIONAL_PHONE_NUMBER, null); double rating = result.optDouble(DOUBLE_RATING, -1); String url = result.optString(STRING_URL, null); String vicinity = result.optString(STRING_VICINITY, null); String website = result.optString(STRING_WEBSITE, null); int utcOffset = result.optInt(INTEGER_UTC_OFFSET, -1); String scopeName = result.optString(STRING_SCOPE); Scope scope = scopeName == null ? null : Scope.valueOf(scopeName); // grab the price rank Price price = Price.NONE; if (result.has(INTEGER_PRICE_LEVEL)) price = Price.values()[result.getInt(INTEGER_PRICE_LEVEL)]; // location JSONObject location = result.getJSONObject(OBJECT_GEOMETRY).getJSONObject(OBJECT_LOCATION); double lat = location.getDouble(DOUBLE_LATITUDE), lng = location.getDouble(DOUBLE_LONGITUDE); // hours of operation JSONObject hours = result.optJSONObject(OBJECT_HOURS); Status status = Status.NONE; Hours schedule = new Hours(); if (hours != null) { boolean statusDefined = hours.has(BOOLEAN_OPENED); status = statusDefined && hours.getBoolean(BOOLEAN_OPENED) ? Status.OPENED : Status.CLOSED; // periods of operation JSONArray jsonPeriods = hours.optJSONArray(ARRAY_PERIODS); if (jsonPeriods != null) { for (int i = 0; i < jsonPeriods.length(); i++) { JSONObject jsonPeriod = jsonPeriods.getJSONObject(i); // opening information (from) JSONObject opens = jsonPeriod.getJSONObject(OBJECT_OPEN); Day openingDay = Day.values()[opens.getInt(INTEGER_DAY)]; String openingTime = opens.getString(STRING_TIME); // if this place is always open, break. boolean alwaysOpened = openingDay == Day.SUNDAY && openingTime.equals("0000") && !jsonPeriod.has(OBJECT_CLOSE); if (alwaysOpened) { schedule.setAlwaysOpened(true); break; } // closing information (to) JSONObject closes = jsonPeriod.getJSONObject(OBJECT_CLOSE); Day closingDay = Day.values()[closes.getInt(INTEGER_DAY)]; // to String closingTime = closes.getString(STRING_TIME); // add the period to the hours schedule.addPeriod(new Hours.Period().setOpeningDay(openingDay).setOpeningTime(openingTime) .setClosingDay(closingDay).setClosingTime(closingTime)); } } } Place place = new Place(); // photos JSONArray jsonPhotos = result.optJSONArray(ARRAY_PHOTOS); List<Photo> photos = new ArrayList<>(); if (jsonPhotos != null) { for (int i = 0; i < jsonPhotos.length(); i++) { JSONObject jsonPhoto = jsonPhotos.getJSONObject(i); String photoReference = jsonPhoto.getString(STRING_PHOTO_REFERENCE); int width = jsonPhoto.getInt(INTEGER_WIDTH), height = jsonPhoto.getInt(INTEGER_HEIGHT); photos.add(new Photo(place, photoReference, width, height)); } } // address components JSONArray addrComponents = result.optJSONArray(ARRAY_ADDRESS_COMPONENTS); List<AddressComponent> addressComponents = new ArrayList<>(); if (addrComponents != null) { for (int i = 0; i < addrComponents.length(); i++) { JSONObject ac = addrComponents.getJSONObject(i); AddressComponent addr = new AddressComponent(); String longName = ac.optString(STRING_LONG_NAME, null); String shortName = ac.optString(STRING_SHORT_NAME, null); addr.setLongName(longName); addr.setShortName(shortName); // address components have types too JSONArray types = ac.optJSONArray(ARRAY_TYPES); if (types != null) { for (int a = 0; a < types.length(); a++) { addr.addType(types.getString(a)); } } addressComponents.add(addr); } } // types JSONArray jsonTypes = result.optJSONArray(ARRAY_TYPES); List<String> types = new ArrayList<>(); if (jsonTypes != null) { for (int i = 0; i < jsonTypes.length(); i++) { types.add(jsonTypes.getString(i)); } } // reviews JSONArray jsonReviews = result.optJSONArray(ARRAY_REVIEWS); List<Review> reviews = new ArrayList<>(); if (jsonReviews != null) { for (int i = 0; i < jsonReviews.length(); i++) { JSONObject jsonReview = jsonReviews.getJSONObject(i); String author = jsonReview.optString(STRING_AUTHOR_NAME, null); String authorUrl = jsonReview.optString(STRING_AUTHOR_URL, null); String lang = jsonReview.optString(STRING_LANGUAGE, null); int reviewRating = jsonReview.optInt(INTEGER_RATING, -1); String text = jsonReview.optString(STRING_TEXT, null); long time = jsonReview.optLong(LONG_TIME, -1); // aspects of the review JSONArray jsonAspects = jsonReview.optJSONArray(ARRAY_ASPECTS); List<Review.Aspect> aspects = new ArrayList<>(); if (jsonAspects != null) { for (int a = 0; a < jsonAspects.length(); a++) { JSONObject jsonAspect = jsonAspects.getJSONObject(a); String aspectType = jsonAspect.getString(STRING_TYPE); int aspectRating = jsonAspect.getInt(INTEGER_RATING); aspects.add(new Review.Aspect(aspectRating, aspectType)); } } reviews.add(new Review().addAspects(aspects).setAuthor(author).setAuthorUrl(authorUrl).setLanguage(lang) .setRating(reviewRating).setText(text).setTime(time)); } } // alt-ids JSONArray jsonAltIds = result.optJSONArray(ARRAY_ALT_IDS); List<AltId> altIds = new ArrayList<>(); if (jsonAltIds != null) { for (int i = 0; i < jsonAltIds.length(); i++) { JSONObject jsonAltId = jsonAltIds.getJSONObject(i); String placeId = jsonAltId.getString(STRING_PLACE_ID); String sn = jsonAltId.getString(STRING_SCOPE); Scope s = sn == null ? null : Scope.valueOf(sn); altIds.add(new AltId(client, placeId, s)); } } return place.setPlaceId(id).setClient(client).setName(name).setAddress(address).setIconUrl(iconUrl).setPrice(price) .setLatitude(lat).setLongitude(lng).addTypes(types).setRating(rating).setStatus(status) .setVicinity(vicinity).setPhoneNumber(phone).setInternationalPhoneNumber(internationalPhone) .setGoogleUrl(url).setWebsite(website).addPhotos(photos).addAddressComponents(addressComponents) .setHours(schedule).addReviews(reviews).setUtcOffset(utcOffset).setScope(scope).addAltIds(altIds) .setJson(result); } /** * Returns the client associated with this Place object. * * @return client */ public GooglePlaces getClient() { return client; } /** * Sets the {@link se.walkercrou.places.GooglePlaces} client associated with this Place object. * * @param client to set * @return this */ protected Place setClient(GooglePlaces client) { this.client = client; return this; } /** * Returns the unique identifier for this place. * * @return id */ public String getPlaceId() { return placeId; } /** * Sets the unique, stable, identifier for this place. * * @param placeId to use * @return this */ protected Place setPlaceId(String placeId) { this.placeId = placeId; return this; } /** * Returns the latitude of the place. * * @return place latitude */ public double getLatitude() { return lat; } /** * Sets the latitude of the place. * * @param lat latitude * @return this */ protected Place setLatitude(double lat) { this.lat = lat; return this; } /** * Returns the longitude of this place. * * @return longitude */ public double getLongitude() { return lng; } /** * Sets the longitude of this place. * * @param lon longitude * @return this */ protected Place setLongitude(double lon) { this.lng = lon; return this; } /** * Returns the amount of seconds this place is off from the UTC timezone. * * @return seconds from timezone */ public int getUtcOffset() { return utcOffset; } /** * Sets the amount of seconds this place is off from the UTC timezone. * * @param utcOffset in seconds * @return this */ protected Place setUtcOffset(int utcOffset) { this.utcOffset = utcOffset; return this; } /** * Returns the {@link se.walkercrou.places.Hours} for this place. * * @return hours of operation */ public Hours getHours() { return hours; } /** * Sets the {@link se.walkercrou.places.Hours} of this place. * * @param hours of operation * @return this */ protected Place setHours(Hours hours) { this.hours = hours; return this; } /** * Returns true if this place is always opened. * * @return true if always opened */ public boolean isAlwaysOpened() { return hours.isAlwaysOpened(); } /** * Returns this Place's phone number. * * @return number */ public String getPhoneNumber() { return phone; } /** * Sets this Place's phone number. * * @param phone number * @return this */ protected Place setPhoneNumber(String phone) { this.phone = phone; return this; } /** * Returns the place's phone number with a country code. * * @return phone number */ public String getInternationalPhoneNumber() { return internationalPhone; } /** * Sets the phone number with an international country code. * * @param internationalPhone phone number * @return this */ protected Place setInternationalPhoneNumber(String internationalPhone) { this.internationalPhone = internationalPhone; return this; } /** * Returns the Google PLus page for this place. * * @return plus page */ public String getGoogleUrl() { return googleUrl; } /** * Sets the Google Plus page for this place. * * @param googleUrl google plus page * @return this */ protected Place setGoogleUrl(String googleUrl) { this.googleUrl = googleUrl; return this; } /** * Returns the website of this place. * * @return website */ public String getWebsite() { return website; } /** * Sets the website url associated with this place. * * @param website of place * @return this */ protected Place setWebsite(String website) { this.website = website; return this; } /** * Returns the "vicinity" the place is in. This is sometimes a substitute for address. * * @return vicinity */ public String getVicinity() { return vicinity; } /** * Sets the "vicinity" the place is in. This is sometimes a substitute for address. * * @param vicinity of place * @return this */ protected Place setVicinity(String vicinity) { this.vicinity = vicinity; return this; } /** * Returns the url of the icon to represent this place. * * @return icon to represent */ public String getIconUrl() { return iconUrl; } /** * Sets the url of the icon to represent this place. * * @param iconUrl to represent place. * @return this */ protected Place setIconUrl(String iconUrl) { this.iconUrl = iconUrl; return this; } /** * Downloads the icon to this place. * * @return this */ public Place downloadIcon() { icon = client.download(iconUrl); return this; } /** * Returns the input stream of this place. {@link #downloadIcon()} must be called previous to call this. * * @return input stream */ public InputStream getIconInputStream() { return icon; } /** * Returns the icon image. {@link #downloadIcon()} must be called previous to this. * * @return image */ public BufferedImage getIconImage() { try { return ImageIO.read(icon); } catch (Exception e) { throw new GooglePlacesException(e); } } /** * Returns the name of this place. * * @return name of place */ public String getName() { return name; } /** * Sets the name of this place. * * @param name of place * @return this */ protected Place setName(String name) { this.name = name; return this; } /** * Returns the address of this place. * * @return address of this place */ public String getAddress() { return addr; } /** * Sets the address of this place. * * @param addr address * @return this */ protected Place setAddress(String addr) { this.addr = addr; return this; } /** * Adds a collection of address components to this place. * * @param c components to add * @return this */ protected Place addAddressComponents(Collection<AddressComponent> c) { this.addressComponents.addAll(c); return this; } /** * Returns the address components for this place. * * @return address components */ public List<AddressComponent> getAddressComponents() { return Collections.unmodifiableList(addressComponents); } /** * Adds a collection of photos to this place. * * @param photos to add * @return this */ protected Place addPhotos(Collection<Photo> photos) { this.photos.addAll(photos); return this; } /** * Returns the photo references for this place. * * @return photos */ public List<Photo> getPhotos() { return Collections.unmodifiableList(photos); } /** * Adds a collection of reviews to this place. * * @param reviews to add * @return this */ protected Place addReviews(Collection<Review> reviews) { this.reviews.addAll(reviews); return this; } /** * Returns this place's reviews in an unmodifiable list. * * @return reviews */ public List<Review> getReviews() { return Collections.unmodifiableList(reviews); } /** * Adds a collection of string "types". * * @param types to add * @return this */ protected Place addTypes(Collection<String> types) { this.types.addAll(types); return this; } /** * Returns all of this place's types in an unmodifiable list. * * @return types */ public List<String> getTypes() { return Collections.unmodifiableList(types); } /** * Adds a collection of {@link se.walkercrou.places.AltId}s. * * @param altIds to add * @return this */ protected Place addAltIds(Collection<AltId> altIds) { this.altIds.addAll(altIds); return this; } /** * Returns all of this place's alt-ids in an unmodifiable list. * * @return alt-ids */ public List<AltId> getAltIds() { return Collections.unmodifiableList(altIds); } /** * Returns the rating of this place. * * @return rating */ public double getRating() { return rating; } /** * Sets the rating of this place. * * @param rating of place * @return this */ protected Place setRating(double rating) { this.rating = rating; return this; } /** * Returns the {@link se.walkercrou.places.Status} of this place. * * @return status */ public Status getStatus() { return status; } /** * Sets the {@link se.walkercrou.places.Status} of this place. * * @param status to set * @return this */ protected Place setStatus(Status status) { this.status = status; return this; } /** * Returns the {@link se.walkercrou.places.Price} of this place. * * @return price */ public Price getPrice() { return price; } /** * Sets the {@link se.walkercrou.places.Price} of this place. * * @param price to set * @return this */ protected Place setPrice(Price price) { this.price = price; return this; } /** * Returns the JSON representation of this place. This does not build a JSON object, it only returns the JSON * that was given in the initial response from the server. * * @return the json representation */ public JSONObject getJson() { return json; } /** * Sets the JSON representation of this Place. * * @param json representation * @return this */ protected Place setJson(JSONObject json) { this.json = json; return this; } /** * Returns the accuracy of the location, expressed in meters. * * @return accuracy of location */ public int getAccuracy() { return accuracy; } /** * Sets the accuracy of the location, expressed in meters. * * @param accuracy of location * @return this */ protected Place setAccuracy(int accuracy) { this.accuracy = accuracy; return this; } /** * Returns the language of the place. * * @return language */ public String getLanguage() { return lang; } /** * Sets the language of the location. * * @param lang place language * @return this */ protected Place setLanguage(String lang) { this.lang = lang; return this; } /** * Returns the scope of this place. * * @return scope * @see se.walkercrou.places.Scope */ public Scope getScope() { return scope; } /** * Sets the scope of the location. * * @param scope to set * @return this * @see se.walkercrou.places.Scope */ protected Place setScope(Scope scope) { this.scope = scope; return this; } /** * Returns an updated Place object with more details than the Place object returned in an initial query. * * @param params extra params to include in the request url * @return a new place with more details */ public Place getDetails(Param... params) { return client.getPlaceById(placeId, params); } @Override public String toString() { return String.format("Place{id=%s}", placeId); } @Override public boolean equals(Object obj) { return obj instanceof Place && ((Place) obj).placeId.equals(placeId); } }
src/main/java/se/walkercrou/places/Place.java
package se.walkercrou.places; import org.json.JSONArray; import org.json.JSONObject; import se.walkercrou.places.exception.GooglePlacesException; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import static se.walkercrou.places.GooglePlaces.*; /** * Represents a place returned by Google Places API_ */ public class Place { private final List<String> types = new ArrayList<>(); private final List<Photo> photos = new ArrayList<>(); private final List<Review> reviews = new ArrayList<>(); private final List<AddressComponent> addressComponents = new ArrayList<>(); private final List<AltId> altIds = new ArrayList<>(); private GooglePlaces client; private String placeId; private Scope scope; private double lat = -1, lng = -1; private JSONObject json; private String iconUrl; private InputStream icon; private String name; private String addr; private String vicinity; private double rating = -1; private Status status = Status.NONE; private Price price = Price.NONE; private String phone, internationalPhone; private String googleUrl, website; private Hours hours; private int utcOffset; private int accuracy; private String lang; protected Place() { } /** * Parses a detailed Place object. * * @param client api client * @param rawJson json to parse * @return a detailed place */ public static Place parseDetails(GooglePlaces client, String rawJson) { JSONObject json = new JSONObject(rawJson); JSONObject result = json.getJSONObject(OBJECT_RESULT); // easy stuff String name = result.getString(STRING_NAME); String address = result.optString(STRING_ADDRESS, null); String phone = result.optString(STRING_PHONE_NUMBER, null); String iconUrl = result.optString(STRING_ICON, null); String internationalPhone = result.optString(STRING_INTERNATIONAL_PHONE_NUMBER, null); double rating = result.optDouble(DOUBLE_RATING, -1); String url = result.optString(STRING_URL, null); String vicinity = result.optString(STRING_VICINITY, null); String website = result.optString(STRING_WEBSITE, null); int utcOffset = result.optInt(INTEGER_UTC_OFFSET, -1); String scopeName = result.optString(STRING_SCOPE); Scope scope = scopeName == null ? null : Scope.valueOf(scopeName); // grab the price rank Price price = Price.NONE; if (result.has(INTEGER_PRICE_LEVEL)) { price = Price.values()[result.getInt(INTEGER_PRICE_LEVEL)]; } // location JSONObject location = result.getJSONObject(OBJECT_GEOMETRY).getJSONObject(OBJECT_LOCATION); double lat = location.getDouble(DOUBLE_LATITUDE), lng = location.getDouble(DOUBLE_LONGITUDE); // hours of operation JSONObject hours = result.optJSONObject(OBJECT_HOURS); Status status = Status.NONE; Hours schedule = new Hours(); if (hours != null) { boolean statusDefined = hours.has(BOOLEAN_OPENED); status = statusDefined && hours.getBoolean(BOOLEAN_OPENED) ? Status.OPENED : Status.CLOSED; // periods of operation JSONArray jsonPeriods = hours.optJSONArray(ARRAY_PERIODS); if (jsonPeriods != null) { for (int i = 0; i < jsonPeriods.length(); i++) { JSONObject jsonPeriod = jsonPeriods.getJSONObject(i); // opening information (from) JSONObject opens = jsonPeriod.getJSONObject(OBJECT_OPEN); Day openingDay = Day.values()[opens.getInt(INTEGER_DAY)]; String openingTime = opens.getString(STRING_TIME); // if this place is always open, break. boolean alwaysOpened = openingDay == Day.SUNDAY && openingTime.equals("0000") && !jsonPeriod.has(OBJECT_CLOSE); if (alwaysOpened) { schedule.setAlwaysOpened(true); break; } // closing information (to) JSONObject closes = jsonPeriod.getJSONObject(OBJECT_CLOSE); Day closingDay = Day.values()[closes.getInt(INTEGER_DAY)]; // to String closingTime = closes.getString(STRING_TIME); // add the period to the hours schedule.addPeriod(new Hours.Period().setOpeningDay(openingDay).setOpeningTime(openingTime) .setClosingDay(closingDay).setClosingTime(closingTime)); } } } Place place = new Place(); // photos JSONArray jsonPhotos = result.optJSONArray(ARRAY_PHOTOS); List<Photo> photos = new ArrayList<>(); if (jsonPhotos != null) { for (int i = 0; i < jsonPhotos.length(); i++) { JSONObject jsonPhoto = jsonPhotos.getJSONObject(i); String photoReference = jsonPhoto.getString(STRING_PHOTO_REFERENCE); int width = jsonPhoto.getInt(INTEGER_WIDTH), height = jsonPhoto.getInt(INTEGER_HEIGHT); photos.add(new Photo(place, photoReference, width, height)); } } // address components JSONArray addrComponents = result.optJSONArray(ARRAY_ADDRESS_COMPONENTS); List<AddressComponent> addressComponents = new ArrayList<>(); if (addrComponents != null) { for (int i = 0; i < addrComponents.length(); i++) { JSONObject ac = addrComponents.getJSONObject(i); AddressComponent addr = new AddressComponent(); String longName = ac.optString(STRING_LONG_NAME, null); String shortName = ac.optString(STRING_SHORT_NAME, null); addr.setLongName(longName); addr.setShortName(shortName); // address components have types too JSONArray types = ac.optJSONArray(ARRAY_TYPES); if (types != null) { for (int a = 0; a < types.length(); a++) { addr.addType(types.getString(a)); } } addressComponents.add(addr); } } // types JSONArray jsonTypes = result.optJSONArray(ARRAY_TYPES); List<String> types = new ArrayList<>(); if (jsonTypes != null) { for (int i = 0; i < jsonTypes.length(); i++) { types.add(jsonTypes.getString(i)); } } // reviews JSONArray jsonReviews = result.optJSONArray(ARRAY_REVIEWS); List<Review> reviews = new ArrayList<>(); if (jsonReviews != null) { for (int i = 0; i < jsonReviews.length(); i++) { JSONObject jsonReview = jsonReviews.getJSONObject(i); String author = jsonReview.optString(STRING_AUTHOR_NAME, null); String authorUrl = jsonReview.optString(STRING_AUTHOR_URL, null); String lang = jsonReview.optString(STRING_LANGUAGE, null); int reviewRating = jsonReview.optInt(INTEGER_RATING, -1); String text = jsonReview.optString(STRING_TEXT, null); long time = jsonReview.optLong(LONG_TIME, -1); // aspects of the review JSONArray jsonAspects = jsonReview.optJSONArray(ARRAY_ASPECTS); List<Review.Aspect> aspects = new ArrayList<>(); if (jsonAspects != null) { for (int a = 0; a < jsonAspects.length(); a++) { JSONObject jsonAspect = jsonAspects.getJSONObject(a); String aspectType = jsonAspect.getString(STRING_TYPE); int aspectRating = jsonAspect.getInt(INTEGER_RATING); aspects.add(new Review.Aspect(aspectRating, aspectType)); } } reviews.add(new Review().addAspects(aspects).setAuthor(author).setAuthorUrl(authorUrl).setLanguage(lang) .setRating(reviewRating).setText(text).setTime(time)); } } // alt-ids JSONArray jsonAltIds = result.optJSONArray(ARRAY_ALT_IDS); List<AltId> altIds = new ArrayList<>(); if (jsonAltIds != null) { for (int i = 0; i < jsonAltIds.length(); i++) { JSONObject jsonAltId = jsonAltIds.getJSONObject(i); String placeId = jsonAltId.getString(STRING_PLACE_ID); String sn = jsonAltId.getString(STRING_SCOPE); Scope s = sn == null ? null : Scope.valueOf(sn); altIds.add(new AltId(client, placeId, s)); } } return place.setClient(client).setName(name).setAddress(address).setIconUrl(iconUrl).setPrice(price) .setLatitude(lat).setLongitude(lng).addTypes(types).setRating(rating).setStatus(status) .setVicinity(vicinity).setPhoneNumber(phone).setInternationalPhoneNumber(internationalPhone) .setGoogleUrl(url).setWebsite(website).addPhotos(photos).addAddressComponents(addressComponents) .setHours(schedule).addReviews(reviews).setUtcOffset(utcOffset).setScope(scope).addAltIds(altIds) .setJson(result); } /** * Returns the client associated with this Place object. * * @return client */ public GooglePlaces getClient() { return client; } /** * Sets the {@link se.walkercrou.places.GooglePlaces} client associated with this Place object. * * @param client to set * @return this */ protected Place setClient(GooglePlaces client) { this.client = client; return this; } /** * Returns the unique identifier for this place. * * @return id */ public String getPlaceId() { return placeId; } /** * Sets the unique, stable, identifier for this place. * * @param placeId to use * @return this */ protected Place setPlaceId(String placeId) { this.placeId = placeId; return this; } /** * Returns the latitude of the place. * * @return place latitude */ public double getLatitude() { return lat; } /** * Sets the latitude of the place. * * @param lat latitude * @return this */ protected Place setLatitude(double lat) { this.lat = lat; return this; } /** * Returns the longitude of this place. * * @return longitude */ public double getLongitude() { return lng; } /** * Sets the longitude of this place. * * @param lon longitude * @return this */ protected Place setLongitude(double lon) { this.lng = lon; return this; } /** * Returns the amount of seconds this place is off from the UTC timezone. * * @return seconds from timezone */ public int getUtcOffset() { return utcOffset; } /** * Sets the amount of seconds this place is off from the UTC timezone. * * @param utcOffset in seconds * @return this */ protected Place setUtcOffset(int utcOffset) { this.utcOffset = utcOffset; return this; } /** * Returns the {@link se.walkercrou.places.Hours} for this place. * * @return hours of operation */ public Hours getHours() { return hours; } /** * Sets the {@link se.walkercrou.places.Hours} of this place. * * @param hours of operation * @return this */ protected Place setHours(Hours hours) { this.hours = hours; return this; } /** * Returns true if this place is always opened. * * @return true if always opened */ public boolean isAlwaysOpened() { return hours.isAlwaysOpened(); } /** * Returns this Place's phone number. * * @return number */ public String getPhoneNumber() { return phone; } /** * Sets this Place's phone number. * * @param phone number * @return this */ protected Place setPhoneNumber(String phone) { this.phone = phone; return this; } /** * Returns the place's phone number with a country code. * * @return phone number */ public String getInternationalPhoneNumber() { return internationalPhone; } /** * Sets the phone number with an international country code. * * @param internationalPhone phone number * @return this */ protected Place setInternationalPhoneNumber(String internationalPhone) { this.internationalPhone = internationalPhone; return this; } /** * Returns the Google PLus page for this place. * * @return plus page */ public String getGoogleUrl() { return googleUrl; } /** * Sets the Google Plus page for this place. * * @param googleUrl google plus page * @return this */ protected Place setGoogleUrl(String googleUrl) { this.googleUrl = googleUrl; return this; } /** * Returns the website of this place. * * @return website */ public String getWebsite() { return website; } /** * Sets the website url associated with this place. * * @param website of place * @return this */ protected Place setWebsite(String website) { this.website = website; return this; } /** * Returns the "vicinity" the place is in. This is sometimes a substitute for address. * * @return vicinity */ public String getVicinity() { return vicinity; } /** * Sets the "vicinity" the place is in. This is sometimes a substitute for address. * * @param vicinity of place * @return this */ protected Place setVicinity(String vicinity) { this.vicinity = vicinity; return this; } /** * Returns the url of the icon to represent this place. * * @return icon to represent */ public String getIconUrl() { return iconUrl; } /** * Sets the url of the icon to represent this place. * * @param iconUrl to represent place. * @return this */ protected Place setIconUrl(String iconUrl) { this.iconUrl = iconUrl; return this; } /** * Downloads the icon to this place. * * @return this */ public Place downloadIcon() { icon = client.download(iconUrl); return this; } /** * Returns the input stream of this place. {@link #downloadIcon()} must be called previous to call this. * * @return input stream */ public InputStream getIconInputStream() { return icon; } /** * Returns the icon image. {@link #downloadIcon()} must be called previous to this. * * @return image */ public BufferedImage getIconImage() { try { return ImageIO.read(icon); } catch (Exception e) { throw new GooglePlacesException(e); } } /** * Returns the name of this place. * * @return name of place */ public String getName() { return name; } /** * Sets the name of this place. * * @param name of place * @return this */ protected Place setName(String name) { this.name = name; return this; } /** * Returns the address of this place. * * @return address of this place */ public String getAddress() { return addr; } /** * Sets the address of this place. * * @param addr address * @return this */ protected Place setAddress(String addr) { this.addr = addr; return this; } /** * Adds a collection of address components to this place. * * @param c components to add * @return this */ protected Place addAddressComponents(Collection<AddressComponent> c) { this.addressComponents.addAll(c); return this; } /** * Returns the address components for this place. * * @return address components */ public List<AddressComponent> getAddressComponents() { return Collections.unmodifiableList(addressComponents); } /** * Adds a collection of photos to this place. * * @param photos to add * @return this */ protected Place addPhotos(Collection<Photo> photos) { this.photos.addAll(photos); return this; } /** * Returns the photo references for this place. * * @return photos */ public List<Photo> getPhotos() { return Collections.unmodifiableList(photos); } /** * Adds a collection of reviews to this place. * * @param reviews to add * @return this */ protected Place addReviews(Collection<Review> reviews) { this.reviews.addAll(reviews); return this; } /** * Returns this place's reviews in an unmodifiable list. * * @return reviews */ public List<Review> getReviews() { return Collections.unmodifiableList(reviews); } /** * Adds a collection of string "types". * * @param types to add * @return this */ protected Place addTypes(Collection<String> types) { this.types.addAll(types); return this; } /** * Returns all of this place's types in an unmodifiable list. * * @return types */ public List<String> getTypes() { return Collections.unmodifiableList(types); } /** * Adds a collection of {@link se.walkercrou.places.AltId}s. * * @param altIds to add * @return this */ protected Place addAltIds(Collection<AltId> altIds) { this.altIds.addAll(altIds); return this; } /** * Returns all of this place's alt-ids in an unmodifiable list. * * @return alt-ids */ public List<AltId> getAltIds() { return Collections.unmodifiableList(altIds); } /** * Returns the rating of this place. * * @return rating */ public double getRating() { return rating; } /** * Sets the rating of this place. * * @param rating of place * @return this */ protected Place setRating(double rating) { this.rating = rating; return this; } /** * Returns the {@link se.walkercrou.places.Status} of this place. * * @return status */ public Status getStatus() { return status; } /** * Sets the {@link se.walkercrou.places.Status} of this place. * * @param status to set * @return this */ protected Place setStatus(Status status) { this.status = status; return this; } /** * Returns the {@link se.walkercrou.places.Price} of this place. * * @return price */ public Price getPrice() { return price; } /** * Sets the {@link se.walkercrou.places.Price} of this place. * * @param price to set * @return this */ protected Place setPrice(Price price) { this.price = price; return this; } /** * Returns the JSON representation of this place. This does not build a JSON object, it only returns the JSON * that was given in the initial response from the server. * * @return the json representation */ public JSONObject getJson() { return json; } /** * Sets the JSON representation of this Place. * * @param json representation * @return this */ protected Place setJson(JSONObject json) { this.json = json; return this; } /** * Returns the accuracy of the location, expressed in meters. * * @return accuracy of location */ public int getAccuracy() { return accuracy; } /** * Sets the accuracy of the location, expressed in meters. * * @param accuracy of location * @return this */ protected Place setAccuracy(int accuracy) { this.accuracy = accuracy; return this; } /** * Returns the language of the place. * * @return language */ public String getLanguage() { return lang; } /** * Sets the language of the location. * * @param lang place language * @return this */ protected Place setLanguage(String lang) { this.lang = lang; return this; } /** * Returns the scope of this place. * * @return scope * @see se.walkercrou.places.Scope */ public Scope getScope() { return scope; } /** * Sets the scope of the location. * * @param scope to set * @return this * @see se.walkercrou.places.Scope */ protected Place setScope(Scope scope) { this.scope = scope; return this; } /** * Returns an updated Place object with more details than the Place object returned in an initial query. * * @param params extra params to include in the request url * @return a new place with more details */ public Place getDetails(Param... params) { return client.getPlaceById(placeId, params); } @Override public String toString() { return String.format("Place{id=%s}", placeId); } @Override public boolean equals(Object obj) { return obj instanceof Place && ((Place) obj).placeId.equals(placeId); } }
Set the placeId in Place.getDetails() (thanks Todd) Signed-off-by: Walker Crouse <[email protected]>
src/main/java/se/walkercrou/places/Place.java
Set the placeId in Place.getDetails() (thanks Todd)
<ide><path>rc/main/java/se/walkercrou/places/Place.java <ide> <ide> // easy stuff <ide> String name = result.getString(STRING_NAME); <add> String id = result.getString(STRING_PLACE_ID); <ide> String address = result.optString(STRING_ADDRESS, null); <ide> String phone = result.optString(STRING_PHONE_NUMBER, null); <ide> String iconUrl = result.optString(STRING_ICON, null); <ide> <ide> // grab the price rank <ide> Price price = Price.NONE; <del> if (result.has(INTEGER_PRICE_LEVEL)) { <add> if (result.has(INTEGER_PRICE_LEVEL)) <ide> price = Price.values()[result.getInt(INTEGER_PRICE_LEVEL)]; <del> } <ide> <ide> // location <ide> JSONObject location = result.getJSONObject(OBJECT_GEOMETRY).getJSONObject(OBJECT_LOCATION); <ide> } <ide> } <ide> <del> return place.setClient(client).setName(name).setAddress(address).setIconUrl(iconUrl).setPrice(price) <add> return place.setPlaceId(id).setClient(client).setName(name).setAddress(address).setIconUrl(iconUrl).setPrice(price) <ide> .setLatitude(lat).setLongitude(lng).addTypes(types).setRating(rating).setStatus(status) <ide> .setVicinity(vicinity).setPhoneNumber(phone).setInternationalPhoneNumber(internationalPhone) <ide> .setGoogleUrl(url).setWebsite(website).addPhotos(photos).addAddressComponents(addressComponents)
Java
apache-2.0
error: pathspec 'thread/src/main/java/org/tanc/concurrent/lock/ConditionUseCase.java' did not match any file(s) known to git
65032cba851883b26c7947a4e21c4eff5d7d0cef
1
gogotanc/java-demo
package org.tanc.concurrent.lock; import org.tanc.concurrent.thread.SleepUtils; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * condition 运用示例 * Created by tanc on 2017/5/2. */ public class ConditionUseCase { public static void main(String[] args) { C c = new C(); Thread a = new Thread(new A(c), "thread a"); Thread b = new Thread(new B(c), "thread b"); a.start(); SleepUtils.second(5); b.start(); } static class C { C() { lock = new ReentrantLock(); condition = lock.newCondition(); } private final Lock lock; private final Condition condition; void methodA() { lock.lock(); try { condition.await(); System.out.println("run"); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } void methodB() { lock.lock(); try { condition.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } } static class A implements Runnable { private final C c; A(C c) { this.c = c; } @Override public void run() { c.methodA(); } } static class B implements Runnable { private final C c; B(C c) { this.c = c; } @Override public void run() { c.methodB(); } } }
thread/src/main/java/org/tanc/concurrent/lock/ConditionUseCase.java
condition use case
thread/src/main/java/org/tanc/concurrent/lock/ConditionUseCase.java
condition use case
<ide><path>hread/src/main/java/org/tanc/concurrent/lock/ConditionUseCase.java <add>package org.tanc.concurrent.lock; <add> <add>import org.tanc.concurrent.thread.SleepUtils; <add> <add>import java.util.concurrent.locks.Condition; <add>import java.util.concurrent.locks.Lock; <add>import java.util.concurrent.locks.ReentrantLock; <add> <add>/** <add> * condition 运用示例 <add> * Created by tanc on 2017/5/2. <add> */ <add>public class ConditionUseCase { <add> <add> public static void main(String[] args) { <add> <add> C c = new C(); <add> <add> Thread a = new Thread(new A(c), "thread a"); <add> Thread b = new Thread(new B(c), "thread b"); <add> <add> a.start(); <add> <add> SleepUtils.second(5); <add> <add> b.start(); <add> } <add> <add> static class C { <add> <add> C() { <add> lock = new ReentrantLock(); <add> condition = lock.newCondition(); <add> } <add> <add> private final Lock lock; <add> private final Condition condition; <add> <add> void methodA() { <add> lock.lock(); <add> try { <add> condition.await(); <add> System.out.println("run"); <add> } catch (Exception e) { <add> e.printStackTrace(); <add> } finally { <add> lock.unlock(); <add> } <add> } <add> <add> void methodB() { <add> lock.lock(); <add> try { <add> condition.signal(); <add> } catch (Exception e) { <add> e.printStackTrace(); <add> } finally { <add> lock.unlock(); <add> } <add> } <add> } <add> <add> static class A implements Runnable { <add> <add> private final C c; <add> <add> A(C c) { <add> this.c = c; <add> } <add> <add> @Override <add> public void run() { <add> c.methodA(); <add> } <add> } <add> <add> static class B implements Runnable { <add> <add> private final C c; <add> <add> B(C c) { <add> this.c = c; <add> } <add> <add> @Override <add> public void run() { <add> c.methodB(); <add> } <add> } <add>}
Java
apache-2.0
eb20bb9c330bf88ef18fb50c82ffd68a3c4fe077
0
nectec-wisru/android-TanrabadSurvey,nectec-wisru/android-TanlabadSurvey,tanrabad/survey
/* * Copyright (c) 2016 NECTEC * National Electronics and Computer Technology Center, Thailand * * 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. */ package th.or.nectec.tanrabad.survey.presenter; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.AppCompatSpinner; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.*; import com.google.android.gms.maps.SupportMapFragment; import org.joda.time.DateTime; import th.or.nectec.tanrabad.domain.place.*; import th.or.nectec.tanrabad.entity.Place; import th.or.nectec.tanrabad.entity.field.Location; import th.or.nectec.tanrabad.entity.lookup.PlaceSubType; import th.or.nectec.tanrabad.entity.lookup.PlaceType; import th.or.nectec.tanrabad.survey.R; import th.or.nectec.tanrabad.survey.job.AbsJobRunner; import th.or.nectec.tanrabad.survey.job.Job; import th.or.nectec.tanrabad.survey.job.PostDataJob; import th.or.nectec.tanrabad.survey.job.PutDataJob; import th.or.nectec.tanrabad.survey.presenter.maps.LiteMapFragment; import th.or.nectec.tanrabad.survey.presenter.maps.LocationUtils; import th.or.nectec.tanrabad.survey.repository.BrokerPlaceRepository; import th.or.nectec.tanrabad.survey.repository.adapter.ThaiWidgetProvinceRepository; import th.or.nectec.tanrabad.survey.repository.persistence.DbPlaceRepository; import th.or.nectec.tanrabad.survey.service.PlaceRestService; import th.or.nectec.tanrabad.survey.utils.alert.Alert; import th.or.nectec.tanrabad.survey.utils.android.InternetConnection; import th.or.nectec.tanrabad.survey.utils.android.ResourceUtils; import th.or.nectec.tanrabad.survey.utils.android.SoftKeyboard; import th.or.nectec.tanrabad.survey.utils.android.TwiceBackPressed; import th.or.nectec.tanrabad.survey.validator.SavePlaceValidator; import th.or.nectec.tanrabad.survey.validator.UpdatePlaceValidator; import th.or.nectec.tanrabad.survey.validator.ValidatorException; import th.or.nectec.thai.widget.address.AddressPicker; import th.or.nectec.thai.widget.address.AddressPickerDialog; import java.util.UUID; public class PlaceFormActivity extends TanrabadActivity implements View.OnClickListener, PlaceSavePresenter, PlacePresenter { public static final String PLACE_TYPE_ID_ARG = "place_category_id_arg"; public static final String PLACE_UUID_ARG = "place_uuid_arg"; public static final int ADD_PLACE_REQ_CODE = 30000; Place place; PlaceRepository placeRepository = BrokerPlaceRepository.getInstance(); private EditText placeNameView; private AddressPicker addressSelect; private AppCompatSpinner placeTypeSelector; private View placeSubtypeLayout; private TextView placeSubtypeLabel; private AppCompatSpinner placeSubtypeSelector; private Button editLocationButton; private FrameLayout addLocationBackground; private Button addMarkerButton; private TwiceBackPressed twiceBackPressed; public static void startAdd(Activity activity, int placeTypeID) { Intent intent = new Intent(activity, PlaceFormActivity.class); intent.putExtra(PlaceFormActivity.PLACE_TYPE_ID_ARG, placeTypeID); activity.startActivityForResult(intent, ADD_PLACE_REQ_CODE); } public static void startEdit(Activity activity, Place place) { Intent intent = new Intent(activity, PlaceFormActivity.class); intent.putExtra(PlaceFormActivity.PLACE_UUID_ARG, place.getId().toString()); intent.putExtra(PlaceFormActivity.PLACE_TYPE_ID_ARG, place.getType()); activity.startActivityForResult(intent, ADD_PLACE_REQ_CODE); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_place_form); setupViews(); setupHomeButton(); setupTwiceBackPressed(); setupPreviewMap(); setupPlaceTypeSelector(); loadPlaceData(); } private void setupTwiceBackPressed() { twiceBackPressed = new TwiceBackPressed(this); } private void setupViews() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); placeNameView = (EditText) findViewById(R.id.place_name); addressSelect = (AddressPicker) findViewById(R.id.address_select); AddressPickerDialog popup = new AddressPickerDialog(this) .setProvinceRepository(new ThaiWidgetProvinceRepository()); addressSelect.setPopup(popup); placeTypeSelector = (AppCompatSpinner) findViewById(R.id.place_type_selector); placeSubtypeLayout = findViewById(R.id.place_subtype_layout); placeSubtypeLabel = (TextView) findViewById(R.id.place_subtype_label); placeSubtypeSelector = (AppCompatSpinner) findViewById(R.id.place_subtype_selector); addLocationBackground = (FrameLayout) findViewById(R.id.add_location_background); addLocationBackground.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SoftKeyboard.hideOn(PlaceFormActivity.this); } }); addMarkerButton = (Button) findViewById(R.id.add_marker); editLocationButton = (Button) findViewById(R.id.edit_location); editLocationButton.setVisibility(View.GONE); setSupportActionBar(toolbar); addMarkerButton.setOnClickListener(this); editLocationButton.setOnClickListener(this); } private void setupPreviewMap() { SupportMapFragment supportMapFragment = LiteMapFragment.newInstance(); getSupportFragmentManager().beginTransaction().replace(R.id.map_container, supportMapFragment).commit(); } private void setupPlaceTypeSelector() { final PlaceTypeForAddAdapter placeAdapter = new PlaceTypeForAddAdapter( this, AccountUtils.canAddOrEditVillage()); placeTypeSelector.setAdapter(placeAdapter); placeTypeSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { setupPlaceSubtypeSpinner(placeAdapter.getItem(i)); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); placeTypeSelector.setSelection(placeAdapter.getPlaceTypePosition(getPlaceTypeID())); } private void setupPlaceSubtypeSpinner(PlaceType selectedPlaceType) { placeSubtypeLabel.setText(String.format(getString(R.string.place_subtype_label), selectedPlaceType.getName())); PlaceSubTypeAdapter placeSubTypeAdapter = new PlaceSubTypeAdapter( PlaceFormActivity.this, selectedPlaceType.getId()); placeSubtypeSelector.setAdapter(placeSubTypeAdapter); if (placeSubTypeAdapter.getCount() > 0) { placeSubtypeLayout.setVisibility(View.VISIBLE); placeSubtypeSelector.setSelection(placeSubTypeAdapter.getPosition(place.getSubType())); } else { placeSubtypeLayout.setVisibility(View.GONE); } } private int getPlaceTypeID() { return getIntent().getIntExtra(PLACE_TYPE_ID_ARG, Place.TYPE_WORSHIP); } private void loadPlaceData() { if (TextUtils.isEmpty(getPlaceUUID())) { place = Place.withName(null); } else { PlaceController placeController = new PlaceController(placeRepository, this); placeController.showPlace(UUID.fromString(getPlaceUUID())); } } public String getPlaceUUID() { return getIntent().getStringExtra(PLACE_UUID_ARG); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.action_activity_place_form, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.save: if (TextUtils.isEmpty(getPlaceUUID())) { doSaveData(); } else { doUpdateData(); } break; } return super.onOptionsItemSelected(item); } public void doSaveData() { try { getPlaceFieldData(); PlaceSaver placeSaver = new PlaceSaver(placeRepository, new SavePlaceValidator(), this); placeSaver.save(place); } catch (ValidatorException e) { Alert.highLevel().show(e.getMessageID()); } } private void getPlaceFieldData() { place.setName(placeNameView.getText().toString().trim()); int placeTypeID = ((PlaceType) placeTypeSelector.getSelectedItem()).getId(); place.setType(placeTypeID); PlaceSubType placeSubType = ((PlaceSubType) placeSubtypeSelector.getSelectedItem()); place.setSubType(placeSubType.getId()); place.setSubdistrictCode(addressSelect.getAddress() == null ? null : addressSelect.getAddress().getCode()); place.setUpdateTimestamp(DateTime.now().toString()); place.setUpdateBy(AccountUtils.getUser().getUsername()); } public void doUpdateData() { getPlaceFieldData(); try { PlaceSaver placeSaver = new PlaceSaver(placeRepository, new UpdatePlaceValidator(), this); placeSaver.update(place); } catch (ValidatorException e) { Alert.highLevel().show(e.getMessageID()); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case MapMarkerActivity.MARK_LOCATION_REQUEST_CODE: if (resultCode == RESULT_OK) { Location placeLocation = LocationUtils.convertJsonToLocation( data.getStringExtra(MapMarkerActivity.MAP_LOCATION)); place.setLocation(placeLocation); setupPreviewMapWithPosition(placeLocation); } } } private void setupPreviewMapWithPosition(Location location) { addLocationBackground.setBackgroundColor(ResourceUtils.from(this).getColor(R.color.transparent)); addMarkerButton.setVisibility(View.GONE); editLocationButton.setVisibility(View.VISIBLE); editLocationButton.setOnClickListener(this); SupportMapFragment supportMapFragment = LiteMapFragment.newInstance(location); getSupportFragmentManager().beginTransaction().replace(R.id.map_container, supportMapFragment).commit(); } @Override public void onBackPressed() { if (twiceBackPressed.onTwiceBackPressed()) { finish(); } } public void onRootViewClick(View view) { SoftKeyboard.hideOn(this); } @Override public void displaySaveSuccess() { if (InternetConnection.isAvailable(this)) doPostData(); setResult(RESULT_OK); finish(); SurveyBuildingHistoryActivity.open(PlaceFormActivity.this, place); } private void doPostData() { PlacePostJobRunner placePostJobRunner = new PlacePostJobRunner(); placePostJobRunner.addJob(new PostDataJob<>(new DbPlaceRepository(this), new PlaceRestService())); placePostJobRunner.start(); } @Override public void displaySaveFail() { } @Override public void alertCannotSaveVillageType() { } @Override public void displayUpdateSuccess() { if (InternetConnection.isAvailable(this)) doPutData(); setResult(RESULT_OK); finish(); } private void doPutData() { PlacePostJobRunner placePostJobRunner = new PlacePostJobRunner(); placePostJobRunner.addJob(new PutDataJob<>(new DbPlaceRepository(this), new PlaceRestService())); placePostJobRunner.start(); } @Override public void displayUpdateFail() { } @Override public void displayPlace(Place place) { if (getSupportActionBar() != null) getSupportActionBar().setTitle(R.string.edit_place); this.place = place; placeNameView.setText(place.getName()); if (!TextUtils.isEmpty(place.getSubdistrictCode())) { addressSelect.setAddressCode(place.getSubdistrictCode()); } if (place.getLocation() != null) setupPreviewMapWithPosition(place.getLocation()); } @Override public void alertPlaceNotFound() { this.place = Place.withName(null); } public class PlacePostJobRunner extends AbsJobRunner { @Override protected void onJobError(Job errorJob, Exception exception) { super.onJobError(errorJob, exception); Log.e(errorJob.toString(), exception.getMessage()); } @Override protected void onJobStart(Job startingJob) { } @Override protected void onRunFinish() { if (errorJobs() == 0) { Alert.mediumLevel().show(R.string.upload_data_success); } else { Alert.mediumLevel().show(R.string.upload_data_failure); } } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.add_marker: MapMarkerActivity.startAdd(PlaceFormActivity.this); break; case R.id.edit_location: MapMarkerActivity.startEdit(PlaceFormActivity.this, place.getLocation()); break; } } }
app/src/main/java/th/or/nectec/tanrabad/survey/presenter/PlaceFormActivity.java
/* * Copyright (c) 2016 NECTEC * National Electronics and Computer Technology Center, Thailand * * 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. */ package th.or.nectec.tanrabad.survey.presenter; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.AppCompatSpinner; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.*; import com.google.android.gms.maps.SupportMapFragment; import org.joda.time.DateTime; import th.or.nectec.tanrabad.domain.place.*; import th.or.nectec.tanrabad.entity.Place; import th.or.nectec.tanrabad.entity.field.Location; import th.or.nectec.tanrabad.entity.lookup.PlaceSubType; import th.or.nectec.tanrabad.entity.lookup.PlaceType; import th.or.nectec.tanrabad.survey.R; import th.or.nectec.tanrabad.survey.job.AbsJobRunner; import th.or.nectec.tanrabad.survey.job.Job; import th.or.nectec.tanrabad.survey.job.PostDataJob; import th.or.nectec.tanrabad.survey.job.PutDataJob; import th.or.nectec.tanrabad.survey.presenter.maps.LiteMapFragment; import th.or.nectec.tanrabad.survey.presenter.maps.LocationUtils; import th.or.nectec.tanrabad.survey.repository.BrokerPlaceRepository; import th.or.nectec.tanrabad.survey.repository.adapter.ThaiWidgetProvinceRepository; import th.or.nectec.tanrabad.survey.repository.persistence.DbPlaceRepository; import th.or.nectec.tanrabad.survey.service.PlaceRestService; import th.or.nectec.tanrabad.survey.utils.alert.Alert; import th.or.nectec.tanrabad.survey.utils.android.InternetConnection; import th.or.nectec.tanrabad.survey.utils.android.ResourceUtils; import th.or.nectec.tanrabad.survey.utils.android.SoftKeyboard; import th.or.nectec.tanrabad.survey.utils.android.TwiceBackPressed; import th.or.nectec.tanrabad.survey.validator.SavePlaceValidator; import th.or.nectec.tanrabad.survey.validator.UpdatePlaceValidator; import th.or.nectec.tanrabad.survey.validator.ValidatorException; import th.or.nectec.thai.widget.address.AddressPicker; import th.or.nectec.thai.widget.address.AddressPickerDialog; import java.util.UUID; public class PlaceFormActivity extends TanrabadActivity implements View.OnClickListener, PlaceSavePresenter, PlacePresenter { public static final String PLACE_TYPE_ID_ARG = "place_category_id_arg"; public static final String PLACE_UUID_ARG = "place_uuid_arg"; public static final int ADD_PLACE_REQ_CODE = 30000; Place place; PlaceRepository placeRepository = BrokerPlaceRepository.getInstance(); private EditText placeNameView; private AddressPicker addressSelect; private AppCompatSpinner placeTypeSelector; private View placeSubtypeLayout; private TextView placeSubtypeLabel; private AppCompatSpinner placeSubtypeSelector; private Button editLocationButton; private FrameLayout addLocationBackground; private Button addMarkerButton; private TwiceBackPressed twiceBackPressed; public static void startAdd(Activity activity, int placeTypeID) { Intent intent = new Intent(activity, PlaceFormActivity.class); intent.putExtra(PlaceFormActivity.PLACE_TYPE_ID_ARG, placeTypeID); activity.startActivityForResult(intent, ADD_PLACE_REQ_CODE); } public static void startEdit(Activity activity, Place place) { Intent intent = new Intent(activity, PlaceFormActivity.class); intent.putExtra(PlaceFormActivity.PLACE_UUID_ARG, place.getId().toString()); intent.putExtra(PlaceFormActivity.PLACE_TYPE_ID_ARG, place.getType()); activity.startActivityForResult(intent, ADD_PLACE_REQ_CODE); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_place_form); setupViews(); setupHomeButton(); setupTwiceBackPressed(); setupPreviewMap(); setupPlaceTypeSelector(); loadPlaceData(); } private void setupTwiceBackPressed() { twiceBackPressed = new TwiceBackPressed(this); } private void setupViews() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); placeNameView = (EditText) findViewById(R.id.place_name); addressSelect = (AddressPicker) findViewById(R.id.address_select); AddressPickerDialog popup = new AddressPickerDialog(this) .setProvinceRepository(new ThaiWidgetProvinceRepository()); addressSelect.setPopup(popup); placeTypeSelector = (AppCompatSpinner) findViewById(R.id.place_type_selector); placeSubtypeLayout = findViewById(R.id.place_subtype_layout); placeSubtypeLabel = (TextView) findViewById(R.id.place_subtype_label); placeSubtypeSelector = (AppCompatSpinner) findViewById(R.id.place_subtype_selector); addLocationBackground = (FrameLayout) findViewById(R.id.add_location_background); addLocationBackground.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SoftKeyboard.hideOn(PlaceFormActivity.this); } }); addMarkerButton = (Button) findViewById(R.id.add_marker); editLocationButton = (Button) findViewById(R.id.edit_location); editLocationButton.setVisibility(View.GONE); setSupportActionBar(toolbar); addMarkerButton.setOnClickListener(this); editLocationButton.setOnClickListener(this); } private void setupPreviewMap() { SupportMapFragment supportMapFragment = LiteMapFragment.newInstance(); getSupportFragmentManager().beginTransaction().replace(R.id.map_container, supportMapFragment).commit(); } private void setupPlaceTypeSelector() { final PlaceTypeForAddAdapter placeAdapter = new PlaceTypeForAddAdapter( this, !AccountUtils.canAddOrEditVillage()); placeTypeSelector.setAdapter(placeAdapter); placeTypeSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { setupPlaceSubtypeSpinner(placeAdapter.getItem(i)); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); placeTypeSelector.setSelection(placeAdapter.getPlaceTypePosition(getPlaceTypeID())); } private void setupPlaceSubtypeSpinner(PlaceType selectedPlaceType) { placeSubtypeLabel.setText(String.format(getString(R.string.place_subtype_label), selectedPlaceType.getName())); PlaceSubTypeAdapter placeSubTypeAdapter = new PlaceSubTypeAdapter( PlaceFormActivity.this, selectedPlaceType.getId()); placeSubtypeSelector.setAdapter(placeSubTypeAdapter); if (placeSubTypeAdapter.getCount() > 0) { placeSubtypeLayout.setVisibility(View.VISIBLE); placeSubtypeSelector.setSelection(placeSubTypeAdapter.getPosition(place.getSubType())); } else { placeSubtypeLayout.setVisibility(View.GONE); } } private int getPlaceTypeID() { return getIntent().getIntExtra(PLACE_TYPE_ID_ARG, Place.TYPE_WORSHIP); } private void loadPlaceData() { if (TextUtils.isEmpty(getPlaceUUID())) { place = Place.withName(null); } else { PlaceController placeController = new PlaceController(placeRepository, this); placeController.showPlace(UUID.fromString(getPlaceUUID())); } } public String getPlaceUUID() { return getIntent().getStringExtra(PLACE_UUID_ARG); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.action_activity_place_form, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.save: if (TextUtils.isEmpty(getPlaceUUID())) { doSaveData(); } else { doUpdateData(); } break; } return super.onOptionsItemSelected(item); } public void doSaveData() { try { getPlaceFieldData(); PlaceSaver placeSaver = new PlaceSaver(placeRepository, new SavePlaceValidator(), this); placeSaver.save(place); } catch (ValidatorException e) { Alert.highLevel().show(e.getMessageID()); } } private void getPlaceFieldData() { place.setName(placeNameView.getText().toString().trim()); int placeTypeID = ((PlaceType) placeTypeSelector.getSelectedItem()).getId(); place.setType(placeTypeID); PlaceSubType placeSubType = ((PlaceSubType) placeSubtypeSelector.getSelectedItem()); place.setSubType(placeSubType.getId()); place.setSubdistrictCode(addressSelect.getAddress() == null ? null : addressSelect.getAddress().getCode()); place.setUpdateTimestamp(DateTime.now().toString()); place.setUpdateBy(AccountUtils.getUser().getUsername()); } public void doUpdateData() { getPlaceFieldData(); try { PlaceSaver placeSaver = new PlaceSaver(placeRepository, new UpdatePlaceValidator(), this); placeSaver.update(place); } catch (ValidatorException e) { Alert.highLevel().show(e.getMessageID()); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case MapMarkerActivity.MARK_LOCATION_REQUEST_CODE: if (resultCode == RESULT_OK) { Location placeLocation = LocationUtils.convertJsonToLocation( data.getStringExtra(MapMarkerActivity.MAP_LOCATION)); place.setLocation(placeLocation); setupPreviewMapWithPosition(placeLocation); } } } private void setupPreviewMapWithPosition(Location location) { addLocationBackground.setBackgroundColor(ResourceUtils.from(this).getColor(R.color.transparent)); addMarkerButton.setVisibility(View.GONE); editLocationButton.setVisibility(View.VISIBLE); editLocationButton.setOnClickListener(this); SupportMapFragment supportMapFragment = LiteMapFragment.newInstance(location); getSupportFragmentManager().beginTransaction().replace(R.id.map_container, supportMapFragment).commit(); } @Override public void onBackPressed() { if (twiceBackPressed.onTwiceBackPressed()) { finish(); } } public void onRootViewClick(View view) { SoftKeyboard.hideOn(this); } @Override public void displaySaveSuccess() { if (InternetConnection.isAvailable(this)) doPostData(); setResult(RESULT_OK); finish(); SurveyBuildingHistoryActivity.open(PlaceFormActivity.this, place); } private void doPostData() { PlacePostJobRunner placePostJobRunner = new PlacePostJobRunner(); placePostJobRunner.addJob(new PostDataJob<>(new DbPlaceRepository(this), new PlaceRestService())); placePostJobRunner.start(); } @Override public void displaySaveFail() { } @Override public void alertCannotSaveVillageType() { } @Override public void displayUpdateSuccess() { if (InternetConnection.isAvailable(this)) doPutData(); setResult(RESULT_OK); finish(); } private void doPutData() { PlacePostJobRunner placePostJobRunner = new PlacePostJobRunner(); placePostJobRunner.addJob(new PutDataJob<>(new DbPlaceRepository(this), new PlaceRestService())); placePostJobRunner.start(); } @Override public void displayUpdateFail() { } @Override public void displayPlace(Place place) { if (getSupportActionBar() != null) getSupportActionBar().setTitle(R.string.edit_place); this.place = place; placeNameView.setText(place.getName()); if (!TextUtils.isEmpty(place.getSubdistrictCode())) { addressSelect.setAddressCode(place.getSubdistrictCode()); } if (place.getLocation() != null) setupPreviewMapWithPosition(place.getLocation()); } @Override public void alertPlaceNotFound() { this.place = Place.withName(null); } public class PlacePostJobRunner extends AbsJobRunner { @Override protected void onJobError(Job errorJob, Exception exception) { super.onJobError(errorJob, exception); Log.e(errorJob.toString(), exception.getMessage()); } @Override protected void onJobStart(Job startingJob) { } @Override protected void onRunFinish() { if (errorJobs() == 0) { Alert.mediumLevel().show(R.string.upload_data_success); } else { Alert.mediumLevel().show(R.string.upload_data_failure); } } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.add_marker: MapMarkerActivity.startAdd(PlaceFormActivity.this); break; case R.id.edit_location: MapMarkerActivity.startEdit(PlaceFormActivity.this, place.getLocation()); break; } } }
แก้บัคเพิ่มหรือแก้ไขชุมชนไม่ได้ ในกรณีที่หน่วยงานดังกล่าวสามารถเพิ่มชุมชนได้
app/src/main/java/th/or/nectec/tanrabad/survey/presenter/PlaceFormActivity.java
แก้บัคเพิ่มหรือแก้ไขชุมชนไม่ได้ ในกรณีที่หน่วยงานดังกล่าวสามารถเพิ่มชุมชนได้
<ide><path>pp/src/main/java/th/or/nectec/tanrabad/survey/presenter/PlaceFormActivity.java <ide> <ide> private void setupPlaceTypeSelector() { <ide> final PlaceTypeForAddAdapter placeAdapter = new PlaceTypeForAddAdapter( <del> this, !AccountUtils.canAddOrEditVillage()); <add> this, AccountUtils.canAddOrEditVillage()); <ide> placeTypeSelector.setAdapter(placeAdapter); <ide> placeTypeSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { <ide> @Override
Java
mit
ea2750ec4247d02edc707967d06e1e1e70f52ae3
0
joan-domingo/Podcasts-RAC1-Android
package cat.xojan.random1.presenter; import android.app.DownloadManager; import android.content.Context; import android.net.Uri; import android.os.Environment; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import cat.xojan.random1.commons.ErrorUtil; import cat.xojan.random1.domain.interactor.PodcastDataInteractor; import cat.xojan.random1.domain.model.Podcast; import cat.xojan.random1.ui.BasePresenter; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class PodcastListPresenter implements BasePresenter { private final DownloadManager mDownloadManager; public interface PodcastsListener { /** update podcast list*/ void updateRecyclerView(List<Podcast> podcasts); /** update podcasts with downloaded*/ void updateRecyclerViewWithDownloaded(List<Podcast> podcasts); /** refresh recycler view*/ void updateRecyclerView(); } private final PodcastDataInteractor mPodcastDataInteractor; private final Context mContext; private Subscription mPodcastSubscription; private PodcastsListener mListener; private Subscription mSubscription; @Inject public PodcastListPresenter(PodcastDataInteractor podcastDataInteractor, Context context, DownloadManager downloadManager) { mPodcastDataInteractor = podcastDataInteractor; mContext = context; mDownloadManager = downloadManager; } public void setPodcastsListener(PodcastsListener listener) { mListener = listener; } public void loadPodcasts(String program, List<Podcast> loadedPodcasts) { if (loadedPodcasts == null) { if (program == null) { mPodcastSubscription = mPodcastDataInteractor.loadPodcasts() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new PodcastSubscriptionObserver()); } else { mPodcastSubscription = mPodcastDataInteractor.loadPodcastsByProgram(program) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new PodcastSubscriptionObserver()); } } else { mListener.updateRecyclerView(loadedPodcasts); } } public void refreshDownloadedPodcasts() { mPodcastDataInteractor.refreshDownloadedPodcasts(); } public void download(Podcast podcast) { Uri uri = Uri.parse(podcast.getFileUrl()); DownloadManager.Request request = new DownloadManager.Request(uri) .setTitle(podcast.getCategory()) .setDescription(podcast.getDescription()) .setDestinationInExternalFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS, podcast.getCategory() + PodcastDataInteractor.SEPARATOR + podcast.getDescription() + PodcastDataInteractor.EXTENSION) .setVisibleInDownloadsUi(true); mDownloadManager.enqueue(request); podcast.setState(Podcast.State.DOWNLOADING); mListener.updateRecyclerView(); } @Override public void resume() { mSubscription = mPodcastDataInteractor.getDownloadedPodcasts() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.newThread()) .subscribe(new Subscriber<List<Podcast>>() { @Override public void onCompleted() { // Ignore } @Override public void onError(Throwable e) { ErrorUtil.logException(e); } @Override public void onNext(List<Podcast> podcasts) { mListener.updateRecyclerViewWithDownloaded(podcasts); } }); } @Override public void pause() { } @Override public void destroy() { if (mPodcastSubscription != null && !mPodcastSubscription.isUnsubscribed()) { mPodcastSubscription.unsubscribe(); } if (mSubscription != null && !mSubscription.isUnsubscribed()) { mSubscription.unsubscribe(); } mListener = null; } public void deletePodcast(Podcast podcast) { mPodcastDataInteractor.deleteDownload(podcast); } private class PodcastSubscriptionObserver extends Subscriber<List<Podcast>> { @Override public void onCompleted() { // Ignore } @Override public void onError(Throwable e) { ErrorUtil.logException(e); mListener.updateRecyclerView(new ArrayList<Podcast>()); } @Override public void onNext(List<Podcast> podcasts) { mListener.updateRecyclerView(podcasts); } } }
app/src/main/java/cat/xojan/random1/presenter/PodcastListPresenter.java
package cat.xojan.random1.presenter; import android.app.DownloadManager; import android.content.Context; import android.net.Uri; import android.os.Environment; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import cat.xojan.random1.commons.ErrorUtil; import cat.xojan.random1.domain.interactor.PodcastDataInteractor; import cat.xojan.random1.domain.model.Podcast; import cat.xojan.random1.ui.BasePresenter; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class PodcastListPresenter implements BasePresenter { private final DownloadManager mDownloadManager; public interface PodcastsListener { /** update podcast list*/ void updateRecyclerView(List<Podcast> podcasts); /** update podcasts with downloaded*/ void updateRecyclerViewWithDownloaded(List<Podcast> podcasts); /** refresh recycler view*/ void updateRecyclerView(); } private final PodcastDataInteractor mPodcastDataInteractor; private final Context mContext; private Subscription mPodcastSubscription; private PodcastsListener mListener; private Subscription mSubscription; @Inject public PodcastListPresenter(PodcastDataInteractor podcastDataInteractor, Context context, DownloadManager downloadManager) { mPodcastDataInteractor = podcastDataInteractor; mContext = context; mDownloadManager = downloadManager; } public void setPodcastsListener(PodcastsListener listener) { mListener = listener; mSubscription = mPodcastDataInteractor.getDownloadedPodcasts() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.newThread()) .subscribe(new Subscriber<List<Podcast>>() { @Override public void onCompleted() { // Ignore } @Override public void onError(Throwable e) { ErrorUtil.logException(e); } @Override public void onNext(List<Podcast> podcasts) { mListener.updateRecyclerViewWithDownloaded(podcasts); } }); } public void loadPodcasts(String program, List<Podcast> loadedPodcasts) { if (loadedPodcasts == null) { if (program == null) { mPodcastSubscription = mPodcastDataInteractor.loadPodcasts() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new PodcastSubscriptionObserver()); } else { mPodcastSubscription = mPodcastDataInteractor.loadPodcastsByProgram(program) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new PodcastSubscriptionObserver()); } } else { mListener.updateRecyclerView(loadedPodcasts); } } public void refreshDownloadedPodcasts() { mPodcastDataInteractor.refreshDownloadedPodcasts(); } public void download(Podcast podcast) { Uri uri = Uri.parse(podcast.getFileUrl()); DownloadManager.Request request = new DownloadManager.Request(uri) .setTitle(podcast.getCategory()) .setDescription(podcast.getDescription()) .setDestinationInExternalFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS, podcast.getCategory() + PodcastDataInteractor.SEPARATOR + podcast.getDescription() + PodcastDataInteractor.EXTENSION) .setVisibleInDownloadsUi(true); mDownloadManager.enqueue(request); podcast.setState(Podcast.State.DOWNLOADING); mListener.updateRecyclerView(); } @Override public void resume() { } @Override public void pause() { } @Override public void destroy() { if (mPodcastSubscription != null && !mPodcastSubscription.isUnsubscribed()) { mPodcastSubscription.unsubscribe(); } if (mSubscription != null && !mSubscription.isUnsubscribed()) { mSubscription.unsubscribe(); } mListener = null; } public void deletePodcast(Podcast podcast) { mPodcastDataInteractor.deleteDownload(podcast); } private class PodcastSubscriptionObserver extends Subscriber<List<Podcast>> { @Override public void onCompleted() { // Ignore } @Override public void onError(Throwable e) { ErrorUtil.logException(e); mListener.updateRecyclerView(new ArrayList<Podcast>()); } @Override public void onNext(List<Podcast> podcasts) { mListener.updateRecyclerView(podcasts); } } }
fix issue #61
app/src/main/java/cat/xojan/random1/presenter/PodcastListPresenter.java
fix issue #61
<ide><path>pp/src/main/java/cat/xojan/random1/presenter/PodcastListPresenter.java <ide> <ide> public void setPodcastsListener(PodcastsListener listener) { <ide> mListener = listener; <del> mSubscription = mPodcastDataInteractor.getDownloadedPodcasts() <del> .observeOn(AndroidSchedulers.mainThread()) <del> .subscribeOn(Schedulers.newThread()) <del> .subscribe(new Subscriber<List<Podcast>>() { <del> @Override <del> public void onCompleted() { <del> // Ignore <del> } <del> <del> @Override <del> public void onError(Throwable e) { <del> ErrorUtil.logException(e); <del> } <del> <del> @Override <del> public void onNext(List<Podcast> podcasts) { <del> mListener.updateRecyclerViewWithDownloaded(podcasts); <del> } <del> }); <ide> } <ide> <ide> public void loadPodcasts(String program, List<Podcast> loadedPodcasts) { <ide> <ide> @Override <ide> public void resume() { <add> mSubscription = mPodcastDataInteractor.getDownloadedPodcasts() <add> .observeOn(AndroidSchedulers.mainThread()) <add> .subscribeOn(Schedulers.newThread()) <add> .subscribe(new Subscriber<List<Podcast>>() { <add> @Override <add> public void onCompleted() { <add> // Ignore <add> } <ide> <add> @Override <add> public void onError(Throwable e) { <add> ErrorUtil.logException(e); <add> } <add> <add> @Override <add> public void onNext(List<Podcast> podcasts) { <add> mListener.updateRecyclerViewWithDownloaded(podcasts); <add> } <add> }); <ide> } <ide> <ide> @Override
JavaScript
mit
21b674530ba4c0cd6d72e993d4a57882aa89ef8b
0
johnbabb/backbone-sandbox
<!-- saved from url=(0048)file:///C:/Users/jxb15/Desktop/Scratch/gist.html --> <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> </head> <body> <script type="text/javascript"> $(function(){ var App = { // defining app name space, You can rename it as per your project name.. Models: {}, Collections: {}, Views: {} }; App.Models.Person = Backbone.Model.extend({}); var person = new App.Models.Person({name:"Taroon Tyagi", age: 26, occupation: "Graphics Designer"}); console.log(person); }); </script> </body> momma! </html>
gits-one.js
<!-- saved from url=(0048)file:///C:/Users/jxb15/Desktop/Scratch/gist.html --> <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> </head> <body> <script type="text/javascript"> $(function(){ var App = { // defining app name space, You can rename it as per your project name.. Models: {}, Collections: {}, Views: {} }; App.Models.Person = Backbone.Model.extend({}); var person = new App.Models.Person({name:"Taroon Tyagi", age: 26, occupation: "Graphics Designer"}); console.log(person); }); </script> </body> </html>
auth me
gits-one.js
auth me
<ide><path>its-one.js <ide> }); <ide> </script> <ide> </body> <add> momma! <ide> </html>
Java
mit
ea7b44a67d5fd41dad056c39bf0b20205e249a5c
0
Jullekungfu/SpaceDefence
package slimpleslickgame; import org.newdawn.slick.Color; import org.newdawn.slick.Graphics; import org.newdawn.slick.ShapeFill; import org.newdawn.slick.fills.GradientFill; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.geom.Shape; import org.newdawn.slick.geom.Vector2f; public class Creep { private int hp; private Vector2f position; private Vector2f direction; private Shape shape; private ShapeFill shapeFill; private float speed = 50; private boolean isDestroyed; private int value = 10; protected final float WIDTH = 20; protected final float HEIGHT = 20; public Creep(Vector2f initPos, Color color){ hp = 100; shape = new Rectangle(0, 0, WIDTH, HEIGHT); shapeFill = new GradientFill(0,0, color, 20, 20, color, true); position = initPos; direction = new Vector2f(0, 0.01f*speed); shape.setLocation(position); isDestroyed = false; } public void onHit(){ hp -= 10; } public void update(int delta){ position.add(direction); shape.setLocation(position); } public void destroy(){ this.isDestroyed = true; this.direction = new Vector2f(0, 0); } public boolean isAlive(){ return !isDestroyed; } public void render(Graphics graphics){ if(hp > 0 && !isDestroyed){ // graphics.fill(shape, shapeFill); graphics.draw(shape, shapeFill); } } public Vector2f getPosition(){ return position; } public Shape getShape() { return shape; } public int getScoreValue(){ return value; } }
slick-game/src/slimpleslickgame/Creep.java
package slimpleslickgame; import org.newdawn.slick.Color; import org.newdawn.slick.Graphics; import org.newdawn.slick.ShapeFill; import org.newdawn.slick.fills.GradientFill; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.geom.Shape; import org.newdawn.slick.geom.Vector2f; public class Creep { private int hp; private Vector2f position; private Vector2f direction; private Shape shape; private ShapeFill shapeFill; private float speed = 50; private boolean isDestroyed; private int value = 10; protected final float WIDTH = 20; protected final float HEIGHT = 20; public Creep(Vector2f initPos, Color color){ hp = 100; shape = new Rectangle(0, 0, WIDTH, HEIGHT); shapeFill = new GradientFill(0,0, color, 20, 20, color, true); position = initPos; direction = new Vector2f(0, 0.01f*speed); shape.setLocation(position); isDestroyed = false; } public void onHit(){ hp -= 10; } public void update(int delta){ position.add(direction); shape.setLocation(position); } public void destroy(){ this.isDestroyed = true; this.direction = new Vector2f(0, 0); } public boolean isAlive(){ return !isDestroyed; } public void render(Graphics graphics){ if(hp > 0 && !isDestroyed){ graphics.fill(shape, shapeFill); } } public Vector2f getPosition(){ return position; } public Shape getShape() { return shape; } public int getScoreValue(){ return value; } }
render creeps
slick-game/src/slimpleslickgame/Creep.java
render creeps
<ide><path>lick-game/src/slimpleslickgame/Creep.java <ide> <ide> public void render(Graphics graphics){ <ide> if(hp > 0 && !isDestroyed){ <del> graphics.fill(shape, shapeFill); <add>// graphics.fill(shape, shapeFill); <add> graphics.draw(shape, shapeFill); <ide> } <ide> } <ide>
JavaScript
mit
004707dfe73094ce7803a90e6e5829b9e320d5db
0
igemsoftware/SYSU-Software2013,igemsoftware/SYSU-Software2013,igemsoftware/SYSU-Software2013,igemsoftware/SYSU-Software2013,igemsoftware/SYSU-Software2013,igemsoftware/SYSU-Software2013
/** * * File: graphiti.js * Author: Rathinho * Description: Initialization of graphiti * **/ // Create namespace var g = {}; g.Application = Class.extend({ NAME: "graphiti.Application", /** * @constructor * * @param {String} canvasId the id of the DOM element to use as paint container */ init: function() { this.view = new g.View("canvas"); }, undo: function() { this.view.getCommandStack().undo(); }, redo: function() { this.view.getCommandStack().redo(); }, zoom: function(x, y, zoomFactor) { this.view.setZoom(this.view.getZoom() * zoomFactor); }, zoomReset: function() { this.view.setZoom(1.0); }, toggleSnapToGrid: function() { this.view.setSnapToGrid(!this.view.getSnapToGrid()); } }); g.View = graphiti.Canvas.extend({ init: function(id) { this._super(id); this.setScrollArea("#" + id); this.currentDropConnection = null; this.setSnapToGrid(true); this.collection = new Array(); // Store all components in this view this.connections = new Array(); // Store all connections in this view this.boundPairs = new Array(); // Store all bounds of proteins this.currentSelected = null; // Store the figure that is currently seleted this.collection.counter = 0; }, /** * @method * Called if the DragDrop object is moving around.<br> * <br> * Graphiti use the jQuery draggable/droppable lib. Please inspect * http://jqueryui.com/demos/droppable/ for further information. * * @param {HTMLElement} droppedDomNode The dragged DOM element. * @param {Number} x the x coordinate of the drag * @param {Number} y the y coordinate of the drag * * @template **/ onDrag: function(droppedDomNode, x, y) {}, /** * @method * Called if the user drop the droppedDomNode onto the canvas.<br> * <br> * Graphiti use the jQuery draggable/droppable lib. Please inspect * http://jqueryui.com/demos/droppable/ for further information. * * @param {HTMLElement} droppedDomNode The dropped DOM element. * @param {Number} x the x coordinate of the drop * @param {Number} y the y coordinate of the drop * @private **/ onDrop: function(droppedDomNode, x, y) { var type = $(droppedDomNode).data("shape"); var figure = eval("new " + type + "();"); // create a command for the undo/redo support var command = new graphiti.command.CommandAdd(this, figure, x, y); this.getCommandStack().execute(command); }, onMouseDown: function( /* :int */ x, /* :int */ y) { var canDragStart = true; var figure = this.getBestFigure(x, y); // check if the user click on a child shape. DragDrop and movement must redirect // to the parent // Exception: Port's if ((figure !== null && figure.getParent() !== null) && !(figure instanceof graphiti.Port)) { figure = figure.getParent(); } if (figure !== null && figure.isDraggable()) { canDragStart = figure.onDragStart(x - figure.getAbsoluteX(), y - figure.getAbsoluteY()); // Element send a veto about the drag&drop operation if (canDragStart === false) { this.mouseDraggingElement = null; this.mouseDownElement = figure; } else { this.mouseDraggingElement = figure; this.mouseDownElement = figure; } } if (figure !== this.currentSelection && figure !== null && figure.isSelectable() === true) { this.hideResizeHandles(); this.setCurrentSelection(figure); // its a line if (figure instanceof graphiti.shape.basic.Line) { // you can move a line with Drag&Drop...but not a connection. // A Connection is fixed linked with the corresponding ports. // if (!(figure instanceof graphiti.Connection)) { this.draggingLineCommand = figure.createCommand(new graphiti.command.CommandType(graphiti.command.CommandType.MOVE)); if (this.draggingLineCommand !== null) { this.draggingLine = figure; } } } else if (canDragStart === false) { this.setCurrentSelection(null); } } else if (figure === null) { this.setCurrentSelection(null); } if (figure == null) { g.hideAllToolbar(); } } }); // Creates shapes g.Shapes = {}; // shape container g.Shapes.Container = graphiti.shape.basic.Rectangle.extend({ NAME: "g.Shapes.Container", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } this.TYPE = "Container"; this.count = 0; this.boundElements = new Array(); this.setAlpha(0.1); // Buttons this.remove = new g.Buttons.Remove(); this.Activate = new g.Buttons.Activate(); this.Inhibit = new g.Buttons.Inhibit(); this.CoExpress = new g.Buttons.CoExpress(); // this.addFigure(new g.Shapes.Protein(), new graphiti.layout.locator.LeftLocator(this)); }, onClick: function(x, y) { var figure = this.getBestFigure(x, y); // console.log(figure); if (figure !== null) figure.onClick(x, y); }, onDoubleClick: function() { g.closeToolbar(this); }, resetChildren: function() { var that = this; this.children.each(function(i, e) { if (!e.figure.TYPE) { e.figure.setCanvas(null); that.children.remove(e.figure); } }); this.repaint(); }, getBestFigure: function(x, y, ignoreType) { var result = null; for (var i = 0; i < this.getChildren().getSize(); i++) { var figure = this.getChildren().get(i); if (figure.hitTest(x, y) == true && figure.TYPE !== ignoreType) { if (result === null) { result = figure; } else if (result.getZOrder() < figure.getZOrder()) { result = figure; } } }; if (result !== null) return result; } // onMouseDown : function(/* :int */x, /* :int */y) }); // Protein component g.Shapes.Protein = graphiti.shape.icon.ProteinIcon.extend({ NAME: "g.Shapes.Protein", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } this.setColor("#339BB9"); this.TYPE = "Protein"; // Buttons this.remove = new g.Buttons.Remove(); this.Activate = new g.Buttons.Activate(); this.Inhibit = new g.Buttons.Inhibit(); this.CoExpress = new g.Buttons.CoExpress(); // Label // this.label = new graphiti.shape.basic.Label("PCS"); // this.label.setFontColor("#000000"); }, onClick: function() { g.toolbar(this); }, onDoubleClick: function() { g.closeToolbar(this); } }); // Inducer component g.Shapes.Inducer = graphiti.shape.icon.InducerIcon.extend({ NAME: "g.Shapes.Inducer", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } // this.setColor("#339BB9"); this.TYPE = "Inducer"; // Buttons this.remove = new g.Buttons.Remove(); this.Activate = new g.Buttons.Activate(); this.Inhibit = new g.Buttons.Inhibit(); this.CoExpress = new g.Buttons.CoExpress(); // Label this.label = new graphiti.shape.basic.Label("Inducer"); this.label.setFontColor("#000000"); }, onClick: function() { g.toolbar(this); }, onDoubleClick: function() { g.closeToolbar(this); } }); // Metal-Ion component g.Shapes.MetalIon = graphiti.shape.icon.MetalIonIcon.extend({ NAME: "g.Shapes.MetalIon", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } this.setColor("#339BB9"); this.TYPE = "MetalIon"; // Buttons this.remove = new g.Buttons.Remove(); this.Activate = new g.Buttons.Activate(); this.Inhibit = new g.Buttons.Inhibit(); this.CoExpress = new g.Buttons.CoExpress(); // Label this.label = new graphiti.shape.basic.Label("Metal ion"); this.label.setFontColor("#000000"); }, onClick: function() { g.toolbar(this); }, onDoubleClick: function() { g.closeToolbar(this); } }); // Temperature component g.Shapes.Temperature = graphiti.shape.icon.TemperatureIcon.extend({ NAME: "g.Shapes.Temperature", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } this.setColor("#339BB9"); this.TYPE = "Temperature"; // Buttons this.remove = new g.Buttons.Remove(); this.Activate = new g.Buttons.Activate(); this.Inhibit = new g.Buttons.Inhibit(); this.CoExpress = new g.Buttons.CoExpress(); // Label this.label = new graphiti.shape.basic.Label("Temperature"); this.label.setFontColor("#000000"); }, onClick: function() { g.toolbar(this); }, onDoubleClick: function() { g.closeToolbar(this); } }); // R/A component g.Shapes.RORA = graphiti.shape.icon.RORAIcon.extend({ NAME: "g.Shapes.RORA", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } this.setColor("#339BB9"); this.TYPE = "RORA"; // Buttons this.remove = new g.Buttons.Remove(); this.Activate = new g.Buttons.Activate(); this.Inhibit = new g.Buttons.Inhibit(); this.CoExpress = new g.Buttons.CoExpress(); // Label this.label = new graphiti.shape.basic.Label("A/R"); this.label.setFontColor("#000000"); }, onClick: function() { g.toolbar(this); }, onDoubleClick: function() { if (this.remove || this.label) { this.resetChildren(); } } }); // R g.Shapes.R = graphiti.shape.icon.R.extend({ NAME: "g.Shapes.R", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } this.TYPE = "R"; } }); // A g.Shapes.A = graphiti.shape.icon.A.extend({ NAME: "g.Shapes.A", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } this.TYPE = "A"; } }); // Buttons g.Buttons = {}; // Remove Button g.Buttons.Remove = graphiti.shape.icon.Remove.extend({ NAME: "g.Buttons.Remove", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(20, 20); } }, onClick: function() { var parent = this.getParent(), connections = parent.getConnections(); for (var i = 0; i < connections.size; i++) { app.view.connections.remove(connections.get(i).getId()); } var command = new graphiti.command.CommandDelete(parent); // 删除父节点 app.view.getCommandStack().execute(command); // 添加到命令栈中 } }); // Activate Button g.Buttons.Activate = graphiti.shape.icon.Activate.extend({ NAME: "g.Buttons.Activate", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(20, 20); } }, onClick: function() { var canvas = this.getCanvas(); var source = this.getParent(); console.log(source.getPorts()); console.log(source.getConnections()); if (canvas.getFigure(app.view.currentSelected).TYPE == "Protein" || canvas.getFigure(app.view.currentSelected).TYPE == "Container") { g.bind(canvas.getFigure(app.view.currentSelected), null, "A"); var target = g.cache; g.connect(source, target, "A"); // var sourcePort = source.createPort("hybrid", new graphiti.layout.locator.BottomLocator(source)); // var targetPort = target.createPort("hybrid", new graphiti.layout.locator.BottomRightLocator(target)); // var command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.ArrowDecorator(), "Activate"); // 连接两点 // app.view.getCommandStack().execute(command); // 添加到命令栈中 // app.view.connections.push(command.connection.getId()); // 添加connection的id到connections集合中 } else if (canvas.getFigure(app.view.currentSelected).TYPE == "RORA") { var target = canvas.getFigure(app.view.currentSelected); var sourcePort = source.createPort("hybrid", new graphiti.layout.locator.BottomLocator(source)); var targetPort = target.createPort("hybrid", new graphiti.layout.locator.BottomLocator(target)); var command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.ArrowDecorator(), "Activate"); // 连接两点 app.view.getCommandStack().execute(command); // 添加到命令栈中 app.view.connections.push(command.connection.getId()); // 添加connection的id到connections集合中 } else if (canvas.getFigure(app.view.currentSelected).TYPE == "Inducer") { var target = canvas.getFigure(app.view.currentSelected); // var sourcePort = source.createPort("hybrid", new graphiti.layout.locator.BottomLocator(source)); var targetPort = target.createPort("hybrid", new graphiti.layout.locator.BottomLocator(target)); var sourcePort = new graphiti.HybridPort(); sourcePort.decorator = "A"; source.addFigure(sourcePort, new graphiti.layout.locator.ManhattanMidpointLocator(source)); var command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.ArrowDecorator(), "Activate"); app.view.getCommandStack().execute(command); // 添加到命令栈中 app.view.connections.push(command.connection.getId()); // 添加connection的id到connections集合中 } } }); // Inhibit Button g.Buttons.Inhibit = graphiti.shape.icon.Inhibit.extend({ NAME: "g.Buttons.Inhibit", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(20, 20); } }, onClick: function() { var canvas = this.getCanvas(); var source = this.getParent(); if (canvas.getFigure(app.view.currentSelected).TYPE == "Protein" || canvas.getFigure(app.view.currentSelected).TYPE == "Container") { g.bind(canvas.getFigure(app.view.currentSelected), null, "R"); var target = g.cache; g.connect(source, target, "R"); // var sourcePort = source.createPort("hybrid", new graphiti.layout.locator.BottomLocator(source)); // var targetPort = target.createPort("hybrid", new graphiti.layout.locator.BottomRightLocator(target)); // // new graphiti.decoration.connection.ArrowDecorator() // var command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.TDecorator(), "Inhibit"); // 连接两点 // app.view.getCommandStack().execute(command); // 添加到命令栈中 // app.view.connections.push(command.connection.getId()); // 添加connection的id到connections集合中 } else if (canvas.getFigure(app.view.currentSelected).TYPE == "RORA") { var target = canvas.getFigure(app.view.currentSelected); var sourcePort = source.createPort("hybrid", new graphiti.layout.locator.BottomLocator(source)); var targetPort = target.createPort("hybrid", new graphiti.layout.locator.BottomLocator(target)); var command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.TDecorator(), "Inhibit"); // 连接两点 app.view.getCommandStack().execute(command); // 添加到命令栈中 app.view.connections.push(command.connection.getId()); // 添加connection的id到connections集合中 } else if (canvas.getFigure(app.view.currentSelected).TYPE == "Inducer") { var target = canvas.getFigure(app.view.currentSelected); // var sourcePort = source.createPort("hybrid", new graphiti.layout.locator.BottomLocator(source)); var targetPort = target.createPort("hybrid", new graphiti.layout.locator.BottomLocator(target)); var sourcePort = new graphiti.HybridPort(); sourcePort.decorator = "T"; source.addFigure(sourcePort, new graphiti.layout.locator.ManhattanMidpointLocator(source)); var command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.TDecorator(), "Inhibit"); app.view.getCommandStack().execute(command); // 添加到命令栈中 app.view.connections.push(command.connection.getId()); // 添加connection的id到connections集合中 } } }); // Co-Expression Button g.Buttons.CoExpress = graphiti.shape.icon.CoExpress.extend({ NAME: "g.Buttons.CoExpress", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(20, 20); } }, onClick: function() { var target = this.getParent(); var source = this.getCanvas().getFigure(app.view.currentSelected); if (source.TYPE == "Protein" || source.TYPE == "Container") { g.bind(source, target, "Protein"); } else if (source.TYPE == "RORA") { g.bind(source, target, "RORA"); } } }); g.Buttons.Unbind = graphiti.shape.icon.CoExpress.extend({ NAME: "g.Buttons.Unbind", init: function(width, height) { this._super(); this.from = null; this.to = null; if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(30, 20); } }, setAttr: function(from, to) { if (from !== null) this.from = from; if (to !== null) this.to = to; }, onClick: function() { g.unbind(this.from, this.to); } }); // functions /* * 两个元素的绑定 */ (function(ex) { ex.bind = function(source, target, type) { var srcPosX = source.getX(), srcPosY = source.getY(); var canvas = source.getCanvas(); var container = null, outerContainer = null; if (source.getParent() && source.getParent().TYPE === "Container") { console.log("has container"); container = source.getParent(); //内容器 outerContainer = container.getParent(); //外容器 } else { console.log("new container"); outerContainer = new g.Shapes.Container(); //外容器 var command = new graphiti.command.CommandAdd(app.view, outerContainer, srcPosX, srcPosY); app.view.getCommandStack().execute(command); app.view.collection.push(outerContainer.getId()); container = new g.Shapes.Container(); //内容器 // app.view.collection.push(container.getId()); container.addFigure(source, new graphiti.layout.locator.ContainerLocator(container, container.count, 100)); source.resetChildren(); container.count += 1; container.locator = new graphiti.layout.locator.ContainerLocator(outerContainer, outerContainer.count, 100); outerContainer.addFigure(container, container.locator); outerContainer.count += 1; } if (type == "Protein") { // 创建新的子容器 var newContainer = new g.Shapes.Container(); newContainer.addFigure(target, new graphiti.layout.locator.ContainerLocator(newContainer, newContainer.count, 100)); newContainer.count += 1; newContainer.locator = new graphiti.layout.locator.ContainerLocator(outerContainer, outerContainer.count, 100); // 添加到外容器中 outerContainer.addFigure(newContainer, newContainer.locator); outerContainer.count += 1; var unbinder = new g.Buttons.Unbind(); unbinder.setAttr(container, newContainer); unbinder.locator = new graphiti.layout.locator.UnbindLocator(outerContainer, outerContainer.count - 1, 100); outerContainer.addFigure(unbinder, unbinder.locator); // 向蛋白绑定信息数组插入记录 app.view.boundPairs.push({ from: source.getId(), to: target.getId(), type: "Bound", inducer: "none" }); app.view.boundPairs.push({from: source.getId(), to: target.getId(), type: "Bound", inducer: "none"}); // 更新外容器状态 updateOuterContainer(); target.resetChildren(); } else if (type == "R") { var has = false; for (var i = 0; i < container.getChildren().size; i++) { var figure = container.getChildren().get(i); if (figure.TYPE == "R") { has = true; break; } } if (!has) { container.setDimension(container.count * 100 + 100, 100); container.addFigure(new g.Shapes.R(), new graphiti.layout.locator.ContainerLocator(container, container.count, 100)); container.count += 1; updateOuterContainer(); } } else if (type == "A") { var has = false; for (var i = 0; i < container.getChildren().size; i++) { var figure = container.getChildren().get(i); if (figure.TYPE == "A") { has = true; break; } } if (!has) { container.setDimension(container.count * 100 + 100, 100); container.addFigure(new g.Shapes.A(), new graphiti.layout.locator.ContainerLocator(container, container.count, 100)); container.count += 1; updateOuterContainer(); } } // 计算并设置外容器宽度 g.cache = container; g.hideAllToolbar(); // 更新外层容器的大小和内部的元素次序 function updateOuterContainer() { var children = outerContainer.getChildren(); var len = children.getSize(); var count = 0; for (var i = 0; i < len; i++) { var innerContainer = children.get(i); if (innerContainer.TYPE == "Container") { innerContainer.locator.no = count; innerContainer.locator.relocate(i, innerContainer); count += innerContainer.count; // console.log(innerContainer.count); } } console.log(children); outerContainer.setDimension(count * 100, 100); } }; })(g); /* * 元素的解绑定 */ (function(ex) { ex.unbind = function(from, to) { alert("haha"); }; })(g); /* * 在生物元件上方显示操作按钮组 */ (function(ex) { ex.toolbar = function(ctx) { // Dom operation $("#right-container").css({ right: '0px' }); var hasClassIn = $("#collapseTwo").hasClass('in'); if (!hasClassIn) { $("#collapseOne").toggleClass('in'); $("#collapseOne").css({ height: '0' }); $("#collapseTwo").toggleClass('in'); $("#collapseTwo").css({ height: "auto" }); } $("#exogenous-factors-config").css({ "display": "none" }); $("#protein-config").css({ "display": "none" }); $("#component-config").css({ "display": "none" }); $("#arrow-config").css({ "display": "none" }); // set current selected figure app.view.currentSelected = ctx.getId(); // remove all children nodes if (ctx.remove || ctx.label) { ctx.resetChildren(); } // add remove button and label ctx.addFigure(ctx.remove, new graphiti.layout.locator.TopLocator(ctx)); // ctx.addFigure(ctx.label, new graphiti.layout.locator.BottomLocator(ctx)); // get this canvas var canvas = ctx.getCanvas(); // different opearation for different types of components if (ctx.TYPE == "Protein") { for (var i = 0; i < canvas.collection.length; i++) { var figure = canvas.getFigure(canvas.collection[i]); if (figure !== null && ctx.getId() !== figure.getId() && (figure.TYPE == "Protein") && !figure.getParent() && figure.getConnections().getSize() == 0) { figure.resetChildren(); figure.addFigure(figure.Activate, new graphiti.layout.locator.TopLeftLocator(figure)); figure.addFigure(figure.Inhibit, new graphiti.layout.locator.TopLocator(figure)); figure.addFigure(figure.CoExpress, new graphiti.layout.locator.TopRightLocator(figure)); } }; // show protein configuration $("#protein-config").css({ "display": "block" }); } else if (ctx.TYPE == "Inducer") { var connections, connection; connections = canvas.getLines(); for (var i = 0; i < connections.size; i++) { connection = connections.get(i); connection.addFigure(new g.Buttons.Activate(), new graphiti.layout.locator.ManhattanMidpointLocator(connection)); connection.addFigure(new g.Buttons.Inhibit(), new graphiti.layout.locator.MidpointLocator(connection)); } // show exogenous-factors configuration $("#exogenous-factors-config").css({ "display": "block" }); } else if (ctx.TYPE == "RORA") { for (var i = 0; i < canvas.collection.length; i++) { var figure = canvas.getFigure(canvas.collection[i]); if (figure !== null && ctx.getId() !== figure.getId() && figure.TYPE == "Protein") { figure.resetChildren(); figure.addFigure(figure.Activate, new graphiti.layout.locator.TopLeftLocator(figure)); figure.addFigure(figure.Inhibit, new graphiti.layout.locator.TopLocator(figure)); figure.addFigure(figure.CoExpress, new graphiti.layout.locator.TopRightLocator(figure)); } } } }; })(g); (function(ex) { ex.closeToolbar = function(ctx) { // remove all children nodes if (ctx.remove || ctx.label) { ctx.resetChildren(); } }; })(g); (function(ex) { ex.hideAllToolbar = function() { var canvas = app.view; for (var i = 0; i < canvas.collection.length; i++) { var figure = canvas.getFigure(canvas.collection[i]); g.closeToolbar(figure); } var connections, connection; connections = canvas.getLines(); for (var i = 0; i < connections.size; i++) { connection = connections.get(i); g.closeToolbar(connection); } } })(g); (function(ex) { ex.connect = function(source, target, type) { var canvas = source.getCanvas(); var sourcePort = source.createPort("hybrid", new graphiti.layout.locator.BottomLocator(source)); var aTarget = null; for (var i = 0; i < target.getChildren().getSize(); i++) { if (target.getChildren().get(i).TYPE == type) { aTarget = target.getChildren().get(i); break; } } var targetPort = aTarget.createPort("hybrid", new graphiti.layout.locator.BottomLocator(aTarget)); var command; if (type == "A") { command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.ArrowDecorator(), "Activate"); // 连接两点 } else if (type == "R") { command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.TDecorator(), "Inhibit"); // 连接两点 } app.view.getCommandStack().execute(command); // 添加到命令栈中 app.view.connections.push(command.connection.getId()); // 添加connection的id到connections集合中 }; })(g); // remove all lines that can be traversed along the path starting from "startNode" (function(ex) { ex.removeLinks = function(startNode) { }; })(g);
project/Python27/web/static/js/regulation/graphiti.js
/** * * File: graphiti.js * Author: Rathinho * Description: Initialization of graphiti * **/ // Create namespace var g = {}; g.Application = Class.extend({ NAME: "graphiti.Application", /** * @constructor * * @param {String} canvasId the id of the DOM element to use as paint container */ init: function() { this.view = new g.View("canvas"); }, undo: function() { this.view.getCommandStack().undo(); }, redo: function() { this.view.getCommandStack().redo(); }, zoom: function(x, y, zoomFactor) { this.view.setZoom(this.view.getZoom() * zoomFactor); }, zoomReset: function() { this.view.setZoom(1.0); }, toggleSnapToGrid: function() { this.view.setSnapToGrid(!this.view.getSnapToGrid()); } }); g.View = graphiti.Canvas.extend({ init: function(id) { this._super(id); this.setScrollArea("#" + id); this.currentDropConnection = null; this.setSnapToGrid(true); this.collection = new Array(); // Store all components in this view this.connections = new Array(); // Store all connections in this view this.boundPairs = new Array(); // Store all bounds of proteins this.currentSelected = null; // Store the figure that is currently seleted this.collection.counter = 0; }, /** * @method * Called if the DragDrop object is moving around.<br> * <br> * Graphiti use the jQuery draggable/droppable lib. Please inspect * http://jqueryui.com/demos/droppable/ for further information. * * @param {HTMLElement} droppedDomNode The dragged DOM element. * @param {Number} x the x coordinate of the drag * @param {Number} y the y coordinate of the drag * * @template **/ onDrag: function(droppedDomNode, x, y) {}, /** * @method * Called if the user drop the droppedDomNode onto the canvas.<br> * <br> * Graphiti use the jQuery draggable/droppable lib. Please inspect * http://jqueryui.com/demos/droppable/ for further information. * * @param {HTMLElement} droppedDomNode The dropped DOM element. * @param {Number} x the x coordinate of the drop * @param {Number} y the y coordinate of the drop * @private **/ onDrop: function(droppedDomNode, x, y) { var type = $(droppedDomNode).data("shape"); var figure = eval("new " + type + "();"); // create a command for the undo/redo support var command = new graphiti.command.CommandAdd(this, figure, x, y); this.getCommandStack().execute(command); }, onMouseDown: function( /* :int */ x, /* :int */ y) { var canDragStart = true; var figure = this.getBestFigure(x, y); // check if the user click on a child shape. DragDrop and movement must redirect // to the parent // Exception: Port's if ((figure !== null && figure.getParent() !== null) && !(figure instanceof graphiti.Port)) { figure = figure.getParent(); } if (figure !== null && figure.isDraggable()) { canDragStart = figure.onDragStart(x - figure.getAbsoluteX(), y - figure.getAbsoluteY()); // Element send a veto about the drag&drop operation if (canDragStart === false) { this.mouseDraggingElement = null; this.mouseDownElement = figure; } else { this.mouseDraggingElement = figure; this.mouseDownElement = figure; } } if (figure !== this.currentSelection && figure !== null && figure.isSelectable() === true) { this.hideResizeHandles(); this.setCurrentSelection(figure); // its a line if (figure instanceof graphiti.shape.basic.Line) { // you can move a line with Drag&Drop...but not a connection. // A Connection is fixed linked with the corresponding ports. // if (!(figure instanceof graphiti.Connection)) { this.draggingLineCommand = figure.createCommand(new graphiti.command.CommandType(graphiti.command.CommandType.MOVE)); if (this.draggingLineCommand !== null) { this.draggingLine = figure; } } } else if (canDragStart === false) { this.setCurrentSelection(null); } } else if (figure === null) { this.setCurrentSelection(null); } if (figure == null) { g.hideAllToolbar(); } } }); // Creates shapes g.Shapes = {}; // shape container g.Shapes.Container = graphiti.shape.basic.Rectangle.extend({ NAME: "g.Shapes.Container", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } this.TYPE = "Container"; this.count = 0; this.boundElements = new Array(); this.setAlpha(0.1); // Buttons this.remove = new g.Buttons.Remove(); this.Activate = new g.Buttons.Activate(); this.Inhibit = new g.Buttons.Inhibit(); this.CoExpress = new g.Buttons.CoExpress(); // this.addFigure(new g.Shapes.Protein(), new graphiti.layout.locator.LeftLocator(this)); }, onClick: function(x, y) { var figure = this.getBestFigure(x, y); // console.log(figure); if (figure !== null) figure.onClick(x, y); }, onDoubleClick: function() { g.closeToolbar(this); }, resetChildren: function() { var that = this; this.children.each(function(i, e) { if (!e.figure.TYPE) { e.figure.setCanvas(null); that.children.remove(e.figure); } }); this.repaint(); }, getBestFigure: function(x, y, ignoreType) { var result = null; for (var i = 0; i < this.getChildren().getSize(); i++) { var figure = this.getChildren().get(i); if (figure.hitTest(x, y) == true && figure.TYPE !== ignoreType) { if (result === null) { result = figure; } else if (result.getZOrder() < figure.getZOrder()) { result = figure; } } }; if (result !== null) return result; } // onMouseDown : function(/* :int */x, /* :int */y) }); // Protein component g.Shapes.Protein = graphiti.shape.icon.ProteinIcon.extend({ NAME: "g.Shapes.Protein", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } this.setColor("#339BB9"); this.TYPE = "Protein"; // Buttons this.remove = new g.Buttons.Remove(); this.Activate = new g.Buttons.Activate(); this.Inhibit = new g.Buttons.Inhibit(); this.CoExpress = new g.Buttons.CoExpress(); // Label // this.label = new graphiti.shape.basic.Label("PCS"); // this.label.setFontColor("#000000"); }, onClick: function() { g.toolbar(this); }, onDoubleClick: function() { g.closeToolbar(this); } }); // Inducer component g.Shapes.Inducer = graphiti.shape.icon.InducerIcon.extend({ NAME: "g.Shapes.Inducer", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } // this.setColor("#339BB9"); this.TYPE = "Inducer"; // Buttons this.remove = new g.Buttons.Remove(); this.Activate = new g.Buttons.Activate(); this.Inhibit = new g.Buttons.Inhibit(); this.CoExpress = new g.Buttons.CoExpress(); // Label this.label = new graphiti.shape.basic.Label("Inducer"); this.label.setFontColor("#000000"); }, onClick: function() { g.toolbar(this); }, onDoubleClick: function() { g.closeToolbar(this); } }); // Metal-Ion component g.Shapes.MetalIon = graphiti.shape.icon.MetalIonIcon.extend({ NAME: "g.Shapes.MetalIon", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } this.setColor("#339BB9"); this.TYPE = "MetalIon"; // Buttons this.remove = new g.Buttons.Remove(); this.Activate = new g.Buttons.Activate(); this.Inhibit = new g.Buttons.Inhibit(); this.CoExpress = new g.Buttons.CoExpress(); // Label this.label = new graphiti.shape.basic.Label("Metal ion"); this.label.setFontColor("#000000"); }, onClick: function() { g.toolbar(this); }, onDoubleClick: function() { g.closeToolbar(this); } }); // Temperature component g.Shapes.Temperature = graphiti.shape.icon.TemperatureIcon.extend({ NAME: "g.Shapes.Temperature", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } this.setColor("#339BB9"); this.TYPE = "Temperature"; // Buttons this.remove = new g.Buttons.Remove(); this.Activate = new g.Buttons.Activate(); this.Inhibit = new g.Buttons.Inhibit(); this.CoExpress = new g.Buttons.CoExpress(); // Label this.label = new graphiti.shape.basic.Label("Temperature"); this.label.setFontColor("#000000"); }, onClick: function() { g.toolbar(this); }, onDoubleClick: function() { g.closeToolbar(this); } }); // R/A component g.Shapes.RORA = graphiti.shape.icon.RORAIcon.extend({ NAME: "g.Shapes.RORA", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } this.setColor("#339BB9"); this.TYPE = "RORA"; // Buttons this.remove = new g.Buttons.Remove(); this.Activate = new g.Buttons.Activate(); this.Inhibit = new g.Buttons.Inhibit(); this.CoExpress = new g.Buttons.CoExpress(); // Label this.label = new graphiti.shape.basic.Label("A/R"); this.label.setFontColor("#000000"); }, onClick: function() { g.toolbar(this); }, onDoubleClick: function() { if (this.remove || this.label) { this.resetChildren(); } } }); // R g.Shapes.R = graphiti.shape.icon.R.extend({ NAME: "g.Shapes.R", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } this.TYPE = "R"; } }); // A g.Shapes.A = graphiti.shape.icon.A.extend({ NAME: "g.Shapes.A", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(100, 100); } this.TYPE = "A"; } }); // Buttons g.Buttons = {}; // Remove Button g.Buttons.Remove = graphiti.shape.icon.Remove.extend({ NAME: "g.Buttons.Remove", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(20, 20); } }, onClick: function() { var parent = this.getParent(), connections = parent.getConnections(); for (var i = 0; i < connections.size; i++) { app.view.connections.remove(connections.get(i).getId()); } var command = new graphiti.command.CommandDelete(parent); // 删除父节点 app.view.getCommandStack().execute(command); // 添加到命令栈中 } }); // Activate Button g.Buttons.Activate = graphiti.shape.icon.Activate.extend({ NAME: "g.Buttons.Activate", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(20, 20); } }, onClick: function() { var canvas = this.getCanvas(); var source = this.getParent(); console.log(source.getPorts()); console.log(source.getConnections()); if (canvas.getFigure(app.view.currentSelected).TYPE == "Protein" || canvas.getFigure(app.view.currentSelected).TYPE == "Container") { g.bind(canvas.getFigure(app.view.currentSelected), null, "A"); var target = g.cache; g.connect(source, target, "A"); // var sourcePort = source.createPort("hybrid", new graphiti.layout.locator.BottomLocator(source)); // var targetPort = target.createPort("hybrid", new graphiti.layout.locator.BottomRightLocator(target)); // var command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.ArrowDecorator(), "Activate"); // 连接两点 // app.view.getCommandStack().execute(command); // 添加到命令栈中 // app.view.connections.push(command.connection.getId()); // 添加connection的id到connections集合中 } else if (canvas.getFigure(app.view.currentSelected).TYPE == "RORA") { var target = canvas.getFigure(app.view.currentSelected); var sourcePort = source.createPort("hybrid", new graphiti.layout.locator.BottomLocator(source)); var targetPort = target.createPort("hybrid", new graphiti.layout.locator.BottomLocator(target)); var command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.ArrowDecorator(), "Activate"); // 连接两点 app.view.getCommandStack().execute(command); // 添加到命令栈中 app.view.connections.push(command.connection.getId()); // 添加connection的id到connections集合中 } else if (canvas.getFigure(app.view.currentSelected).TYPE == "Inducer") { var target = canvas.getFigure(app.view.currentSelected); // var sourcePort = source.createPort("hybrid", new graphiti.layout.locator.BottomLocator(source)); var targetPort = target.createPort("hybrid", new graphiti.layout.locator.BottomLocator(target)); var sourcePort = new graphiti.HybridPort(); sourcePort.decorator = "A"; source.addFigure(sourcePort, new graphiti.layout.locator.ManhattanMidpointLocator(source)); var command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.ArrowDecorator(), "Activate"); app.view.getCommandStack().execute(command); // 添加到命令栈中 app.view.connections.push(command.connection.getId()); // 添加connection的id到connections集合中 } } }); // Inhibit Button g.Buttons.Inhibit = graphiti.shape.icon.Inhibit.extend({ NAME: "g.Buttons.Inhibit", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(20, 20); } }, onClick: function() { var canvas = this.getCanvas(); var source = this.getParent(); if (canvas.getFigure(app.view.currentSelected).TYPE == "Protein" || canvas.getFigure(app.view.currentSelected).TYPE == "Container") { g.bind(canvas.getFigure(app.view.currentSelected), null, "R"); var target = g.cache; g.connect(source, target, "R"); // var sourcePort = source.createPort("hybrid", new graphiti.layout.locator.BottomLocator(source)); // var targetPort = target.createPort("hybrid", new graphiti.layout.locator.BottomRightLocator(target)); // // new graphiti.decoration.connection.ArrowDecorator() // var command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.TDecorator(), "Inhibit"); // 连接两点 // app.view.getCommandStack().execute(command); // 添加到命令栈中 // app.view.connections.push(command.connection.getId()); // 添加connection的id到connections集合中 } else if (canvas.getFigure(app.view.currentSelected).TYPE == "RORA") { var target = canvas.getFigure(app.view.currentSelected); var sourcePort = source.createPort("hybrid", new graphiti.layout.locator.BottomLocator(source)); var targetPort = target.createPort("hybrid", new graphiti.layout.locator.BottomLocator(target)); var command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.TDecorator(), "Inhibit"); // 连接两点 app.view.getCommandStack().execute(command); // 添加到命令栈中 app.view.connections.push(command.connection.getId()); // 添加connection的id到connections集合中 } else if (canvas.getFigure(app.view.currentSelected).TYPE == "Inducer") { var target = canvas.getFigure(app.view.currentSelected); // var sourcePort = source.createPort("hybrid", new graphiti.layout.locator.BottomLocator(source)); var targetPort = target.createPort("hybrid", new graphiti.layout.locator.BottomLocator(target)); var sourcePort = new graphiti.HybridPort(); sourcePort.decorator = "T"; source.addFigure(sourcePort, new graphiti.layout.locator.ManhattanMidpointLocator(source)); var command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.TDecorator(), "Inhibit"); app.view.getCommandStack().execute(command); // 添加到命令栈中 app.view.connections.push(command.connection.getId()); // 添加connection的id到connections集合中 } } }); // Co-Expression Button g.Buttons.CoExpress = graphiti.shape.icon.CoExpress.extend({ NAME: "g.Buttons.CoExpress", init: function(width, height) { this._super(); if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(20, 20); } }, onClick: function() { var target = this.getParent(); var source = this.getCanvas().getFigure(app.view.currentSelected); if (source.TYPE == "Protein" || source.TYPE == "Container") { g.bind(source, target, "Protein"); } else if (source.TYPE == "RORA") { g.bind(source, target, "RORA"); } } }); g.Buttons.Unbind = graphiti.shape.icon.CoExpress.extend({ NAME: "g.Buttons.Unbind", init: function(width, height) { this._super(); this.from = null; this.to = null; if (typeof radius === "number") { this.setDimension(radius, radius); } else { this.setDimension(30, 20); } }, setAttr: function(from, to) { if (from !== null) this.from = from; if (to !== null) this.to = to; }, onClick: function() { g.unbind(this.from, this.to); } }); // functions /* * 两个元素的绑定 */ (function(ex) { ex.bind = function(source, target, type) { var srcPosX = source.getX(), srcPosY = source.getY(); var canvas = source.getCanvas(); var container = null, outerContainer = null; if (source.getParent() && source.getParent().TYPE === "Container") { console.log("has container"); container = source.getParent(); //内容器 outerContainer = container.getParent(); //外容器 } else { console.log("new container"); outerContainer = new g.Shapes.Container(); //外容器 var command = new graphiti.command.CommandAdd(app.view, outerContainer, srcPosX, srcPosY); app.view.getCommandStack().execute(command); app.view.collection.push(outerContainer.getId()); container = new g.Shapes.Container(); //内容器 // app.view.collection.push(container.getId()); container.addFigure(source, new graphiti.layout.locator.ContainerLocator(container, container.count, 100)); source.resetChildren(); container.count += 1; container.locator = new graphiti.layout.locator.ContainerLocator(outerContainer, outerContainer.count, 100); outerContainer.addFigure(container, container.locator); outerContainer.count += 1; } if (type == "Protein") { // 创建新的子容器 var newContainer = new g.Shapes.Container(); newContainer.addFigure(target, new graphiti.layout.locator.ContainerLocator(newContainer, newContainer.count, 100)); newContainer.count += 1; newContainer.locator = new graphiti.layout.locator.ContainerLocator(outerContainer, outerContainer.count, 100); // 添加到外容器中 outerContainer.addFigure(newContainer, newContainer.locator); outerContainer.count += 1; var unbinder = new g.Buttons.Unbind(); unbinder.setAttr(container, newContainer); unbinder.locator = new graphiti.layout.locator.UnbindLocator(outerContainer, outerContainer.count - 1, 100); outerContainer.addFigure(unbinder, unbinder.locator); // 向蛋白绑定信息数组插入记录 app.view.boundPairs.push({ from: source.getId(), to: target.getId(), type: "bound", inducer: "none" }); app.view.boundPairs.push({from: source.getId(), to: target.getId(), type: "Bound", inducer: "none"}); // 更新外容器状态 updateOuterContainer(); target.resetChildren(); } else if (type == "R") { var has = false; for (var i = 0; i < container.getChildren().size; i++) { var figure = container.getChildren().get(i); if (figure.TYPE == "R") { has = true; break; } } if (!has) { container.setDimension(container.count * 100 + 100, 100); container.addFigure(new g.Shapes.R(), new graphiti.layout.locator.ContainerLocator(container, container.count, 100)); container.count += 1; updateOuterContainer(); } } else if (type == "A") { var has = false; for (var i = 0; i < container.getChildren().size; i++) { var figure = container.getChildren().get(i); if (figure.TYPE == "A") { has = true; break; } } if (!has) { container.setDimension(container.count * 100 + 100, 100); container.addFigure(new g.Shapes.A(), new graphiti.layout.locator.ContainerLocator(container, container.count, 100)); container.count += 1; updateOuterContainer(); } } // 计算并设置外容器宽度 g.cache = container; g.hideAllToolbar(); // 更新外层容器的大小和内部的元素次序 function updateOuterContainer() { var children = outerContainer.getChildren(); var len = children.getSize(); var count = 0; for (var i = 0; i < len; i++) { var innerContainer = children.get(i); if (innerContainer.TYPE == "Container") { innerContainer.locator.no = count; innerContainer.locator.relocate(i, innerContainer); count += innerContainer.count; // console.log(innerContainer.count); } } console.log(children); outerContainer.setDimension(count * 100, 100); } }; })(g); /* * 元素的解绑定 */ (function(ex) { ex.unbind = function(from, to) { alert("haha"); }; })(g); /* * 在生物元件上方显示操作按钮组 */ (function(ex) { ex.toolbar = function(ctx) { // Dom operation $("#right-container").css({ right: '0px' }); var hasClassIn = $("#collapseTwo").hasClass('in'); if (!hasClassIn) { $("#collapseOne").toggleClass('in'); $("#collapseOne").css({ height: '0' }); $("#collapseTwo").toggleClass('in'); $("#collapseTwo").css({ height: "auto" }); } $("#exogenous-factors-config").css({ "display": "none" }); $("#protein-config").css({ "display": "none" }); $("#component-config").css({ "display": "none" }); $("#arrow-config").css({ "display": "none" }); // set current selected figure app.view.currentSelected = ctx.getId(); // remove all children nodes if (ctx.remove || ctx.label) { ctx.resetChildren(); } // add remove button and label ctx.addFigure(ctx.remove, new graphiti.layout.locator.TopLocator(ctx)); // ctx.addFigure(ctx.label, new graphiti.layout.locator.BottomLocator(ctx)); // get this canvas var canvas = ctx.getCanvas(); // different opearation for different types of components if (ctx.TYPE == "Protein") { for (var i = 0; i < canvas.collection.length; i++) { var figure = canvas.getFigure(canvas.collection[i]); if (figure !== null && ctx.getId() !== figure.getId() && (figure.TYPE == "Protein") && !figure.getParent() && figure.getConnections().getSize() == 0) { figure.resetChildren(); figure.addFigure(figure.Activate, new graphiti.layout.locator.TopLeftLocator(figure)); figure.addFigure(figure.Inhibit, new graphiti.layout.locator.TopLocator(figure)); figure.addFigure(figure.CoExpress, new graphiti.layout.locator.TopRightLocator(figure)); } }; // show protein configuration $("#protein-config").css({ "display": "block" }); } else if (ctx.TYPE == "Inducer") { var connections, connection; connections = canvas.getLines(); for (var i = 0; i < connections.size; i++) { connection = connections.get(i); connection.addFigure(new g.Buttons.Activate(), new graphiti.layout.locator.ManhattanMidpointLocator(connection)); connection.addFigure(new g.Buttons.Inhibit(), new graphiti.layout.locator.MidpointLocator(connection)); } // show exogenous-factors configuration $("#exogenous-factors-config").css({ "display": "block" }); } else if (ctx.TYPE == "RORA") { for (var i = 0; i < canvas.collection.length; i++) { var figure = canvas.getFigure(canvas.collection[i]); if (figure !== null && ctx.getId() !== figure.getId() && figure.TYPE == "Protein") { figure.resetChildren(); figure.addFigure(figure.Activate, new graphiti.layout.locator.TopLeftLocator(figure)); figure.addFigure(figure.Inhibit, new graphiti.layout.locator.TopLocator(figure)); figure.addFigure(figure.CoExpress, new graphiti.layout.locator.TopRightLocator(figure)); } } } }; })(g); (function(ex) { ex.closeToolbar = function(ctx) { // remove all children nodes if (ctx.remove || ctx.label) { ctx.resetChildren(); } }; })(g); (function(ex) { ex.hideAllToolbar = function() { var canvas = app.view; for (var i = 0; i < canvas.collection.length; i++) { var figure = canvas.getFigure(canvas.collection[i]); g.closeToolbar(figure); } var connections, connection; connections = canvas.getLines(); for (var i = 0; i < connections.size; i++) { connection = connections.get(i); g.closeToolbar(connection); } } })(g); (function(ex) { ex.connect = function(source, target, type) { var canvas = source.getCanvas(); var sourcePort = source.createPort("hybrid", new graphiti.layout.locator.BottomLocator(source)); var aTarget = null; for (var i = 0; i < target.getChildren().getSize(); i++) { if (target.getChildren().get(i).TYPE == type) { aTarget = target.getChildren().get(i); break; } } var targetPort = aTarget.createPort("hybrid", new graphiti.layout.locator.BottomLocator(aTarget)); var command; if (type == "A") { command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.ArrowDecorator(), "Activate"); // 连接两点 } else if (type == "R") { command = new graphiti.command.CommandConnect(canvas, targetPort, sourcePort, new graphiti.decoration.connection.TDecorator(), "Inhibit"); // 连接两点 } app.view.getCommandStack().execute(command); // 添加到命令栈中 app.view.connections.push(command.connection.getId()); // 添加connection的id到connections集合中 }; })(g); // remove all lines that can be traversed along the path starting from "startNode" (function(ex) { ex.removeLinks = function(startNode) { }; })(g);
rematch name
project/Python27/web/static/js/regulation/graphiti.js
rematch name
<ide><path>roject/Python27/web/static/js/regulation/graphiti.js <ide> app.view.boundPairs.push({ <ide> from: source.getId(), <ide> to: target.getId(), <del> type: "bound", <add> type: "Bound", <ide> inducer: "none" <ide> }); <ide>
JavaScript
mit
b5c75ffd96b2a42835f71f7354dc319fbe3f13bf
0
NAPWebProductionEditTeam/MagTool2,NAPWebProductionEditTeam/MagTool2,NAPWebProductionEditTeam/MagTool2
(function(window, $, app) { function Credits() { var getCreditHolder = function() { return app.Page.get().find('[class*="creditsHolder"]'); }; var getCreditWhole = function() { return app.Page.get().find('[class*="creditsWhole"]'); }; this.togglePosition = function() { var creditsHolder = getCreditHolder(); var creditsWhole = getCreditWhole(); if (creditsHolder.is('.creditsHolderRight')) { creditsHolder.addClass('creditsHolderLeft').removeClass('creditsHolderRight'); creditsWhole.addClass('creditsWholeLeft').removeClass('creditsWholeRight'); } else { creditsHolder.addClass('creditsHolderRight').removeClass('creditsHolderLeft'); creditsWhole.addClass('creditsWholeRight').removeClass('creditsWholeLeft'); } }; this.toggleColor = function() { var creditsHolder = getCreditHolder(); var creditsWhole = getCreditWhole(); creditsHolder.toggleClass('white'); }; this.toggle = function() { var creditsHolder = getCreditHolder(); var creditsWhole = getCreditWhole(); creditsHolder.toggleClass('creditsNone'); creditsWhole.toggleClass('creditsNone'); }; } app.modules.Credits = Credits; })(window, jQuery, MagTool);
src/js/Application/Credits.js
/* globals magazineBuilder */ (function(window, $, app) { function Credits (){ var getCreditHolder=function(){ return app.Page.get().find('[class*="creditsHolder"]'); }; var getCreditWhole=function(){ return app.Page.get().find('[class*="creditsWhole"]'); }; this.togglePosition = function(){ var creditsHolder = getCreditHolder(); var creditsWhole = getCreditWhole(); if(creditsHolder.is('.creditsHolderRight')) { creditsHolder.addClass('creditsHolderLeft').removeClass('creditsHolderRight'); creditsWhole.addClass('creditsWholeLeft').removeClass('creditsWholeRight'); }else { creditsHolder.addClass('creditsHolderRight').removeClass('creditsHolderLeft'); creditsWhole.addClass('creditsWholeRight').removeClass('creditsWholeLeft'); } }; this.toggleColor = function(){ var creditsHolder = getCreditHolder(); var creditsWhole = getCreditWhole(); creditsHolder.toggleClass('white'); }; this.toggle = function(){ var creditsHolder = getCreditHolder(); var creditsWhole = getCreditWhole(); creditsHolder.toggleClass('creditsNone'); creditsWhole.toggleClass('creditsNone'); }; } app.modules.Credits=Credits; })(window, jQuery, MagTool);
CS Fixes
src/js/Application/Credits.js
CS Fixes
<ide><path>rc/js/Application/Credits.js <del>/* globals magazineBuilder */ <del> <ide> (function(window, $, app) { <del> function Credits (){ <del> var getCreditHolder=function(){ <add> function Credits() { <add> var getCreditHolder = function() { <ide> return app.Page.get().find('[class*="creditsHolder"]'); <ide> }; <ide> <del> var getCreditWhole=function(){ <add> var getCreditWhole = function() { <ide> return app.Page.get().find('[class*="creditsWhole"]'); <ide> }; <ide> <del> this.togglePosition = function(){ <add> this.togglePosition = function() { <ide> var creditsHolder = getCreditHolder(); <ide> var creditsWhole = getCreditWhole(); <ide> <del> if(creditsHolder.is('.creditsHolderRight')) { <add> if (creditsHolder.is('.creditsHolderRight')) { <ide> creditsHolder.addClass('creditsHolderLeft').removeClass('creditsHolderRight'); <ide> creditsWhole.addClass('creditsWholeLeft').removeClass('creditsWholeRight'); <del> }else { <add> } else { <ide> creditsHolder.addClass('creditsHolderRight').removeClass('creditsHolderLeft'); <ide> creditsWhole.addClass('creditsWholeRight').removeClass('creditsWholeLeft'); <ide> } <ide> }; <ide> <del> this.toggleColor = function(){ <add> this.toggleColor = function() { <ide> var creditsHolder = getCreditHolder(); <ide> var creditsWhole = getCreditWhole(); <ide> <ide> creditsHolder.toggleClass('white'); <ide> }; <ide> <del> this.toggle = function(){ <add> this.toggle = function() { <ide> var creditsHolder = getCreditHolder(); <ide> var creditsWhole = getCreditWhole(); <ide> <ide> }; <ide> } <ide> <del> app.modules.Credits=Credits; <add> app.modules.Credits = Credits; <ide> })(window, jQuery, MagTool);
Java
bsd-3-clause
dff5297b7e02a968fce6ca02498526b85909680d
0
ClemsonRSRG/RESOLVE,ClemsonRSRG/RESOLVE,NighatYasmin/RESOLVE,yushan87/RESOLVE,mikekab/RESOLVE,ClemsonRSRG/RESOLVE,yushan87/RESOLVE,mikekab/RESOLVE,yushan87/RESOLVE,NighatYasmin/RESOLVE,NighatYasmin/RESOLVE
/** * VCGenerator.java * --------------------------------- * Copyright (c) 2015 * RESOLVE Software Research Group * School of Computing * Clemson University * All rights reserved. * --------------------------------- * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ package edu.clemson.cs.r2jt.vcgeneration; /* * Libraries */ import edu.clemson.cs.r2jt.ResolveCompiler; import edu.clemson.cs.r2jt.absyn.*; import edu.clemson.cs.r2jt.data.*; import edu.clemson.cs.r2jt.init.CompileEnvironment; import edu.clemson.cs.r2jt.rewriteprover.VC; import edu.clemson.cs.r2jt.treewalk.TreeWalker; import edu.clemson.cs.r2jt.treewalk.TreeWalkerVisitor; import edu.clemson.cs.r2jt.typeandpopulate.*; import edu.clemson.cs.r2jt.typeandpopulate.entry.*; import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTGeneric; import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTType; import edu.clemson.cs.r2jt.typereasoning.TypeGraph; import edu.clemson.cs.r2jt.misc.Flag; import edu.clemson.cs.r2jt.misc.FlagDependencies; import edu.clemson.cs.r2jt.vcgeneration.treewalkers.NestedFuncWalker; import java.io.File; import java.util.*; import java.util.List; /** * TODO: Write a description of this module */ public class VCGenerator extends TreeWalkerVisitor { // =========================================================== // Global Variables // =========================================================== // Symbol table related items private final MathSymbolTableBuilder mySymbolTable; private final TypeGraph myTypeGraph; private final MTType BOOLEAN; private final MTType MTYPE; private MTType Z; private ModuleScope myCurrentModuleScope; // Module level global variables private Exp myGlobalRequiresExp; private Exp myGlobalConstraintExp; // Conventions/Correspondence private Exp myConventionExp; private Exp myCorrespondenceExp; // Operation/Procedure level global variables private OperationEntry myCurrentOperationEntry; private OperationProfileEntry myCurrentOperationProfileEntry; private Exp myOperationDecreasingExp; /** * <p>The current assertion we are applying * VC rules to.</p> */ private AssertiveCode myCurrentAssertiveCode; /** * <p>A map of facility declarations to <code>Exp</code>, where the expression * contains the things we can assume from the facility declaration.</p> */ private Map<FacilityDec, Exp> myFacilityDeclarationMap; // TODO: Change this! /** * <p>A map of facility declarations to a list of formal and actual constraints.</p> */ private Map<FacilityDec, List<EqualsExp>> myFacilityFormalActualMap; /** * <p>A list that will be built up with <code>AssertiveCode</code> * objects, each representing a VC or group of VCs that must be * satisfied to verify a parsed program.</p> */ private Collection<AssertiveCode> myFinalAssertiveCodeList; /** * <p>A stack that is used to keep track of the <code>AssertiveCode</code> * that we still need to apply proof rules to.</p> */ private Stack<AssertiveCode> myIncAssertiveCodeStack; /** * <p>A stack that is used to keep track of the information that we * haven't printed for the <code>AssertiveCode</code> * that we still need to apply proof rules to.</p> */ private Stack<String> myIncAssertiveCodeStackInfo; /** * <p>The current compile environment used throughout * the compiler.</p> */ private CompileEnvironment myInstanceEnvironment; /** * <p>This object creates the different VC outputs.</p> */ private OutputVCs myOutputGenerator; /** * <p>This string buffer holds all the steps * the VC generator takes to generate VCs.</p> */ private StringBuffer myVCBuffer; // =========================================================== // Flag Strings // =========================================================== private static final String FLAG_ALTSECTION_NAME = "GenerateVCs"; private static final String FLAG_DESC_ATLVERIFY_VC = "Generate VCs."; private static final String FLAG_DESC_ATTPVCS_VC = "Generate Performance VCs"; // =========================================================== // Flags // =========================================================== public static final Flag FLAG_ALTVERIFY_VC = new Flag(FLAG_ALTSECTION_NAME, "altVCs", FLAG_DESC_ATLVERIFY_VC); public static final Flag FLAG_ALTPVCS_VC = new Flag(FLAG_ALTSECTION_NAME, "PVCs", FLAG_DESC_ATTPVCS_VC); public static final void setUpFlags() { FlagDependencies.addImplies(FLAG_ALTPVCS_VC, FLAG_ALTVERIFY_VC); } // =========================================================== // Constructors // =========================================================== public VCGenerator(ScopeRepository table, final CompileEnvironment env) { // Symbol table items mySymbolTable = (MathSymbolTableBuilder) table; myTypeGraph = mySymbolTable.getTypeGraph(); BOOLEAN = myTypeGraph.BOOLEAN; MTYPE = myTypeGraph.CLS; Z = null; // Current items myConventionExp = null; myCorrespondenceExp = null; myCurrentModuleScope = null; myCurrentOperationEntry = null; myCurrentOperationProfileEntry = null; myGlobalConstraintExp = null; myGlobalRequiresExp = null; myOperationDecreasingExp = null; // Instance Environment myInstanceEnvironment = env; // VCs + Debugging String myCurrentAssertiveCode = null; myFacilityDeclarationMap = new HashMap<FacilityDec, Exp>(); myFacilityFormalActualMap = new HashMap<FacilityDec, List<EqualsExp>>(); myFinalAssertiveCodeList = new LinkedList<AssertiveCode>(); myIncAssertiveCodeStack = new Stack<AssertiveCode>(); myIncAssertiveCodeStackInfo = new Stack<String>(); myOutputGenerator = null; myVCBuffer = new StringBuffer(); } // =========================================================== // Visitor Methods // =========================================================== // ----------------------------------------------------------- // ConceptBodyModuleDec // ----------------------------------------------------------- @Override public void preConceptBodyModuleDec(ConceptBodyModuleDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" VC Generation Details "); myVCBuffer.append(" =========================\n"); myVCBuffer.append("\n Concept Realization Name:\t"); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append("\n Concept Name:\t"); myVCBuffer.append(dec.getConceptName().getName()); myVCBuffer.append("\n"); myVCBuffer.append("\n===================================="); myVCBuffer.append("======================================\n"); myVCBuffer.append("\n"); // Set the current module scope try { myCurrentModuleScope = mySymbolTable.getModuleScope(new ModuleIdentifier(dec)); // Get "Z" from the TypeGraph Z = Utilities.getMathTypeZ(dec.getLocation(), myCurrentModuleScope); // From the list of imports, obtain the global constraints // of the imported modules. myGlobalConstraintExp = getConstraints(dec.getLocation(), myCurrentModuleScope .getImports()); // Store the global requires clause myGlobalRequiresExp = getRequiresClause(dec.getLocation(), dec); // Obtain the global requires clause from the Concept ConceptModuleDec conceptModuleDec = (ConceptModuleDec) mySymbolTable .getModuleScope( new ModuleIdentifier(dec.getConceptName() .getName())).getDefiningElement(); Exp conceptRequires = getRequiresClause(conceptModuleDec.getLocation(), conceptModuleDec); if (!conceptRequires.isLiteralTrue()) { if (myGlobalRequiresExp.isLiteralTrue()) { myGlobalRequiresExp = conceptRequires; } else { myGlobalRequiresExp = myTypeGraph.formConjunct(myGlobalRequiresExp, conceptRequires); } } } catch (NoSuchSymbolException e) { System.err.println("Module " + dec.getName() + " does not exist or is not in scope."); Utilities.noSuchModule(dec.getLocation()); } } @Override public void postConceptBodyModuleDec(ConceptBodyModuleDec dec) { // Set the module level global variables to null myCurrentModuleScope = null; myGlobalConstraintExp = null; myGlobalRequiresExp = null; } // ----------------------------------------------------------- // EnhancementBodyModuleDec // ----------------------------------------------------------- @Override public void preEnhancementBodyModuleDec(EnhancementBodyModuleDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" VC Generation Details "); myVCBuffer.append(" =========================\n"); myVCBuffer.append("\n Enhancement Realization Name:\t"); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append("\n Enhancement Name:\t"); myVCBuffer.append(dec.getEnhancementName().getName()); myVCBuffer.append("\n Concept Name:\t"); myVCBuffer.append(dec.getConceptName().getName()); myVCBuffer.append("\n"); myVCBuffer.append("\n===================================="); myVCBuffer.append("======================================\n"); myVCBuffer.append("\n"); // Set the current module scope try { myCurrentModuleScope = mySymbolTable.getModuleScope(new ModuleIdentifier(dec)); // Get "Z" from the TypeGraph Z = Utilities.getMathTypeZ(dec.getLocation(), myCurrentModuleScope); // From the list of imports, obtain the global constraints // of the imported modules. myGlobalConstraintExp = getConstraints(dec.getLocation(), myCurrentModuleScope .getImports()); // Store the global requires clause myGlobalRequiresExp = getRequiresClause(dec.getLocation(), dec); // Obtain the global requires clause from the Concept ConceptModuleDec conceptModuleDec = (ConceptModuleDec) mySymbolTable .getModuleScope( new ModuleIdentifier(dec.getConceptName() .getName())).getDefiningElement(); Exp conceptRequires = getRequiresClause(conceptModuleDec.getLocation(), conceptModuleDec); if (!conceptRequires.isLiteralTrue()) { if (myGlobalRequiresExp.isLiteralTrue()) { myGlobalRequiresExp = conceptRequires; } else { myGlobalRequiresExp = myTypeGraph.formConjunct(myGlobalRequiresExp, conceptRequires); } } // Obtain the global requires clause from the Enhancement EnhancementModuleDec enhancementModuleDec = (EnhancementModuleDec) mySymbolTable.getModuleScope( new ModuleIdentifier(dec.getEnhancementName() .getName())).getDefiningElement(); Exp enhancementRequires = getRequiresClause(enhancementModuleDec.getLocation(), enhancementModuleDec); if (!enhancementRequires.isLiteralTrue()) { if (myGlobalRequiresExp.isLiteralTrue()) { myGlobalRequiresExp = enhancementRequires; } else { myGlobalRequiresExp = myTypeGraph.formConjunct(myGlobalRequiresExp, enhancementRequires); } } } catch (NoSuchSymbolException e) { System.err.println("Module " + dec.getName() + " does not exist or is not in scope."); Utilities.noSuchModule(dec.getLocation()); } } @Override public void postEnhancementBodyModuleDec(EnhancementBodyModuleDec dec) { // Set the module level global variables to null myCurrentModuleScope = null; myGlobalConstraintExp = null; myGlobalRequiresExp = null; } // ----------------------------------------------------------- // FacilityDec // ----------------------------------------------------------- @Override public void postFacilityDec(FacilityDec dec) { // Applies the facility declaration rule applyFacilityDeclRule(dec); // Loop through assertive code stack loopAssertiveCodeStack(); } // ----------------------------------------------------------- // FacilityModuleDec // ----------------------------------------------------------- @Override public void preFacilityModuleDec(FacilityModuleDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" VC Generation Details "); myVCBuffer.append(" =========================\n"); myVCBuffer.append("\n Facility Name:\t"); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append("\n"); myVCBuffer.append("\n===================================="); myVCBuffer.append("======================================\n"); myVCBuffer.append("\n"); // Set the current module scope try { myCurrentModuleScope = mySymbolTable.getModuleScope(new ModuleIdentifier(dec)); // Get "Z" from the TypeGraph Z = Utilities.getMathTypeZ(dec.getLocation(), myCurrentModuleScope); // From the list of imports, obtain the global constraints // of the imported modules. myGlobalConstraintExp = getConstraints(dec.getLocation(), myCurrentModuleScope .getImports()); // Store the global requires clause myGlobalRequiresExp = getRequiresClause(dec.getLocation(), dec); } catch (NoSuchSymbolException e) { System.err.println("Module " + dec.getName() + " does not exist or is not in scope."); Utilities.noSuchModule(dec.getLocation()); } } @Override public void postFacilityModuleDec(FacilityModuleDec dec) { // Set the module level global variables to null myCurrentModuleScope = null; myGlobalConstraintExp = null; myGlobalRequiresExp = null; } // ----------------------------------------------------------- // FacilityOperationDec // ----------------------------------------------------------- @Override public void preFacilityOperationDec(FacilityOperationDec dec) { // Keep the current operation dec List<PTType> argTypes = new LinkedList<PTType>(); for (ParameterVarDec p : dec.getParameters()) { argTypes.add(p.getTy().getProgramTypeValue()); } myCurrentOperationEntry = Utilities.searchOperation(dec.getLocation(), null, dec .getName(), argTypes, myCurrentModuleScope); // Obtain the performance duration clause if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { myCurrentOperationProfileEntry = Utilities.searchOperationProfile(dec.getLocation(), null, dec.getName(), argTypes, myCurrentModuleScope); } } @Override public void postFacilityOperationDec(FacilityOperationDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" Procedure: "); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append(" =========================\n"); // The current assertive code myCurrentAssertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Obtains items from the current operation Location loc = dec.getLocation(); String name = dec.getName().getName(); boolean isLocal = Utilities.isLocationOperation(dec.getName().getName(), myCurrentModuleScope); Exp requires = modifyRequiresClause(getRequiresClause(loc, dec), loc, name, isLocal); Exp ensures = modifyEnsuresClause(getEnsuresClause(loc, dec), loc, name, isLocal); List<Statement> statementList = dec.getStatements(); List<VarDec> variableList = dec.getAllVariables(); Exp decreasing = dec.getDecreasing(); Exp procDur = null; Exp varFinalDur = null; // Obtain type constrains from parameter // TODO: Only add type constraints if they use the facility; Exp typeConstraint = null; for (FacilityDec fDec : myFacilityDeclarationMap.keySet()) { Exp temp = Exp.copy(myFacilityDeclarationMap.get(fDec)); if (typeConstraint == null) { typeConstraint = temp; } else { typeConstraint = myTypeGraph.formConjunct(typeConstraint, temp); } } // NY YS if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { procDur = myCurrentOperationProfileEntry.getDurationClause(); // Loop through local variables to get their finalization duration for (VarDec v : dec.getVariables()) { Exp finalVarDur = Utilities.createFinalizAnyDur(v, myTypeGraph.R); // Create/Add the duration expression if (varFinalDur == null) { varFinalDur = finalVarDur; } else { varFinalDur = new InfixExp((Location) loc.clone(), varFinalDur, Utilities.createPosSymbol("+"), finalVarDur); } varFinalDur.setMathType(myTypeGraph.R); } } // Apply the procedure declaration rule applyProcedureDeclRule(loc, name, requires, ensures, decreasing, procDur, varFinalDur, typeConstraint, variableList, statementList, isLocal); // Add this to our stack of to be processed assertive codes. myIncAssertiveCodeStack.push(myCurrentAssertiveCode); myIncAssertiveCodeStackInfo.push(""); // Set the current assertive code to null // YS: (We the modify requires and ensures clause needs to have // and current assertive code to work. Not very clean way to // solve the problem, but should work.) myCurrentAssertiveCode = null; // Loop through assertive code stack loopAssertiveCodeStack(); myOperationDecreasingExp = null; myCurrentOperationEntry = null; myCurrentOperationProfileEntry = null; } // ----------------------------------------------------------- // ModuleDec // ----------------------------------------------------------- @Override public void postModuleDec(ModuleDec dec) { // Create the output generator and finalize output myOutputGenerator = new OutputVCs(myInstanceEnvironment, myFinalAssertiveCodeList, myVCBuffer); // Check if it is generating VCs for WebIDE or not. if (myInstanceEnvironment.flags.isFlagSet(ResolveCompiler.FLAG_XML_OUT)) { myOutputGenerator.outputToJSON(); } else { // Print to file if we are in debug mode // TODO: Add debug flag here String filename; if (myInstanceEnvironment.getOutputFilename() != null) { filename = myInstanceEnvironment.getOutputFilename(); } else { filename = createVCFileName(); } myOutputGenerator.outputToFile(filename); } } // ----------------------------------------------------------- // ProcedureDec // ----------------------------------------------------------- @Override public void preProcedureDec(ProcedureDec dec) { // Keep the current operation dec List<PTType> argTypes = new LinkedList<PTType>(); for (ParameterVarDec p : dec.getParameters()) { argTypes.add(p.getTy().getProgramTypeValue()); } myCurrentOperationEntry = Utilities.searchOperation(dec.getLocation(), null, dec .getName(), argTypes, myCurrentModuleScope); // Obtain the performance duration clause if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { myCurrentOperationProfileEntry = Utilities.searchOperationProfile(dec.getLocation(), null, dec.getName(), argTypes, myCurrentModuleScope); } } @Override public void postProcedureDec(ProcedureDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" Procedure: "); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append(" =========================\n"); // The current assertive code myCurrentAssertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Obtains items from the current operation OperationDec opDec = (OperationDec) myCurrentOperationEntry.getDefiningElement(); Location loc = dec.getLocation(); String name = dec.getName().getName(); boolean isLocal = Utilities.isLocationOperation(dec.getName().getName(), myCurrentModuleScope); Exp requires = modifyRequiresClause(getRequiresClause(loc, opDec), loc, name, isLocal); Exp ensures = modifyEnsuresClause(getEnsuresClause(loc, opDec), loc, name, isLocal); List<Statement> statementList = dec.getStatements(); List<VarDec> variableList = dec.getAllVariables(); Exp decreasing = dec.getDecreasing(); Exp procDur = null; Exp varFinalDur = null; // Obtain type constrains from parameter // TODO: Only add type constraints if they use the facility; Exp facTypeConstraint = null; for (FacilityDec fDec : myFacilityDeclarationMap.keySet()) { Exp temp = Exp.copy(myFacilityDeclarationMap.get(fDec)); if (facTypeConstraint == null) { facTypeConstraint = temp; } else { facTypeConstraint = myTypeGraph.formConjunct(facTypeConstraint, temp); } } // NY YS if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { procDur = myCurrentOperationProfileEntry.getDurationClause(); // Loop through local variables to get their finalization duration for (VarDec v : dec.getVariables()) { Exp finalVarDur = Utilities.createFinalizAnyDur(v, BOOLEAN); // Create/Add the duration expression if (varFinalDur == null) { varFinalDur = finalVarDur; } else { varFinalDur = new InfixExp((Location) loc.clone(), varFinalDur, Utilities.createPosSymbol("+"), finalVarDur); } varFinalDur.setMathType(myTypeGraph.R); } } // Apply the procedure declaration rule applyProcedureDeclRule(loc, name, requires, ensures, decreasing, procDur, varFinalDur, facTypeConstraint, variableList, statementList, isLocal); // Add this to our stack of to be processed assertive codes. myIncAssertiveCodeStack.push(myCurrentAssertiveCode); myIncAssertiveCodeStackInfo.push(""); // Set the current assertive code to null // YS: (We the modify requires and ensures clause needs to have // and current assertive code to work. Not very clean way to // solve the problem, but should work.) myCurrentAssertiveCode = null; // Loop through assertive code stack loopAssertiveCodeStack(); myOperationDecreasingExp = null; myCurrentOperationEntry = null; myCurrentOperationProfileEntry = null; } // ----------------------------------------------------------- // RepresentationDec // ----------------------------------------------------------- @Override public void postRepresentationDec(RepresentationDec dec) { // Applies the initialization rule applyInitializationRule(dec); // Applies the correspondence rule applyCorrespondenceRule(dec); // Loop through assertive code stack loopAssertiveCodeStack(); } // =========================================================== // Public Methods // =========================================================== // ----------------------------------------------------------- // Prover Mode // ----------------------------------------------------------- /** * <p>The set of immmutable VCs that the in house provers can use.</p> * * @return VCs to be proved. */ public List<VC> proverOutput() { return myOutputGenerator.getProverOutput(); } // =========================================================== // Private Methods // =========================================================== /** * <p>Loop through the list of <code>VarDec</code>, search * for their corresponding <code>ProgramVariableEntry</code> * and add the result to the list of free variables.</p> * * @param variableList List of the all variables as * <code>VarDec</code>. */ private void addVarDecsAsFreeVars(List<VarDec> variableList) { // Loop through the variable list for (VarDec v : variableList) { myCurrentAssertiveCode.addFreeVar(Utilities.createVarExp(v .getLocation(), null, v.getName(), v.getTy() .getMathTypeValue(), null)); } } /** * <p>Creates the name of the output file.</p> * * @return Name of the file */ private String createVCFileName() { File file = myInstanceEnvironment.getTargetFile(); ModuleID cid = myInstanceEnvironment.getModuleID(file); file = myInstanceEnvironment.getFile(cid); String filename = file.toString(); int temp = filename.indexOf("."); String tempfile = filename.substring(0, temp); String mainFileName; mainFileName = tempfile + ".asrt_new"; return mainFileName; } /** * <p>Returns all the constraint clauses combined together for the * for the current <code>ModuleDec</code>.</p> * * @param loc The location of the <code>ModuleDec</code>. * @param imports The list of imported modules. * * @return The constraint clause <code>Exp</code>. */ private Exp getConstraints(Location loc, List<ModuleIdentifier> imports) { Exp retExp = null; List<String> importedConceptName = new LinkedList<String>(); // Loop for (ModuleIdentifier mi : imports) { try { ModuleDec dec = mySymbolTable.getModuleScope(mi).getDefiningElement(); List<Exp> contraintExpList = null; // Handling for facility imports if (dec instanceof ShortFacilityModuleDec) { FacilityDec facDec = ((ShortFacilityModuleDec) dec).getDec(); dec = mySymbolTable.getModuleScope( new ModuleIdentifier(facDec .getConceptName().getName())) .getDefiningElement(); } if (dec instanceof ConceptModuleDec && !importedConceptName.contains(dec.getName() .getName())) { contraintExpList = ((ConceptModuleDec) dec).getConstraints(); // Copy all the constraints for (Exp e : contraintExpList) { // Deep copy and set the location detail Exp constraint = Exp.copy(e); if (constraint.getLocation() != null) { Location theLoc = constraint.getLocation(); theLoc.setDetails("Constraint of Module: " + dec.getName()); Utilities.setLocation(constraint, theLoc); } // Form conjunct if needed. if (retExp == null) { retExp = Exp.copy(e); } else { retExp = myTypeGraph.formConjunct(retExp, Exp .copy(e)); } } // Avoid importing constraints for the same concept twice importedConceptName.add(dec.getName().getName()); } } catch (NoSuchSymbolException e) { System.err.println("Module " + mi.toString() + " does not exist or is not in scope."); Utilities.noSuchModule(loc); } } return retExp; } /** * <p>Returns the ensures clause for the current <code>Dec</code>.</p> * * @param location The location of the ensures clause. * @param dec The corresponding <code>Dec</code>. * * @return The ensures clause <code>Exp</code>. */ private Exp getEnsuresClause(Location location, Dec dec) { PosSymbol name = dec.getName(); Exp ensures = null; Exp retExp; // Check for each kind of ModuleDec possible if (dec instanceof FacilityOperationDec) { ensures = ((FacilityOperationDec) dec).getEnsures(); } else if (dec instanceof OperationDec) { ensures = ((OperationDec) dec).getEnsures(); } // Deep copy and fill in the details of this location if (ensures != null) { retExp = Exp.copy(ensures); } else { retExp = myTypeGraph.getTrueVarExp(); } if (retExp.getLocation() != null) { Location loc = (Location) location.clone(); loc.setDetails("Ensures Clause of " + name); Utilities.setLocation(retExp, loc); } return retExp; } /** * <p>Locate and return the corresponding operation dec based on the qualifier, * name, and arguments.</p> * * @param loc Location of the calling statement. * @param qual Qualifier of the operation * @param name Name of the operation. * @param args List of arguments for the operation. * * @return The operation corresponding to the calling statement in <code>OperationDec</code> form. */ private OperationDec getOperationDec(Location loc, PosSymbol qual, PosSymbol name, List<ProgramExp> args) { // Obtain the corresponding OperationEntry and OperationDec List<PTType> argTypes = new LinkedList<PTType>(); for (ProgramExp arg : args) { argTypes.add(arg.getProgramType()); } OperationEntry opEntry = Utilities.searchOperation(loc, qual, name, argTypes, myCurrentModuleScope); // Obtain an OperationDec from the OperationEntry ResolveConceptualElement element = opEntry.getDefiningElement(); OperationDec opDec; if (element instanceof OperationDec) { opDec = (OperationDec) opEntry.getDefiningElement(); } else { FacilityOperationDec fOpDec = (FacilityOperationDec) opEntry.getDefiningElement(); opDec = new OperationDec(fOpDec.getName(), fOpDec.getParameters(), fOpDec.getReturnTy(), fOpDec.getStateVars(), fOpDec .getRequires(), fOpDec.getEnsures()); } return opDec; } /** * <p>Returns the requires clause for the current <code>Dec</code>.</p> * * @param location The location of the requires clause. * @param dec The corresponding <code>Dec</code>. * * @return The requires clause <code>Exp</code>. */ private Exp getRequiresClause(Location location, Dec dec) { PosSymbol name = dec.getName(); Exp requires = null; Exp retExp; // Check for each kind of ModuleDec possible if (dec instanceof FacilityOperationDec) { requires = ((FacilityOperationDec) dec).getRequires(); } else if (dec instanceof OperationDec) { requires = ((OperationDec) dec).getRequires(); } else if (dec instanceof ConceptModuleDec) { requires = ((ConceptModuleDec) dec).getRequirement(); } else if (dec instanceof ConceptBodyModuleDec) { requires = ((ConceptBodyModuleDec) dec).getRequires(); } else if (dec instanceof EnhancementModuleDec) { requires = ((EnhancementModuleDec) dec).getRequirement(); } else if (dec instanceof EnhancementBodyModuleDec) { requires = ((EnhancementBodyModuleDec) dec).getRequires(); } else if (dec instanceof FacilityModuleDec) { requires = ((FacilityModuleDec) dec).getRequirement(); } // Deep copy and fill in the details of this location if (requires != null) { retExp = Exp.copy(requires); } else { retExp = myTypeGraph.getTrueVarExp(); } if (location != null) { Location loc = (Location) location.clone(); loc.setDetails("Requires Clause for " + name); Utilities.setLocation(retExp, loc); } return retExp; } /** * <p>Loop through our stack of incomplete assertive codes.</p> */ private void loopAssertiveCodeStack() { // Loop until our to process assertive code stack is empty while (!myIncAssertiveCodeStack.empty()) { // Set the incoming assertive code as our current assertive // code we are working on. myCurrentAssertiveCode = myIncAssertiveCodeStack.pop(); myVCBuffer.append("\n***********************"); myVCBuffer.append("***********************\n"); // Append any information that still needs to be added to our // Debug VC Buffer myVCBuffer.append(myIncAssertiveCodeStackInfo.pop()); // Apply proof rules applyRules(); myVCBuffer.append("\n***********************"); myVCBuffer.append("***********************\n"); // Add it to our list of final assertive codes if we don't have confirm true // as our goal. if (!myCurrentAssertiveCode.getFinalConfirm().getAssertion() .isLiteralTrue()) { myFinalAssertiveCodeList.add(myCurrentAssertiveCode); } // Set the current assertive code to null myCurrentAssertiveCode = null; } } /** * <p>Modify the argument expression list if we have a * nested function call.</p> * * @param callArgs The original list of arguments. * * @return The modified list of arguments. */ private List<Exp> modifyArgumentList(List<ProgramExp> callArgs) { // Find all the replacements that needs to happen to the requires // and ensures clauses List<Exp> replaceArgs = new ArrayList<Exp>(); for (ProgramExp p : callArgs) { // Check for nested function calls in ProgramDotExp // and ProgramParamExp. if (p instanceof ProgramDotExp || p instanceof ProgramParamExp) { NestedFuncWalker nfw = new NestedFuncWalker(myCurrentOperationEntry, myOperationDecreasingExp, mySymbolTable, myCurrentModuleScope, myCurrentAssertiveCode); TreeWalker tw = new TreeWalker(nfw); tw.visit(p); // Add the requires clause as something we need to confirm Exp pRequires = nfw.getRequiresClause(); if (!pRequires.isLiteralTrue()) { myCurrentAssertiveCode.addConfirm(pRequires.getLocation(), pRequires, false); } // Add the modified ensures clause as the new expression we want // to replace in the CallStmt's ensures clause. replaceArgs.add(nfw.getEnsuresClause()); } // For all other types of arguments, simply add it to the list to be replaced else { replaceArgs.add(p); } } return replaceArgs; } /** * <p>Modifies the ensures clause based on the parameter mode.</p> * * @param ensures The <code>Exp</code> containing the ensures clause. * @param opLocation The <code>Location</code> for the operation * @param opName The name of the operation. * @param parameterVarDecList The list of parameter variables for the operation. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified ensures clause <code>Exp</code>. */ private Exp modifyEnsuresByParameter(Exp ensures, Location opLocation, String opName, List<ParameterVarDec> parameterVarDecList, boolean isLocal) { // Loop through each parameter for (ParameterVarDec p : parameterVarDecList) { // Ty is NameTy if (p.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) p.getTy(); // Exp form of the parameter variable VarExp parameterExp = new VarExp(p.getLocation(), null, p.getName().copy()); parameterExp.setMathType(pNameTy.getMathTypeValue()); // Create an old exp (#parameterExp) OldExp oldParameterExp = new OldExp(p.getLocation(), Exp.copy(parameterExp)); oldParameterExp.setMathType(pNameTy.getMathTypeValue()); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy.getQualifier(), pNameTy.getName(), myCurrentModuleScope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste .toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); } // Preserves or Restores mode if (p.getMode() == Mode.PRESERVES || p.getMode() == Mode.RESTORES) { // Create an equals expression of the form "#parameterExp = parameterExp" EqualsExp equalsExp = new EqualsExp(opLocation, oldParameterExp, EqualsExp.EQUAL, parameterExp); equalsExp.setMathType(BOOLEAN); // Set the details for the new location Location equalLoc; if (ensures != null && ensures.getLocation() != null) { Location enLoc = ensures.getLocation(); equalLoc = ((Location) enLoc.clone()); } else { equalLoc = ((Location) opLocation.clone()); equalLoc.setDetails("Ensures Clause of " + opName); } equalLoc.setDetails(equalLoc.getDetails() + " (Condition from \"" + p.getMode().getModeName() + "\" parameter mode)"); equalsExp.setLocation(equalLoc); // Create an AND infix expression with the ensures clause if (ensures != null && !ensures.equals(myTypeGraph.getTrueVarExp())) { Location newEnsuresLoc = (Location) ensures.getLocation().clone(); ensures = myTypeGraph.formConjunct(ensures, equalsExp); ensures.setLocation(newEnsuresLoc); } // Make new expression the ensures clause else { ensures = equalsExp; } } // Clears mode else if (p.getMode() == Mode.CLEARS) { Exp init; if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Obtain the exemplar in VarExp form VarExp exemplar = new VarExp(null, null, type.getExemplar()); exemplar.setMathType(pNameTy.getMathTypeValue()); // Deep copy the original initialization ensures and the constraint init = Exp.copy(type.getInitialization().getEnsures()); // Replace the formal with the actual init = Utilities.replace(init, exemplar, parameterExp); // Set the details for the new location if (init.getLocation() != null) { Location initLoc; if (ensures != null && ensures.getLocation() != null) { Location reqLoc = ensures.getLocation(); initLoc = ((Location) reqLoc.clone()); } else { initLoc = ((Location) opLocation.clone()); initLoc.setDetails("Ensures Clause of " + opName); } initLoc.setDetails(initLoc.getDetails() + " (Condition from \"" + p.getMode().getModeName() + "\" parameter mode)"); init.setLocation(initLoc); } } // Since the type is generic, we can only use the is_initial predicate // to ensure that the value is initial value. else { // Obtain the original dec from the AST Location varLoc = p.getLocation(); // Create an is_initial dot expression init = Utilities.createInitExp(new VarDec(p.getName(), p.getTy()), MTYPE, BOOLEAN); if (varLoc != null) { Location loc = (Location) varLoc.clone(); loc.setDetails("Initial Value for " + p.getName().getName()); Utilities.setLocation(init, loc); } } // Create an AND infix expression with the ensures clause if (ensures != null && !ensures.equals(myTypeGraph.getTrueVarExp())) { Location newEnsuresLoc = (Location) ensures.getLocation().clone(); ensures = myTypeGraph.formConjunct(ensures, init); ensures.setLocation(newEnsuresLoc); } // Make initialization expression the ensures clause else { ensures = init; } } // If the type is a type representation, then our requires clause // should really say something about the conceptual type and not // the variable if (ste instanceof RepresentationTypeEntry && !isLocal) { Exp conceptualExp = Utilities.createConcVarExp(opLocation, parameterExp, parameterExp.getMathType(), BOOLEAN); OldExp oldConceptualExp = new OldExp(opLocation, Exp.copy(conceptualExp)); ensures = Utilities.replace(ensures, parameterExp, conceptualExp); ensures = Utilities.replace(ensures, oldParameterExp, oldConceptualExp); } } else { // Ty not handled. Utilities.tyNotHandled(p.getTy(), p.getLocation()); } } return ensures; } /** * <p>Returns the ensures clause.</p> * * @param ensures The <code>Exp</code> containing the ensures clause. * @param opLocation The <code>Location</code> for the operation. * @param opName The name for the operation. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified ensures clause <code>Exp</code>. */ private Exp modifyEnsuresClause(Exp ensures, Location opLocation, String opName, boolean isLocal) { // Obtain the list of parameters for the current operation List<ParameterVarDec> parameterVarDecList; if (myCurrentOperationEntry.getDefiningElement() instanceof FacilityOperationDec) { parameterVarDecList = ((FacilityOperationDec) myCurrentOperationEntry .getDefiningElement()).getParameters(); } else { parameterVarDecList = ((OperationDec) myCurrentOperationEntry .getDefiningElement()).getParameters(); } // Modifies the existing ensures clause based on // the parameter modes. ensures = modifyEnsuresByParameter(ensures, opLocation, opName, parameterVarDecList, isLocal); return ensures; } /** * <p>Modifies the requires clause based on .</p> * * @param requires The <code>Exp</code> containing the requires clause. * * @return The modified requires clause <code>Exp</code>. */ private Exp modifyRequiresByGlobalMode(Exp requires) { return requires; } /** * <p>Modifies the requires clause based on the parameter mode.</p> * * @param requires The <code>Exp</code> containing the requires clause. * @param opLocation The <code>Location</code> for the operation. * @param opName The name for the operation. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified requires clause <code>Exp</code>. */ private Exp modifyRequiresByParameter(Exp requires, Location opLocation, String opName, boolean isLocal) { // Obtain the list of parameters List<ParameterVarDec> parameterVarDecList; if (myCurrentOperationEntry.getDefiningElement() instanceof FacilityOperationDec) { parameterVarDecList = ((FacilityOperationDec) myCurrentOperationEntry .getDefiningElement()).getParameters(); } else { parameterVarDecList = ((OperationDec) myCurrentOperationEntry .getDefiningElement()).getParameters(); } // Loop through each parameter for (ParameterVarDec p : parameterVarDecList) { ProgramTypeEntry typeEntry; // Ty is NameTy if (p.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) p.getTy(); PTType ptType = pNameTy.getProgramTypeValue(); // Only deal with actual types and don't deal // with entry types passed in to the concept realization if (!(ptType instanceof PTGeneric)) { // Convert p to a VarExp VarExp parameterExp = new VarExp(null, null, p.getName()); parameterExp.setMathType(pNameTy.getMathTypeValue()); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy.getQualifier(), pNameTy.getName(), myCurrentModuleScope); if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); } // Obtain the original dec from the AST VarExp exemplar = null; Exp constraint = null; if (typeEntry.getDefiningElement() instanceof TypeDec) { TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Obtain the exemplar in VarExp form exemplar = new VarExp(null, null, type.getExemplar()); exemplar.setMathType(pNameTy.getMathTypeValue()); // If we have a type representation, then there are no initialization // or constraint clauses. if (ste instanceof ProgramTypeEntry) { // Deep copy the constraint if (type.getConstraint() != null) { constraint = Exp.copy(type.getConstraint()); } } } // Other than the replaces mode, constraints for the // other parameter modes needs to be added // to the requires clause as conjuncts. if (p.getMode() != Mode.REPLACES) { if (constraint != null && !constraint.equals(myTypeGraph .getTrueVarExp())) { // Replace the formal with the actual if (exemplar != null) { constraint = Utilities.replace(constraint, exemplar, parameterExp); } // Set the details for the new location if (constraint.getLocation() != null) { Location constLoc; if (requires != null && requires.getLocation() != null) { Location reqLoc = requires.getLocation(); constLoc = ((Location) reqLoc.clone()); } else { // Append the name of the current procedure String details = ""; if (myCurrentOperationEntry != null) { details = " in Procedure " + myCurrentOperationEntry .getName(); } constLoc = ((Location) opLocation.clone()); constLoc.setDetails("Requires Clause of " + opName + details); } constLoc.setDetails(constLoc.getDetails() + " (Constraint from \"" + p.getMode().getModeName() + "\" parameter mode)"); constraint.setLocation(constLoc); } // Create an AND infix expression with the requires clause if (requires != null && !requires.equals(myTypeGraph .getTrueVarExp())) { requires = myTypeGraph.formConjunct(requires, constraint); requires.setLocation((Location) opLocation .clone()); } // Make constraint expression the requires clause else { requires = constraint; } } } // If the type is a type representation, then our requires clause // should really say something about the conceptual type and not // the variable if (ste instanceof RepresentationTypeEntry && !isLocal) { requires = Utilities.replace(requires, parameterExp, Utilities .createConcVarExp(opLocation, parameterExp, parameterExp .getMathType(), BOOLEAN)); } } // Add the current variable to our list of free variables myCurrentAssertiveCode.addFreeVar(Utilities.createVarExp(p .getLocation(), null, p.getName(), pNameTy .getMathTypeValue(), null)); } else { // Ty not handled. Utilities.tyNotHandled(p.getTy(), p.getLocation()); } } return requires; } /** * <p>Modifies the requires clause.</p> * * @param requires The <code>Exp</code> containing the requires clause. * @param opLocation The <code>Location</code> for the operation. * @param opName The name of the operation. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified requires clause <code>Exp</code>. */ private Exp modifyRequiresClause(Exp requires, Location opLocation, String opName, boolean isLocal) { // Modifies the existing requires clause based on // the parameter modes. requires = modifyRequiresByParameter(requires, opLocation, opName, isLocal); // Modifies the existing requires clause based on // the parameter modes. // TODO: Ask Murali what this means requires = modifyRequiresByGlobalMode(requires); return requires; } /** * <p>Replace the formal with the actual variables * inside the ensures clause.</p> * * @param ensures The ensures clause. * @param paramList The list of parameter variables. * @param stateVarList The list of state variables. * @param argList The list of arguments from the operation call. * @param isSimple Check if it is a simple replacement. * * @return The ensures clause in <code>Exp</code> form. */ private Exp replaceFormalWithActualEns(Exp ensures, List<ParameterVarDec> paramList, List<AffectsItem> stateVarList, List<Exp> argList, boolean isSimple) { // Current final confirm Exp newConfirm; // List to hold temp and real values of variables in case // of duplicate spec and real variables List<Exp> undRepList = new ArrayList<Exp>(); List<Exp> replList = new ArrayList<Exp>(); // Replace state variables in the ensures clause // and create new confirm statements if needed. for (int i = 0; i < stateVarList.size(); i++) { ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); newConfirm = confirmStmt.getAssertion(); AffectsItem stateVar = stateVarList.get(i); // Only deal with Alters/Reassigns/Replaces/Updates modes if (stateVar.getMode() == Mode.ALTERS || stateVar.getMode() == Mode.REASSIGNS || stateVar.getMode() == Mode.REPLACES || stateVar.getMode() == Mode.UPDATES) { // Obtain the variable from our free variable list Exp globalFreeVar = myCurrentAssertiveCode.getFreeVar(stateVar.getName(), true); if (globalFreeVar != null) { VarExp oldNamesVar = new VarExp(); oldNamesVar.setName(stateVar.getName()); // Create a local free variable if it is not there Exp localFreeVar = myCurrentAssertiveCode.getFreeVar(stateVar .getName(), false); if (localFreeVar == null) { // TODO: Don't have a type for state variables? localFreeVar = new VarExp(null, null, stateVar.getName()); localFreeVar = Utilities.createQuestionMarkVariable( myTypeGraph.formConjunct(ensures, newConfirm), (VarExp) localFreeVar); myCurrentAssertiveCode.addFreeVar(localFreeVar); } else { localFreeVar = Utilities.createQuestionMarkVariable( myTypeGraph.formConjunct(ensures, newConfirm), (VarExp) localFreeVar); } // Creating "#" expressions and replace these in the // ensures clause. OldExp osVar = new OldExp(null, Exp.copy(globalFreeVar)); OldExp oldNameOSVar = new OldExp(null, Exp.copy(oldNamesVar)); ensures = Utilities.replace(ensures, oldNamesVar, globalFreeVar); ensures = Utilities.replace(ensures, oldNameOSVar, osVar); // If it is not simple replacement, replace all ensures clauses // with the appropriate expressions. if (!isSimple) { ensures = Utilities.replace(ensures, globalFreeVar, localFreeVar); ensures = Utilities .replace(ensures, osVar, globalFreeVar); newConfirm = Utilities.replace(newConfirm, globalFreeVar, localFreeVar); } // Set newConfirm as our new final confirm statement myCurrentAssertiveCode.setFinalConfirm(newConfirm, confirmStmt.getSimplify()); } // Error: Why isn't it a free variable. else { Utilities.notInFreeVarList(stateVar.getName(), stateVar .getLocation()); } } } // Replace postcondition variables in the ensures clause for (int i = 0; i < argList.size(); i++) { ParameterVarDec varDec = paramList.get(i); Exp exp = argList.get(i); PosSymbol VDName = varDec.getName(); ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); newConfirm = confirmStmt.getAssertion(); // VarExp form of the parameter variable VarExp oldExp = new VarExp(null, null, VDName); oldExp.setMathType(exp.getMathType()); oldExp.setMathTypeValue(exp.getMathTypeValue()); // Convert the pExp into a something we can use Exp repl = Utilities.convertExp(exp); Exp undqRep = null, quesRep = null; OldExp oSpecVar, oRealVar; String replName = null; // Case #1: ProgramIntegerExp // Case #2: ProgramCharExp // Case #3: ProgramStringExp if (exp instanceof ProgramIntegerExp || exp instanceof ProgramCharExp || exp instanceof ProgramStringExp) { Exp convertExp = Utilities.convertExp(exp); if (exp instanceof ProgramIntegerExp) { replName = Integer.toString(((IntegerExp) convertExp) .getValue()); } else if (exp instanceof ProgramCharExp) { replName = Character.toString(((CharExp) convertExp) .getValue()); } else { replName = ((StringExp) convertExp).getValue(); } // Create a variable expression of the form "_?[Argument Name]" undqRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_?" + replName), exp .getMathType(), exp.getMathTypeValue()); // Create a variable expression of the form "?[Argument Name]" quesRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("?" + replName), exp .getMathType(), exp.getMathTypeValue()); } // Case #4: VariableDotExp else if (exp instanceof VariableDotExp) { if (repl instanceof DotExp) { Exp pE = ((DotExp) repl).getSegments().get(0); replName = pE.toString(0); // Create a variable expression of the form "_?[Argument Name]" undqRep = Exp.copy(repl); edu.clemson.cs.r2jt.collections.List<Exp> segList = ((DotExp) undqRep).getSegments(); VariableNameExp undqNameRep = new VariableNameExp(null, null, Utilities .createPosSymbol("_?" + replName)); undqNameRep.setMathType(pE.getMathType()); segList.set(0, undqNameRep); ((DotExp) undqRep).setSegments(segList); // Create a variable expression of the form "?[Argument Name]" quesRep = Exp.copy(repl); segList = ((DotExp) quesRep).getSegments(); segList.set(0, ((VariableDotExp) exp).getSegments().get(0)); ((DotExp) quesRep).setSegments(segList); } else if (repl instanceof VariableDotExp) { Exp pE = ((VariableDotExp) repl).getSegments().get(0); replName = pE.toString(0); // Create a variable expression of the form "_?[Argument Name]" undqRep = Exp.copy(repl); edu.clemson.cs.r2jt.collections.List<VariableExp> segList = ((VariableDotExp) undqRep).getSegments(); VariableNameExp undqNameRep = new VariableNameExp(null, null, Utilities .createPosSymbol("_?" + replName)); undqNameRep.setMathType(pE.getMathType()); segList.set(0, undqNameRep); ((VariableDotExp) undqRep).setSegments(segList); // Create a variable expression of the form "?[Argument Name]" quesRep = Exp.copy(repl); segList = ((VariableDotExp) quesRep).getSegments(); segList.set(0, ((VariableDotExp) exp).getSegments().get(0)); ((VariableDotExp) quesRep).setSegments(segList); } // Error: Case not handled! else { Utilities.expNotHandled(exp, exp.getLocation()); } } // Case #5: VariableNameExp else if (exp instanceof VariableNameExp) { // Name of repl in string form replName = ((VariableNameExp) exp).getName().getName(); // Create a variable expression of the form "_?[Argument Name]" undqRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_?" + replName), exp .getMathType(), exp.getMathTypeValue()); // Create a variable expression of the form "?[Argument Name]" quesRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("?" + replName), exp .getMathType(), exp.getMathTypeValue()); } // Case #6: Result from a nested function call else { // Name of repl in string form replName = varDec.getName().getName(); // Create a variable expression of the form "_?[Argument Name]" undqRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_?" + replName), exp .getMathType(), exp.getMathTypeValue()); // Create a variable expression of the form "?[Argument Name]" quesRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("?" + replName), exp .getMathType(), exp.getMathTypeValue()); } // "#" versions of oldExp and repl oSpecVar = new OldExp(null, Exp.copy(oldExp)); oRealVar = new OldExp(null, Exp.copy(repl)); // Nothing can be null! if (oldExp != null && quesRep != null && oSpecVar != null && repl != null && oRealVar != null) { // Alters, Clears, Reassigns, Replaces, Updates if (varDec.getMode() == Mode.ALTERS || varDec.getMode() == Mode.CLEARS || varDec.getMode() == Mode.REASSIGNS || varDec.getMode() == Mode.REPLACES || varDec.getMode() == Mode.UPDATES) { Exp quesVar; // Obtain the free variable VarExp freeVar = (VarExp) myCurrentAssertiveCode.getFreeVar( Utilities.createPosSymbol(replName), false); if (freeVar == null) { freeVar = Utilities .createVarExp( varDec.getLocation(), null, Utilities .createPosSymbol(replName), varDec.getTy() .getMathTypeValue(), null); } // Apply the question mark to the free variable freeVar = Utilities .createQuestionMarkVariable(myTypeGraph .formConjunct(ensures, newConfirm), freeVar); if (exp instanceof ProgramDotExp || exp instanceof VariableDotExp) { // Make a copy from repl quesVar = Exp.copy(repl); // Replace the free variable in the question mark variable as the first element // in the dot expression. VarExp tmpVar = new VarExp(null, null, freeVar.getName()); tmpVar.setMathType(myTypeGraph.BOOLEAN); edu.clemson.cs.r2jt.collections.List<Exp> segs = ((DotExp) quesVar).getSegments(); segs.set(0, tmpVar); ((DotExp) quesVar).setSegments(segs); } else { // Create a variable expression from free variable quesVar = new VarExp(null, null, freeVar.getName()); quesVar.setMathType(freeVar.getMathType()); quesVar.setMathTypeValue(freeVar.getMathTypeValue()); } // Add the new free variable to free variable list myCurrentAssertiveCode.addFreeVar(freeVar); // Check if our ensures clause has the parameter variable in it. if (ensures.containsVar(VDName.getName(), true) || ensures.containsVar(VDName.getName(), false)) { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, undqRep); ensures = Utilities.replace(ensures, oSpecVar, repl); // Add it to our list of variables to be replaced later undRepList.add(undqRep); replList.add(quesVar); } else { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, quesRep); ensures = Utilities.replace(ensures, oSpecVar, repl); } // Update our final confirm with the parameter argument newConfirm = Utilities.replace(newConfirm, repl, quesVar); myCurrentAssertiveCode.setFinalConfirm(newConfirm, confirmStmt.getSimplify()); } // All other modes else { // Check if our ensures clause has the parameter variable in it. if (ensures.containsVar(VDName.getName(), true) || ensures.containsVar(VDName.getName(), false)) { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, undqRep); ensures = Utilities.replace(ensures, oSpecVar, undqRep); // Add it to our list of variables to be replaced later undRepList.add(undqRep); replList.add(repl); } else { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, repl); ensures = Utilities.replace(ensures, oSpecVar, repl); } } } } // Replace the temp values with the actual values for (int i = 0; i < undRepList.size(); i++) { ensures = Utilities.replace(ensures, undRepList.get(i), replList .get(i)); } return ensures; } /** * <p>Replace the formal with the actual variables * inside the requires clause.</p> * * @param requires The requires clause. * @param paramList The list of parameter variables. * @param argList The list of arguments from the operation call. * * @return The requires clause in <code>Exp</code> form. */ private Exp replaceFormalWithActualReq(Exp requires, List<ParameterVarDec> paramList, List<Exp> argList) { // List to hold temp and real values of variables in case // of duplicate spec and real variables List<Exp> undRepList = new ArrayList<Exp>(); List<Exp> replList = new ArrayList<Exp>(); // Replace precondition variables in the requires clause for (int i = 0; i < argList.size(); i++) { ParameterVarDec varDec = paramList.get(i); Exp exp = argList.get(i); // Convert the pExp into a something we can use Exp repl = Utilities.convertExp(exp); // VarExp form of the parameter variable VarExp oldExp = Utilities.createVarExp(null, null, varDec.getName(), exp .getMathType(), exp.getMathTypeValue()); // New VarExp VarExp newExp = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_" + varDec.getName().getName()), repl.getMathType(), repl.getMathTypeValue()); // Replace the old with the new in the requires clause requires = Utilities.replace(requires, oldExp, newExp); // Add it to our list undRepList.add(newExp); replList.add(repl); } // Replace the temp values with the actual values for (int i = 0; i < undRepList.size(); i++) { requires = Utilities.replace(requires, undRepList.get(i), replList .get(i)); } return requires; } /** * <p>Simplify the assume statement where possible.</p> * * @param stmt The assume statement we want to simplify. * @param exp The current expression we are dealing with. * * @return The modified expression in <code>Exp/code> form. */ private Exp simplifyAssumeRule(AssumeStmt stmt, Exp exp) { // Variables Exp assumeExp = stmt.getAssertion(); List<Exp> assumeExpList = Utilities.splitConjunctExp(assumeExp, new ArrayList<Exp>()); for (int i = 0; i < assumeExpList.size(); i++) { Exp currentExp = assumeExpList.get(i); } // EqualsExp if (assumeExp instanceof EqualsExp) { EqualsExp equalsExp = (EqualsExp) assumeExp; // Do simplifications if we have an equals if (equalsExp.getOperator() == EqualsExp.EQUAL) { // Check to see if the left hand side is an expression // we can replace. if (Utilities.containsReplaceableExp(equalsExp.getLeft())) { // Create a temp expression where left is replaced with the right Exp tmp = Utilities.replace(exp, equalsExp.getLeft(), equalsExp.getRight()); // If tmp hasn't changed, then check to see if the right hand side // is an expression we can replace. if (tmp.equals(exp) && (Utilities.containsReplaceableExp(equalsExp .getRight()))) { tmp = Utilities.replace(exp, equalsExp.getRight(), equalsExp.getLeft()); } // Update exp if we did a replacement if (!tmp.equals(exp)) { exp = tmp; // If this is not a stipulate assume clause, // we can safely get rid of it, otherwise we keep it. if (!stmt.getIsStipulate()) { assumeExp = null; } } } } } // InfixExp else if (assumeExp instanceof InfixExp) { InfixExp infixExp = (InfixExp) assumeExp; // Only do simplifications if we have an and operator if (infixExp.getOpName().equals("and")) { // Recursively call simplify on the left and on the right AssumeStmt left = new AssumeStmt(stmt.getLocation(), Exp.copy(infixExp .getLeft()), stmt.getIsStipulate()); AssumeStmt right = new AssumeStmt(stmt.getLocation(), Exp.copy(infixExp .getRight()), stmt.getIsStipulate()); exp = simplifyAssumeRule(left, exp); exp = simplifyAssumeRule(right, exp); // Case #1: Nothing on the left and nothing on the right if (left.getAssertion() == null && right.getAssertion() == null) { assumeExp = null; } // Case #2: Both still have assertions else if (left.getAssertion() != null && right.getAssertion() != null) { assumeExp = myTypeGraph.formConjunct(left.getAssertion(), right .getAssertion()); } // Case #3: Left still has assertions else if (left.getAssertion() != null) { assumeExp = left.getAssertion(); } // Case #4: Right still has assertions else { assumeExp = right.getAssertion(); } } } // Store the new assertion stmt.setAssertion(assumeExp); return exp; } // ----------------------------------------------------------- // Proof Rules // ----------------------------------------------------------- /** * <p>Applies the assume rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>AssumeStmt</code>. */ private void applyAssumeStmtRule(AssumeStmt stmt) { // Check to see if our assertion just has "True" Exp assertion = stmt.getAssertion(); if (assertion instanceof VarExp && assertion.equals(myTypeGraph.getTrueVarExp())) { // Verbose Mode Debug Messages myVCBuffer.append("\nAssume Rule Applied and Simplified: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Apply simplification ConfirmStmt finalConfirm = myCurrentAssertiveCode.getFinalConfirm(); boolean simplify = finalConfirm.getSimplify(); Exp currentFinalConfirm = simplifyAssumeRule(stmt, finalConfirm.getAssertion()); // Only create an implies expression if the goal is not just "true". // If the goal is "true", then simplify should be true as well. if (stmt.getAssertion() != null && !simplify) { // Create a new implies expression currentFinalConfirm = myTypeGraph.formImplies(stmt.getAssertion(), currentFinalConfirm); } // Set this as our new final confirm myCurrentAssertiveCode.setFinalConfirm(currentFinalConfirm, simplify); // Verbose Mode Debug Messages myVCBuffer.append("\nAssume Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } } /** * <p>Applies the change rule.</p> * * @param change The change clause */ private void applyChangeRule(VerificationStatement change) { List<VariableExp> changeList = (List<VariableExp>) change.getAssertion(); ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp finalConfirm = confirmStmt.getAssertion(); // Loop through each variable for (VariableExp v : changeList) { // v is an instance of VariableNameExp if (v instanceof VariableNameExp) { VariableNameExp vNameExp = (VariableNameExp) v; // Create VarExp for vNameExp VarExp vExp = Utilities.createVarExp(vNameExp.getLocation(), vNameExp .getQualifier(), vNameExp.getName(), vNameExp .getMathType(), vNameExp.getMathTypeValue()); // Create a new question mark variable VarExp newV = Utilities .createQuestionMarkVariable(finalConfirm, vExp); // Add this new variable to our list of free variables myCurrentAssertiveCode.addFreeVar(newV); // Replace all instances of vExp with newV finalConfirm = Utilities.replace(finalConfirm, vExp, newV); } } // Set the modified statement as our new final confirm myCurrentAssertiveCode.setFinalConfirm(finalConfirm, confirmStmt .getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nChange Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the call statement rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>CallStmt</code>. */ private void applyCallStmtRule(CallStmt stmt) { // Call a method to locate the operation dec for this call OperationDec opDec = getOperationDec(stmt.getLocation(), stmt.getQualifier(), stmt .getName(), stmt.getArguments()); boolean isLocal = Utilities.isLocationOperation(stmt.getName().getName(), myCurrentModuleScope); // Get the ensures clause for this operation // Note: If there isn't an ensures clause, it is set to "True" Exp ensures; if (opDec.getEnsures() != null) { ensures = Exp.copy(opDec.getEnsures()); } else { ensures = myTypeGraph.getTrueVarExp(); } // Get the requires clause for this operation Exp requires; boolean simplify = false; if (opDec.getRequires() != null) { requires = Exp.copy(opDec.getRequires()); // Simplify if we just have true if (requires.isLiteralTrue()) { simplify = true; } } else { requires = myTypeGraph.getTrueVarExp(); simplify = true; } // Find all the replacements that needs to happen to the requires // and ensures clauses List<ProgramExp> callArgs = stmt.getArguments(); List<Exp> replaceArgs = modifyArgumentList(callArgs); // Modify ensures using the parameter modes ensures = modifyEnsuresByParameter(ensures, stmt.getLocation(), opDec .getName().getName(), opDec.getParameters(), isLocal); // Replace PreCondition variables in the requires clause requires = replaceFormalWithActualReq(requires, opDec.getParameters(), replaceArgs); // Replace PostCondition variables in the ensures clause ensures = replaceFormalWithActualEns(ensures, opDec.getParameters(), opDec.getStateVars(), replaceArgs, false); // NY YS // Duration for CallStmt if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = (Location) stmt.getLocation().clone(); ConfirmStmt finalConfirm = myCurrentAssertiveCode.getFinalConfirm(); Exp finalConfirmExp = finalConfirm.getAssertion(); // Obtain the corresponding OperationProfileEntry List<PTType> argTypes = new LinkedList<PTType>(); for (ProgramExp arg : stmt.getArguments()) { argTypes.add(arg.getProgramType()); } OperationProfileEntry ope = Utilities.searchOperationProfile(loc, stmt.getQualifier(), stmt.getName(), argTypes, myCurrentModuleScope); // Add the profile ensures as additional assume Exp profileEnsures = ope.getEnsuresClause(); if (profileEnsures != null) { profileEnsures = replaceFormalWithActualEns(profileEnsures, opDec .getParameters(), opDec.getStateVars(), replaceArgs, false); // Obtain the current location if (stmt.getName().getLocation() != null) { // Set the details of the current location Location ensuresLoc = (Location) loc.clone(); ensuresLoc.setDetails("Ensures Clause of " + opDec.getName() + " from Profile " + ope.getName()); Utilities.setLocation(profileEnsures, ensuresLoc); } ensures = myTypeGraph.formConjunct(ensures, profileEnsures); } // Construct the Duration Clause Exp opDur = Exp.copy(ope.getDurationClause()); // Replace PostCondition variables in the duration clause opDur = replaceFormalWithActualEns(opDur, opDec.getParameters(), opDec.getStateVars(), replaceArgs, false); VarExp cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(finalConfirmExp)), myTypeGraph.R, null); Exp durCallExp = Utilities.createDurCallExp((Location) loc.clone(), Integer .toString(opDec.getParameters().size()), Z, myTypeGraph.R); InfixExp sumEvalDur = new InfixExp((Location) loc.clone(), opDur, Utilities .createPosSymbol("+"), durCallExp); sumEvalDur.setMathType(myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), sumEvalDur); sumEvalDur.setMathType(myTypeGraph.R); // For any evaluates mode expression, we need to finalize the variable edu.clemson.cs.r2jt.collections.List<ProgramExp> assignExpList = stmt.getArguments(); for (int i = 0; i < assignExpList.size(); i++) { ParameterVarDec p = opDec.getParameters().get(i); VariableExp pExp = (VariableExp) assignExpList.get(i); if (p.getMode() == Mode.EVALUATES) { VarDec v = new VarDec(Utilities.getVarName(pExp), p.getTy()); FunctionExp finalDur = Utilities.createFinalizAnyDur(v, myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), sumEvalDur, Utilities.createPosSymbol("+"), finalDur); sumEvalDur.setMathType(myTypeGraph.R); } } // Replace Cum_Dur in our final ensures clause finalConfirmExp = Utilities.replace(finalConfirmExp, cumDur, sumEvalDur); myCurrentAssertiveCode.setFinalConfirm(finalConfirmExp, finalConfirm.getSimplify()); } // Modify the location of the requires clause and add it to myCurrentAssertiveCode if (requires != null) { // Obtain the current location // Note: If we don't have a location, we create one Location loc; if (stmt.getName().getLocation() != null) { loc = (Location) stmt.getName().getLocation().clone(); } else { loc = new Location(null, null); } // Append the name of the current procedure String details = ""; if (myCurrentOperationEntry != null) { details = " in Procedure " + myCurrentOperationEntry.getName(); } // Set the details of the current location loc.setDetails("Requires Clause of " + opDec.getName() + details); Utilities.setLocation(requires, loc); // Add this to our list of things to confirm myCurrentAssertiveCode.addConfirm((Location) loc.clone(), requires, simplify); } // Modify the location of the requires clause and add it to myCurrentAssertiveCode if (ensures != null) { // Obtain the current location Location loc = null; if (stmt.getName().getLocation() != null) { // Set the details of the current location loc = (Location) stmt.getName().getLocation().clone(); loc.setDetails("Ensures Clause of " + opDec.getName()); Utilities.setLocation(ensures, loc); } // Add this to our list of things to assume myCurrentAssertiveCode.addAssume(loc, ensures, false); } // Verbose Mode Debug Messages myVCBuffer.append("\nOperation Call Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies different rules to code statements.</p> * * @param statement The different statements. */ private void applyCodeRules(Statement statement) { // Apply each statement rule here. if (statement instanceof AssumeStmt) { applyAssumeStmtRule((AssumeStmt) statement); } else if (statement instanceof CallStmt) { applyCallStmtRule((CallStmt) statement); } else if (statement instanceof ConfirmStmt) { applyConfirmStmtRule((ConfirmStmt) statement); } else if (statement instanceof FuncAssignStmt) { applyFuncAssignStmtRule((FuncAssignStmt) statement); } else if (statement instanceof IfStmt) { applyIfStmtRule((IfStmt) statement); } else if (statement instanceof MemoryStmt) { // TODO: Deal with Forget if (((MemoryStmt) statement).isRemember()) { applyRememberRule(); } } else if (statement instanceof SwapStmt) { applySwapStmtRule((SwapStmt) statement); } else if (statement instanceof WhileStmt) { applyWhileStmtRule((WhileStmt) statement); } } /** * <p>Applies the confirm rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>ConfirmStmt</code>. */ private void applyConfirmStmtRule(ConfirmStmt stmt) { // Check to see if our assertion can be simplified Exp assertion = stmt.getAssertion(); if (stmt.getSimplify()) { // Verbose Mode Debug Messages myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Obtain the current final confirm statement ConfirmStmt currentFinalConfirm = myCurrentAssertiveCode.getFinalConfirm(); // Check to see if we can simplify the final confirm if (currentFinalConfirm.getSimplify()) { // Obtain the current location if (assertion.getLocation() != null) { // Set the details of the current location Location loc = (Location) assertion.getLocation().clone(); Utilities.setLocation(assertion, loc); } myCurrentAssertiveCode.setFinalConfirm(assertion, stmt .getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Create a new and expression InfixExp newConf = myTypeGraph.formConjunct(assertion, currentFinalConfirm .getAssertion()); // Set this new expression as the new final confirm myCurrentAssertiveCode.setFinalConfirm(newConf, false); // Verbose Mode Debug Messages myVCBuffer.append("\nConfirm Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } } } /** * <p>Applies the correspondence rule.</p> * * @param dec Representation declaration object. */ private void applyCorrespondenceRule(RepresentationDec dec) { // Create a new assertive code to hold the correspondence VCs AssertiveCode assertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Obtain the location for each assume clause Location decLoc = dec.getLocation(); // Add the global constraints as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalConstraintExp, false); // Add the global require clause as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalRequiresExp, false); // Add the convention as given assertiveCode.addAssume((Location) decLoc.clone(), dec.getConvention(), false); // Add the correspondence as given myCorrespondenceExp = dec.getCorrespondence(); assertiveCode.addAssume((Location) decLoc.clone(), myCorrespondenceExp, false); // Search for the type we are implementing SymbolTableEntry ste = Utilities.searchProgramType(dec.getLocation(), null, dec .getName(), myCurrentModuleScope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(dec.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry(dec.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type .getExemplar(), typeEntry.getModelType(), null); DotExp conceptualVar = Utilities.createConcVarExp(null, exemplar, typeEntry .getModelType(), BOOLEAN); // Make sure we have a constraint Exp constraint; if (type.getConstraint() == null) { constraint = myTypeGraph.getTrueVarExp(); } else { constraint = Exp.copy(type.getConstraint()); } constraint = Utilities.replace(constraint, exemplar, conceptualVar); // Set the location for the constraint Location loc; if (myCorrespondenceExp.getLocation() != null) { loc = (Location) myCorrespondenceExp.getLocation().clone(); } else { loc = (Location) type.getLocation().clone(); } loc.setDetails("Well Defined Correspondence for " + dec.getName().getName()); Utilities.setLocation(constraint, loc); // We need to make sure the constraints for the type we are // implementing is met. boolean simplify = false; // Simplify if we just have true if (constraint.isLiteralTrue()) { simplify = true; } assertiveCode.setFinalConfirm(constraint, simplify); // Add the constraints for the implementing facility // or for each of the fields inside the record. Exp fieldConstraints = myTypeGraph.getTrueVarExp(); if (dec.getRepresentation() instanceof NameTy) { NameTy ty = (NameTy) dec.getRepresentation(); fieldConstraints = Utilities.retrieveConstraint(ty.getLocation(), ty .getQualifier(), ty.getName(), exemplar, myCurrentModuleScope); } else { RecordTy ty = (RecordTy) dec.getRepresentation(); // Find the constraints for each field inside the record. for (VarDec v : ty.getFields()) { NameTy vTy = (NameTy) v.getTy(); // Create the name of the variable VarExp vName = Utilities.createVarExp(null, null, v.getName(), vTy .getMathType(), vTy.getMathTypeValue()); // Create [Exemplar].[v] dotted expression edu.clemson.cs.r2jt.collections.List<Exp> dotExpList = new edu.clemson.cs.r2jt.collections.List<Exp>(); dotExpList.add(exemplar); dotExpList.add(vName); DotExp varNameExp = Utilities.createDotExp(v.getLocation(), dotExpList, v.getMathType()); Exp vConstraint = Utilities.retrieveConstraint(vTy.getLocation(), vTy .getQualifier(), vTy.getName(), varNameExp, myCurrentModuleScope); if (fieldConstraints.isLiteralTrue()) { fieldConstraints = vConstraint; } else { fieldConstraints = myTypeGraph.formConjunct(fieldConstraints, vConstraint); } } } // Only add the field constraints if we don't have true if (!fieldConstraints.isLiteralTrue()) { assertiveCode.addAssume(loc, fieldConstraints, false); } } // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(assertiveCode); // Verbose Mode Debug Messages String newString = "\n========================= Type Representation Name:\t" + dec.getName().getName() + " =========================\n"; newString += "\nCorrespondence Rule Applied: \n"; newString += assertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } /** * <p>Applies the facility declaration rule.</p> * * @param dec Facility declaration object. */ private void applyFacilityDeclRule(FacilityDec dec) { // Create a new assertive code to hold the facility declaration VCs AssertiveCode assertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Location for the assume clauses Location decLoc = dec.getLocation(); // Add the global constraints as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalConstraintExp, false); // Add the global require clause as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalRequiresExp, false); // TODO: Loop through every enhancement/enhancement realization declaration, if any. // Obtain the concept module for the facility try { ConceptModuleDec facConceptDec = (ConceptModuleDec) mySymbolTable .getModuleScope( new ModuleIdentifier(dec.getConceptName() .getName())).getDefiningElement(); // Concept parameters List<ModuleArgumentItem> conceptParams = dec.getConceptParams(); // Concept requires clause Exp req = getRequiresClause(facConceptDec.getLocation(), facConceptDec); Location loc = (Location) dec.getName().getLocation().clone(); loc.setDetails("Facility Declaration Rule"); req = Utilities.replaceFacilityDeclarationVariables(req, facConceptDec.getParameters(), conceptParams); req.setLocation(loc); boolean simplify = false; // Simplify if we just have true if (req.isLiteralTrue()) { simplify = true; } assertiveCode.setFinalConfirm(req, simplify); // Obtain the constraint of the concept type Exp assumeExp = null; // TODO: This is ugly! Need to clean this up! List<ModuleParameterDec> moduleParameterList = facConceptDec.getParameters(); List<EqualsExp> formalToActualList = new LinkedList<EqualsExp>(); for (int i = 0; i < moduleParameterList.size(); i++) { ModuleParameterDec m = moduleParameterList.get(i); if (m.getWrappedDec() instanceof ConstantParamDec) { ConstantParamDec constantParamDec = (ConstantParamDec) m.getWrappedDec(); VarDec tempDec = new VarDec(constantParamDec.getName(), constantParamDec.getTy()); // Search for the ProgramTypeEntry // Ty is NameTy if (tempDec.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) tempDec.getTy(); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities .searchProgramType(pNameTy .getLocation(), pNameTy .getQualifier(), pNameTy .getName(), myCurrentModuleScope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy .getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); } // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the declared variable VarExp varDecExp = Utilities.createVarExp(tempDec.getLocation(), null, tempDec.getName(), typeEntry .getModelType(), null); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type.getExemplar(), typeEntry .getModelType(), null); // Make sure we have a constraint Exp constraint; if (type.getConstraint() == null) { constraint = myTypeGraph.getTrueVarExp(); } else { constraint = Exp.copy(type.getConstraint()); } constraint = Utilities.replace(constraint, exemplar, varDecExp); // Set the location for the constraint Location constraintLoc; if (constraint.getLocation() != null) { constraintLoc = (Location) constraint.getLocation().clone(); } else { constraintLoc = (Location) type.getLocation().clone(); } constraintLoc.setDetails("Constraints on " + tempDec.getName().getName()); Utilities.setLocation(constraint, constraintLoc); // Replace with facility declaration variables constraint = Utilities .replaceFacilityDeclarationVariables( constraint, facConceptDec .getParameters(), conceptParams); if (assumeExp == null) { assumeExp = constraint; } else { assumeExp = myTypeGraph.formConjunct(assumeExp, constraint); } // TODO: Change this! This is such a hack! // Create an equals expression from formal to actual Exp actualExp; if (conceptParams.get(i).getEvalExp() != null) { actualExp = Utilities.convertExp(conceptParams.get(i) .getEvalExp()); } else { actualExp = Exp.copy(varDecExp); } EqualsExp formalEq = new EqualsExp(dec.getLocation(), varDecExp, 1, actualExp); formalEq.setMathType(BOOLEAN); formalToActualList.add(formalEq); } else { // Ty not handled. Utilities.tyNotHandled(tempDec.getTy(), tempDec .getLocation()); } } } // Make sure it is not null if (assumeExp == null) { assumeExp = myTypeGraph.getTrueVarExp(); } myFacilityDeclarationMap.put(dec, assumeExp); myFacilityFormalActualMap.put(dec, formalToActualList); } catch (NoSuchSymbolException e) { Utilities.noSuchModule(dec.getLocation()); } // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(assertiveCode); // Verbose Mode Debug Messages String newString = "\n========================= Facility Dec Name:\t" + dec.getName().getName() + " =========================\n"; newString += "\nFacility Declaration Rule Applied: \n"; newString += assertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } /** * <p>Applies the function assignment rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>FuncAssignStmt</code>. */ private void applyFuncAssignStmtRule(FuncAssignStmt stmt) { PosSymbol qualifier = null; ProgramExp assignExp = stmt.getAssign(); ProgramParamExp assignParamExp = null; // Replace all instances of the variable on the left hand side // in the ensures clause with the expression on the right. Exp leftVariable; // We have a variable inside a record as the variable being assigned. if (stmt.getVar() instanceof VariableDotExp) { VariableDotExp v = (VariableDotExp) stmt.getVar(); List<VariableExp> vList = v.getSegments(); edu.clemson.cs.r2jt.collections.List<Exp> newSegments = new edu.clemson.cs.r2jt.collections.List<Exp>(); // Loot through each variable expression and add it to our dot list for (VariableExp vr : vList) { VarExp varExp = new VarExp(); if (vr instanceof VariableNameExp) { varExp.setName(((VariableNameExp) vr).getName()); varExp.setMathType(vr.getMathType()); varExp.setMathTypeValue(vr.getMathTypeValue()); newSegments.add(varExp); } } // Expression to be replaced leftVariable = new DotExp(v.getLocation(), newSegments, null); leftVariable.setMathType(v.getMathType()); leftVariable.setMathTypeValue(v.getMathTypeValue()); } // We have a regular variable being assigned. else { // Expression to be replaced VariableNameExp v = (VariableNameExp) stmt.getVar(); leftVariable = new VarExp(v.getLocation(), null, v.getName()); leftVariable.setMathType(v.getMathType()); leftVariable.setMathTypeValue(v.getMathTypeValue()); } // Simply replace the numbers/characters/strings if (assignExp instanceof ProgramIntegerExp || assignExp instanceof ProgramCharExp || assignExp instanceof ProgramStringExp) { Exp replaceExp = Utilities.convertExp(assignExp); // Replace all instances of the left hand side // variable in the current final confirm statement. ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp newConf = confirmStmt.getAssertion(); newConf = Utilities.replace(newConf, leftVariable, replaceExp); // Set this as our new final confirm statement. myCurrentAssertiveCode.setFinalConfirm(newConf, confirmStmt .getSimplify()); } else { // Check to see what kind of expression is on the right hand side if (assignExp instanceof ProgramParamExp) { // Cast to a ProgramParamExp assignParamExp = (ProgramParamExp) assignExp; } else if (assignExp instanceof ProgramDotExp) { // Cast to a ProgramParamExp ProgramDotExp dotExp = (ProgramDotExp) assignExp; assignParamExp = (ProgramParamExp) dotExp.getExp(); qualifier = dotExp.getQualifier(); } // Call a method to locate the operation dec for this call OperationDec opDec = getOperationDec(stmt.getLocation(), qualifier, assignParamExp.getName(), assignParamExp .getArguments()); // Check for recursive call of itself if (myCurrentOperationEntry != null && myCurrentOperationEntry.getName().equals( opDec.getName().getName()) && myCurrentOperationEntry.getReturnType() != null) { // Create a new confirm statement using P_val and the decreasing clause VarExp pVal = Utilities.createPValExp(myOperationDecreasingExp .getLocation(), myCurrentModuleScope); // Create a new infix expression IntegerExp oneExp = new IntegerExp(); oneExp.setValue(1); oneExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp leftExp = new InfixExp(stmt.getLocation(), oneExp, Utilities .createPosSymbol("+"), Exp .copy(myOperationDecreasingExp)); leftExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp exp = Utilities.createLessThanEqExp(stmt.getLocation(), leftExp, pVal, BOOLEAN); // Create the new confirm statement Location loc; if (myOperationDecreasingExp.getLocation() != null) { loc = (Location) myOperationDecreasingExp.getLocation() .clone(); } else { loc = (Location) stmt.getLocation().clone(); } loc.setDetails("Show Termination of Recursive Call"); Utilities.setLocation(exp, loc); ConfirmStmt conf = new ConfirmStmt(loc, exp, false); // Add it to our list of assertions myCurrentAssertiveCode.addCode(conf); } // Get the requires clause for this operation Exp requires; boolean simplify = false; if (opDec.getRequires() != null) { requires = Exp.copy(opDec.getRequires()); // Simplify if we just have true if (requires.isLiteralTrue()) { simplify = true; } } else { requires = myTypeGraph.getTrueVarExp(); simplify = true; } // Find all the replacements that needs to happen to the requires // and ensures clauses List<ProgramExp> callArgs = assignParamExp.getArguments(); List<Exp> replaceArgs = modifyArgumentList(callArgs); // Replace PreCondition variables in the requires clause requires = replaceFormalWithActualReq(requires, opDec.getParameters(), replaceArgs); // Modify the location of the requires clause and add it to myCurrentAssertiveCode // Obtain the current location // Note: If we don't have a location, we create one Location reqloc; if (assignParamExp.getName().getLocation() != null) { reqloc = (Location) assignParamExp.getName().getLocation() .clone(); } else { reqloc = new Location(null, null); } // Append the name of the current procedure String details = ""; if (myCurrentOperationEntry != null) { details = " in Procedure " + myCurrentOperationEntry.getName(); } // Set the details of the current location reqloc .setDetails("Requires Clause of " + opDec.getName() + details); Utilities.setLocation(requires, reqloc); // Add this to our list of things to confirm myCurrentAssertiveCode.addConfirm((Location) reqloc.clone(), requires, simplify); // Get the ensures clause for this operation // Note: If there isn't an ensures clause, it is set to "True" Exp ensures, opEnsures; if (opDec.getEnsures() != null) { opEnsures = Exp.copy(opDec.getEnsures()); // Make sure we have an EqualsExp, else it is an error. if (opEnsures instanceof EqualsExp) { // Has to be a VarExp on the left hand side (containing the name // of the function operation) if (((EqualsExp) opEnsures).getLeft() instanceof VarExp) { VarExp leftExp = (VarExp) ((EqualsExp) opEnsures).getLeft(); // Check if it has the name of the operation if (leftExp.getName().equals(opDec.getName())) { ensures = ((EqualsExp) opEnsures).getRight(); // Obtain the current location if (assignParamExp.getName().getLocation() != null) { // Set the details of the current location Location loc = (Location) assignParamExp.getName() .getLocation().clone(); loc.setDetails("Ensures Clause of " + opDec.getName()); Utilities.setLocation(ensures, loc); } // Replace the formal with the actual ensures = replaceFormalWithActualEns(ensures, opDec .getParameters(), opDec .getStateVars(), replaceArgs, true); // Replace all instances of the left hand side // variable in the current final confirm statement. ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp newConf = confirmStmt.getAssertion(); newConf = Utilities.replace(newConf, leftVariable, ensures); // Set this as our new final confirm statement. myCurrentAssertiveCode.setFinalConfirm(newConf, confirmStmt.getSimplify()); // NY YS // Duration for CallStmt if (myInstanceEnvironment.flags .isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = (Location) stmt.getLocation().clone(); ConfirmStmt finalConfirm = myCurrentAssertiveCode .getFinalConfirm(); Exp finalConfirmExp = finalConfirm.getAssertion(); // Obtain the corresponding OperationProfileEntry List<PTType> argTypes = new LinkedList<PTType>(); for (ProgramExp arg : assignParamExp .getArguments()) { argTypes.add(arg.getProgramType()); } OperationProfileEntry ope = Utilities.searchOperationProfile(loc, qualifier, assignParamExp .getName(), argTypes, myCurrentModuleScope); // Add the profile ensures as additional assume Exp profileEnsures = ope.getEnsuresClause(); if (profileEnsures != null) { profileEnsures = replaceFormalWithActualEns( profileEnsures, opDec .getParameters(), opDec.getStateVars(), replaceArgs, false); // Obtain the current location if (assignParamExp.getLocation() != null) { // Set the details of the current location Location ensuresLoc = (Location) loc.clone(); ensuresLoc .setDetails("Ensures Clause of " + opDec.getName() + " from Profile " + ope.getName()); Utilities.setLocation(profileEnsures, ensuresLoc); } finalConfirmExp = myTypeGraph.formConjunct( finalConfirmExp, profileEnsures); } // Construct the Duration Clause Exp opDur = Exp.copy(ope.getDurationClause()); // Replace PostCondition variables in the duration clause opDur = replaceFormalWithActualEns(opDur, opDec .getParameters(), opDec .getStateVars(), replaceArgs, false); VarExp cumDur = Utilities .createVarExp( (Location) loc.clone(), null, Utilities .createPosSymbol(Utilities .getCumDur(finalConfirmExp)), myTypeGraph.R, null); Exp durCallExp = Utilities .createDurCallExp( (Location) loc.clone(), Integer .toString(opDec .getParameters() .size()), Z, myTypeGraph.R); InfixExp sumEvalDur = new InfixExp((Location) loc.clone(), opDur, Utilities .createPosSymbol("+"), durCallExp); sumEvalDur.setMathType(myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities .createPosSymbol("+"), sumEvalDur); sumEvalDur.setMathType(myTypeGraph.R); // For any evaluates mode expression, we need to finalize the variable edu.clemson.cs.r2jt.collections.List<ProgramExp> assignExpList = assignParamExp.getArguments(); for (int i = 0; i < assignExpList.size(); i++) { ParameterVarDec p = opDec.getParameters().get(i); VariableExp pExp = (VariableExp) assignExpList.get(i); if (p.getMode() == Mode.EVALUATES) { VarDec v = new VarDec(Utilities .getVarName(pExp), p .getTy()); FunctionExp finalDur = Utilities.createFinalizAnyDur( v, myTypeGraph.R); sumEvalDur = new InfixExp( (Location) loc.clone(), sumEvalDur, Utilities .createPosSymbol("+"), finalDur); sumEvalDur.setMathType(myTypeGraph.R); } } // Add duration of assignment and finalize the temporary variable Exp assignDur = Utilities.createVarExp((Location) loc .clone(), null, Utilities .createPosSymbol("Dur_Assgn"), myTypeGraph.R, null); sumEvalDur = new InfixExp((Location) loc.clone(), sumEvalDur, Utilities .createPosSymbol("+"), assignDur); sumEvalDur.setMathType(myTypeGraph.R); Exp finalExpDur = Utilities.createFinalizAnyDurExp(stmt .getVar(), myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), sumEvalDur, Utilities .createPosSymbol("+"), finalExpDur); sumEvalDur.setMathType(myTypeGraph.R); // Replace Cum_Dur in our final ensures clause finalConfirmExp = Utilities.replace(finalConfirmExp, cumDur, sumEvalDur); myCurrentAssertiveCode.setFinalConfirm( finalConfirmExp, finalConfirm .getSimplify()); } } else { Utilities.illegalOperationEnsures(opDec .getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } } // Verbose Mode Debug Messages myVCBuffer.append("\nFunction Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the if statement rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>IfStmt</code>. */ private void applyIfStmtRule(IfStmt stmt) { // Note: In the If Rule, we will have two instances of the assertive code. // One for when the if condition is true and one for the else condition. // The current global assertive code variable is going to be used for the if path, // and we are going to create a new assertive code for the else path (this includes // the case when there is no else clause). ProgramExp ifCondition = stmt.getTest(); // Negation of If (Need to make a copy before we start modifying // the current assertive code for the if part) AssertiveCode negIfAssertiveCode = new AssertiveCode(myCurrentAssertiveCode); // Call a method to locate the operation dec for this call PosSymbol qualifier = null; ProgramParamExp testParamExp = null; // Check to see what kind of expression is on the right hand side if (ifCondition instanceof ProgramParamExp) { // Cast to a ProgramParamExp testParamExp = (ProgramParamExp) ifCondition; } else if (ifCondition instanceof ProgramDotExp) { // Cast to a ProgramParamExp ProgramDotExp dotExp = (ProgramDotExp) ifCondition; testParamExp = (ProgramParamExp) dotExp.getExp(); qualifier = dotExp.getQualifier(); } else { Utilities.expNotHandled(ifCondition, stmt.getLocation()); } Location ifConditionLoc; if (ifCondition.getLocation() != null) { ifConditionLoc = (Location) ifCondition.getLocation().clone(); } else { ifConditionLoc = (Location) stmt.getLocation().clone(); } OperationDec opDec = getOperationDec(ifCondition.getLocation(), qualifier, testParamExp.getName(), testParamExp.getArguments()); // Check for recursive call of itself if (myCurrentOperationEntry != null && myCurrentOperationEntry.getName().equals( opDec.getName().getName()) && myCurrentOperationEntry.getReturnType() != null) { // Create a new confirm statement using P_val and the decreasing clause VarExp pVal = Utilities.createPValExp(myOperationDecreasingExp .getLocation(), myCurrentModuleScope); // Create a new infix expression IntegerExp oneExp = new IntegerExp(); oneExp.setValue(1); oneExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp leftExp = new InfixExp(stmt.getLocation(), oneExp, Utilities .createPosSymbol("+"), Exp .copy(myOperationDecreasingExp)); leftExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp exp = Utilities.createLessThanEqExp(stmt.getLocation(), leftExp, pVal, BOOLEAN); // Create the new confirm statement Location loc; if (myOperationDecreasingExp.getLocation() != null) { loc = (Location) myOperationDecreasingExp.getLocation().clone(); } else { loc = (Location) stmt.getLocation().clone(); } loc.setDetails("Show Termination of Recursive Call"); Utilities.setLocation(exp, loc); ConfirmStmt conf = new ConfirmStmt(loc, exp, false); // Add it to our list of assertions myCurrentAssertiveCode.addCode(conf); } // Confirm the invoking condition // Get the requires clause for this operation Exp requires; boolean simplify = false; if (opDec.getRequires() != null) { requires = Exp.copy(opDec.getRequires()); // Simplify if we just have true if (requires.isLiteralTrue()) { simplify = true; } } else { requires = myTypeGraph.getTrueVarExp(); simplify = true; } // Find all the replacements that needs to happen to the requires // and ensures clauses List<ProgramExp> callArgs = testParamExp.getArguments(); List<Exp> replaceArgs = modifyArgumentList(callArgs); // Replace PreCondition variables in the requires clause requires = replaceFormalWithActualReq(requires, opDec.getParameters(), replaceArgs); // Modify the location of the requires clause and add it to myCurrentAssertiveCode // Obtain the current location // Note: If we don't have a location, we create one Location reqloc; if (testParamExp.getName().getLocation() != null) { reqloc = (Location) testParamExp.getName().getLocation().clone(); } else { reqloc = new Location(null, null); } // Set the details of the current location reqloc.setDetails("Requires Clause of " + opDec.getName()); Utilities.setLocation(requires, reqloc); // Add this to our list of things to confirm myCurrentAssertiveCode.addConfirm((Location) reqloc.clone(), requires, simplify); // Add the if condition as the assume clause // Get the ensures clause for this operation // Note: If there isn't an ensures clause, it is set to "True" Exp ensures, negEnsures = null, opEnsures; if (opDec.getEnsures() != null) { opEnsures = Exp.copy(opDec.getEnsures()); // Make sure we have an EqualsExp, else it is an error. if (opEnsures instanceof EqualsExp) { // Has to be a VarExp on the left hand side (containing the name // of the function operation) if (((EqualsExp) opEnsures).getLeft() instanceof VarExp) { VarExp leftExp = (VarExp) ((EqualsExp) opEnsures).getLeft(); // Check if it has the name of the operation if (leftExp.getName().equals(opDec.getName())) { ensures = ((EqualsExp) opEnsures).getRight(); // Obtain the current location Location loc = null; if (testParamExp.getName().getLocation() != null) { // Set the details of the current location loc = (Location) testParamExp.getName() .getLocation().clone(); loc.setDetails("If Statement Condition"); Utilities.setLocation(ensures, loc); } // Replace the formals with the actuals. ensures = replaceFormalWithActualEns(ensures, opDec .getParameters(), opDec.getStateVars(), replaceArgs, false); myCurrentAssertiveCode.addAssume(loc, ensures, true); // Negation of the condition negEnsures = Utilities.negateExp(ensures, BOOLEAN); } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } // Create a list for the then clause edu.clemson.cs.r2jt.collections.List<Statement> thenStmtList; if (stmt.getThenclause() != null) { thenStmtList = stmt.getThenclause(); } else { thenStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); } // Modify the confirm details ConfirmStmt ifConfirm = myCurrentAssertiveCode.getFinalConfirm(); Exp ifConfirmExp = ifConfirm.getAssertion(); Location ifLocation; if (ifConfirmExp.getLocation() != null) { ifLocation = (Location) ifConfirmExp.getLocation().clone(); } else { ifLocation = (Location) stmt.getLocation().clone(); } String ifDetail = ifLocation.getDetails() + ", Condition at " + ifConditionLoc.toString() + " is true"; ifLocation.setDetails(ifDetail); ifConfirmExp.setLocation(ifLocation); // NY YS // Duration for If Part InfixExp sumEvalDur = null; if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = (Location) ifLocation.clone(); VarExp cumDur; boolean trueConfirm = false; // Our previous rule must have been a while rule ConfirmStmt conf = null; if (ifConfirmExp.isLiteralTrue() && thenStmtList.size() != 0) { Statement st = thenStmtList.get(thenStmtList.size() - 1); if (st instanceof ConfirmStmt) { conf = (ConfirmStmt) st; cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(conf.getAssertion())), myTypeGraph.R, null); trueConfirm = true; } else { cumDur = null; Utilities.noSuchSymbol(null, "Cum_Dur", loc); } } else { cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(ifConfirmExp)), myTypeGraph.R, null); } // Search for operation profile List<PTType> argTypes = new LinkedList<PTType>(); List<ProgramExp> argsList = testParamExp.getArguments(); for (ProgramExp arg : argsList) { argTypes.add(arg.getProgramType()); } OperationProfileEntry ope = Utilities.searchOperationProfile(loc, qualifier, testParamExp.getName(), argTypes, myCurrentModuleScope); Exp opDur = Exp.copy(ope.getDurationClause()); Exp durCallExp = Utilities.createDurCallExp(loc, Integer.toString(opDec .getParameters().size()), Z, myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), opDur, Utilities .createPosSymbol("+"), durCallExp); sumEvalDur.setMathType(myTypeGraph.R); Exp sumPlusCumDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), Exp .copy(sumEvalDur)); sumPlusCumDur.setMathType(myTypeGraph.R); if (trueConfirm && conf != null) { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" Exp confirm = conf.getAssertion(); confirm = Utilities.replace(confirm, cumDur, Exp .copy(sumPlusCumDur)); conf.setAssertion(confirm); thenStmtList.set(thenStmtList.size() - 1, conf); } else { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" ifConfirmExp = Utilities.replace(ifConfirmExp, cumDur, Exp .copy(sumPlusCumDur)); } } // Add the statements inside the if to the assertive code myCurrentAssertiveCode.addStatements(thenStmtList); // Set the final if confirm myCurrentAssertiveCode.setFinalConfirm(ifConfirmExp, ifConfirm .getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nIf Part Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); // Add the negation of the if condition as the assume clause if (negEnsures != null) { negIfAssertiveCode.addAssume(ifLocation, negEnsures, true); } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } // Create a list for the then clause edu.clemson.cs.r2jt.collections.List<Statement> elseStmtList; if (stmt.getElseclause() != null) { elseStmtList = stmt.getElseclause(); } else { elseStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); } // Modify the confirm details ConfirmStmt negIfConfirm = negIfAssertiveCode.getFinalConfirm(); Exp negIfConfirmExp = negIfConfirm.getAssertion(); Location negIfLocation; if (negIfConfirmExp.getLocation() != null) { negIfLocation = (Location) negIfConfirmExp.getLocation().clone(); } else { negIfLocation = (Location) stmt.getLocation().clone(); } String negIfDetail = negIfLocation.getDetails() + ", Condition at " + ifConditionLoc.toString() + " is false"; negIfLocation.setDetails(negIfDetail); negIfConfirmExp.setLocation(negIfLocation); // NY YS // Duration for Else Part if (sumEvalDur != null) { Location loc = (Location) negIfLocation.clone(); VarExp cumDur; boolean trueConfirm = false; // Our previous rule must have been a while rule ConfirmStmt conf = null; if (negIfConfirmExp.isLiteralTrue() && elseStmtList.size() != 0) { Statement st = elseStmtList.get(elseStmtList.size() - 1); if (st instanceof ConfirmStmt) { conf = (ConfirmStmt) st; cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(conf.getAssertion())), myTypeGraph.R, null); trueConfirm = true; } else { cumDur = null; Utilities.noSuchSymbol(null, "Cum_Dur", loc); } } else { cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(negIfConfirmExp)), myTypeGraph.R, null); } Exp sumPlusCumDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), Exp .copy(sumEvalDur)); sumPlusCumDur.setMathType(myTypeGraph.R); if (trueConfirm && conf != null) { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" Exp confirm = conf.getAssertion(); confirm = Utilities.replace(confirm, cumDur, Exp .copy(sumPlusCumDur)); conf.setAssertion(confirm); elseStmtList.set(elseStmtList.size() - 1, conf); } else { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" negIfConfirmExp = Utilities.replace(negIfConfirmExp, cumDur, Exp .copy(sumPlusCumDur)); } } // Add the statements inside the else to the assertive code negIfAssertiveCode.addStatements(elseStmtList); // Set the final else confirm negIfAssertiveCode.setFinalConfirm(negIfConfirmExp, negIfConfirm .getSimplify()); // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(negIfAssertiveCode); // Verbose Mode Debug Messages String newString = "\nNegation of If Part Rule Applied: \n"; newString += negIfAssertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } /** * <p>Applies the initialization rule.</p> * * @param dec Representation declaration object. */ private void applyInitializationRule(RepresentationDec dec) { // Create a new assertive code to hold the correspondence VCs AssertiveCode assertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Location for the assume clauses Location decLoc = dec.getLocation(); // Add the global constraints as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalConstraintExp, false); // Add the global require clause as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalRequiresExp, false); // Add any variable declarations for records if (dec.getRepresentation() instanceof RecordTy) { RecordTy ty = (RecordTy) dec.getRepresentation(); assertiveCode.addVariableDecs(ty.getFields()); } // Add any statements in the initialization block if (dec.getInitialization() != null) { InitItem initItem = dec.getInitialization(); assertiveCode.addStatements(initItem.getStatements()); } // Search for the type we are implementing SymbolTableEntry ste = Utilities.searchProgramType(dec.getLocation(), null, dec .getName(), myCurrentModuleScope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(dec.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry(dec.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type .getExemplar(), typeEntry.getModelType(), null); // Add the correspondence as given assertiveCode.addAssume((Location) decLoc.clone(), dec .getCorrespondence(), false); // Make sure we have a convention if (dec.getConvention() == null) { myConventionExp = myTypeGraph.getTrueVarExp(); } else { myConventionExp = Exp.copy(dec.getConvention()); } // Set the location for the constraint Location loc; if (myConventionExp.getLocation() != null) { loc = (Location) myConventionExp.getLocation().clone(); } else { loc = (Location) dec.getLocation().clone(); } loc.setDetails("Convention for " + dec.getName().getName()); Utilities.setLocation(myConventionExp, loc); // Add the convention as something we need to confirm boolean simplify = false; // Simplify if we just have true if (myConventionExp.isLiteralTrue()) { simplify = true; } Exp convention = Exp.copy(myConventionExp); Location conventionLoc = (Location) convention.getLocation().clone(); conventionLoc.setDetails(conventionLoc.getDetails() + " generated by Initialization Rule"); Utilities.setLocation(convention, conventionLoc); assertiveCode.addConfirm(loc, convention, simplify); // Create a variable that refers to the conceptual exemplar DotExp conceptualVar = Utilities.createConcVarExp(null, exemplar, typeEntry .getModelType(), BOOLEAN); // Make sure we have a constraint Exp init; if (type.getInitialization().getEnsures() == null) { init = myTypeGraph.getTrueVarExp(); } else { init = Exp.copy(type.getInitialization().getEnsures()); } init = Utilities.replace(init, exemplar, conceptualVar); // Set the location for the constraint Location initLoc; initLoc = (Location) dec.getLocation().clone(); initLoc.setDetails("Initialization Rule for " + dec.getName().getName()); Utilities.setLocation(init, initLoc); // Add the initialization as something we need to confirm simplify = false; // Simplify if we just have true if (init.isLiteralTrue()) { simplify = true; } assertiveCode.addConfirm(loc, init, simplify); } // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(assertiveCode); // Verbose Mode Debug Messages String newString = "\n========================= Type Representation Name:\t" + dec.getName().getName() + " =========================\n"; newString += "\nInitialization Rule Applied: \n"; newString += assertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } /** * <p>Applies the procedure declaration rule.</p> * * @param opLoc Location of the procedure declaration. * @param name Name of the procedure. * @param requires Requires clause * @param ensures Ensures clause * @param decreasing Decreasing clause (if any) * @param procDur Procedure duration clause (if in performance mode) * @param varFinalDur Local variable finalization duration clause (if in performance mode) * @param typeConstraint Facility type constraints (if any) * @param variableList List of all variables for this procedure * @param statementList List of statements for this procedure * @param isLocal True if the it is a local operation. False otherwise. */ private void applyProcedureDeclRule(Location opLoc, String name, Exp requires, Exp ensures, Exp decreasing, Exp procDur, Exp varFinalDur, Exp typeConstraint, List<VarDec> variableList, List<Statement> statementList, boolean isLocal) { // Add the global requires clause if (myGlobalRequiresExp != null) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), myGlobalRequiresExp, false); } // Add the global constraints if (myGlobalConstraintExp != null) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), myGlobalConstraintExp, false); } // Add the convention as something we need to ensure if (myConventionExp != null && !isLocal) { Exp convention = Exp.copy(myConventionExp); myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), convention, false); } // Add the correspondence as a given if (myCorrespondenceExp != null && !isLocal) { Exp correspondence = Exp.copy(myCorrespondenceExp); myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), correspondence, false); } // Add the requires clause if (requires != null) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), requires, false); } // Add the facility formal to actuals Exp formalActualExp = myTypeGraph.getTrueVarExp(); for (FacilityDec fDec : myFacilityFormalActualMap.keySet()) { List<EqualsExp> eList = myFacilityFormalActualMap.get(fDec); for (EqualsExp e : eList) { EqualsExp newEquals = (EqualsExp) Exp.copy(e); VarExp oldLeft = (VarExp) Exp.copy(newEquals.getLeft()); VarExp newLeft; if (formalActualExp.containsVar(oldLeft.getName().getName(), false)) { newLeft = Utilities.createQuestionMarkVariable( formalActualExp, oldLeft); } else { newLeft = oldLeft; } newEquals.setLeft(newLeft); // Get rid of true if (formalActualExp.isLiteralTrue()) { formalActualExp = newEquals; } else { formalActualExp = myTypeGraph .formConjunct(formalActualExp, newEquals); } } } if (!formalActualExp.isLiteralTrue()) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), formalActualExp, false); } // NY - Add any procedure duration clauses if (procDur != null) { // Add Cum_Dur as a free variable VarExp cumDur = Utilities.createVarExp((Location) opLoc.clone(), null, Utilities.createPosSymbol("Cum_Dur"), myTypeGraph.R, null); myCurrentAssertiveCode.addFreeVar(cumDur); // Create 0.0 VarExp zeroPtZero = Utilities.createVarExp(opLoc, null, Utilities .createPosSymbol("0.0"), myTypeGraph.R, null); // Create an equals expression (Cum_Dur = 0.0) EqualsExp equalsExp = new EqualsExp(null, Exp.copy(cumDur), EqualsExp.EQUAL, zeroPtZero); equalsExp.setMathType(BOOLEAN); Location eqLoc = (Location) opLoc.clone(); eqLoc.setDetails("Initialization of Cum_Dur for Procedure " + name); Utilities.setLocation(equalsExp, eqLoc); // Add it to our things to assume myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), equalsExp, false); // Create the duration expression Exp durationExp; if (varFinalDur != null) { durationExp = new InfixExp(null, Exp.copy(cumDur), Utilities .createPosSymbol("+"), varFinalDur); } else { durationExp = Exp.copy(cumDur); } durationExp.setMathType(myTypeGraph.R); Location sumLoc = (Location) opLoc.clone(); sumLoc .setDetails("Summation of Finalization Duration for Procedure " + name); Utilities.setLocation(durationExp, sumLoc); InfixExp greaterEqExp = new InfixExp(null, durationExp, Utilities .createPosSymbol("<="), procDur); greaterEqExp.setMathType(BOOLEAN); Location andLoc = (Location) opLoc.clone(); andLoc.setDetails("Duration Clause of " + name); Utilities.setLocation(greaterEqExp, andLoc); // Append the duration to the ensures clause ensures = myTypeGraph.formConjunct(ensures, greaterEqExp); } // Add the facility type constraints if (typeConstraint != null) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), typeConstraint, false); } // Add the remember rule myCurrentAssertiveCode.addCode(new MemoryStmt((Location) opLoc.clone(), true)); // Add declared variables into the assertion. Also add // them to the list of free variables. myCurrentAssertiveCode.addVariableDecs(variableList); addVarDecsAsFreeVars(variableList); // Check to see if we have a recursive procedure. // If yes, we will need to create an additional assume clause // (P_val = (decreasing clause)) in our list of assertions. if (decreasing != null) { // Store for future use myOperationDecreasingExp = decreasing; // Add P_val as a free variable VarExp pVal = Utilities.createPValExp(decreasing.getLocation(), myCurrentModuleScope); myCurrentAssertiveCode.addFreeVar(pVal); // Create an equals expression EqualsExp equalsExp = new EqualsExp(null, pVal, EqualsExp.EQUAL, Exp .copy(decreasing)); equalsExp.setMathType(BOOLEAN); Location eqLoc = (Location) decreasing.getLocation().clone(); eqLoc.setDetails("Progress Metric for Recursive Procedure"); Utilities.setLocation(equalsExp, eqLoc); // Add it to our things to assume myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), equalsExp, false); } // Add the list of statements myCurrentAssertiveCode.addStatements(statementList); // Add the correspondence as a given again if (myCorrespondenceExp != null && !isLocal) { Exp correspondence = Exp.copy(myCorrespondenceExp); myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), correspondence, false); } // Add the convention as something we need to ensure if (myConventionExp != null && !isLocal) { Exp convention = Exp.copy(myConventionExp); Location conventionLoc = (Location) opLoc.clone(); conventionLoc.setDetails(convention.getLocation().getDetails() + " generated by " + name); Utilities.setLocation(convention, conventionLoc); // Simplify if we just have true boolean simplify = false; if (myConventionExp.isLiteralTrue()) { simplify = true; } myCurrentAssertiveCode.addConfirm(conventionLoc, convention, simplify); } // Simplify if we just have true boolean simplify = false; if (ensures.isLiteralTrue()) { simplify = true; } // Add the final confirms clause myCurrentAssertiveCode.setFinalConfirm(ensures, simplify); // Verbose Mode Debug Messages myVCBuffer.append("\nProcedure Declaration Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the remember rule.</p> */ private void applyRememberRule() { // Obtain the final confirm and apply the remember method for Exp ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp conf = confirmStmt.getAssertion(); conf = conf.remember(); myCurrentAssertiveCode.setFinalConfirm(conf, confirmStmt.getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nRemember Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies each of the proof rules. This <code>AssertiveCode</code> will be * stored for later use and therefore should be considered immutable after * a call to this method.</p> */ private void applyRules() { // Apply a proof rule to each of the assertions while (myCurrentAssertiveCode.hasAnotherAssertion()) { // Work our way from the last assertion VerificationStatement curAssertion = myCurrentAssertiveCode.getLastAssertion(); switch (curAssertion.getType()) { // Change Assertion case VerificationStatement.CHANGE: applyChangeRule(curAssertion); break; // Code case VerificationStatement.CODE: applyCodeRules((Statement) curAssertion.getAssertion()); break; // Variable Declaration Assertion case VerificationStatement.VARIABLE: applyVarDeclRule(curAssertion); break; } } } /** * <p>Applies the swap statement rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>SwapStmt</code>. */ private void applySwapStmtRule(SwapStmt stmt) { // Obtain the current final confirm clause ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp conf = confirmStmt.getAssertion(); // Create a copy of the left and right hand side VariableExp stmtLeft = (VariableExp) Exp.copy(stmt.getLeft()); VariableExp stmtRight = (VariableExp) Exp.copy(stmt.getRight()); // New left and right Exp newLeft = Utilities.convertExp(stmtLeft); Exp newRight = Utilities.convertExp(stmtRight); // Use our final confirm to obtain the math types List lst = conf.getSubExpressions(); for (int i = 0; i < lst.size(); i++) { if (lst.get(i) instanceof VarExp) { VarExp thisExp = (VarExp) lst.get(i); if (newRight instanceof VarExp) { if (thisExp.getName().equals( ((VarExp) newRight).getName().getName())) { newRight.setMathType(thisExp.getMathType()); newRight.setMathTypeValue(thisExp.getMathTypeValue()); } } if (newLeft instanceof VarExp) { if (thisExp.getName().equals( ((VarExp) newLeft).getName().getName())) { newLeft.setMathType(thisExp.getMathType()); newLeft.setMathTypeValue(thisExp.getMathTypeValue()); } } } } // Temp variable VarExp tmp = new VarExp(); tmp.setName(Utilities.createPosSymbol("_" + Utilities.getVarName(stmtLeft).getName())); tmp.setMathType(stmtLeft.getMathType()); tmp.setMathTypeValue(stmtLeft.getMathTypeValue()); // Replace according to the swap rule conf = Utilities.replace(conf, newRight, tmp); conf = Utilities.replace(conf, newLeft, newRight); conf = Utilities.replace(conf, tmp, newLeft); // NY YS // Duration for swap statements if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = stmt.getLocation(); VarExp cumDur = Utilities .createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(conf)), myTypeGraph.R, null); Exp swapDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol("Dur_Swap"), myTypeGraph.R, null); InfixExp sumSwapDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), swapDur); sumSwapDur.setMathType(myTypeGraph.R); conf = Utilities.replace(conf, cumDur, sumSwapDur); } // Set this new expression as the new final confirm myCurrentAssertiveCode.setFinalConfirm(conf, confirmStmt.getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nSwap Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the variable declaration rule.</p> * * @param var A declared variable stored as a * <code>VerificationStatement</code> */ private void applyVarDeclRule(VerificationStatement var) { // Obtain the variable from the verification statement VarDec varDec = (VarDec) var.getAssertion(); ProgramTypeEntry typeEntry; // Ty is NameTy if (varDec.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) varDec.getTy(); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy .getQualifier(), pNameTy.getName(), myCurrentModuleScope); if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry(pNameTy.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the declared variable VarExp varDecExp = Utilities.createVarExp(varDec.getLocation(), null, varDec.getName(), typeEntry.getModelType(), null); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type .getExemplar(), typeEntry.getModelType(), null); // Deep copy the original initialization ensures Exp init = Exp.copy(type.getInitialization().getEnsures()); init = Utilities.replace(init, exemplar, varDecExp); // Set the location for the initialization ensures Location loc; if (init.getLocation() != null) { loc = (Location) init.getLocation().clone(); } else { loc = (Location) type.getLocation().clone(); } loc.setDetails("Initialization ensures on " + varDec.getName().getName()); Utilities.setLocation(init, loc); // Final confirm clause Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm().getAssertion(); // Obtain the string form of the variable String varName = varDec.getName().getName(); // Check to see if we have a variable dot expression. // If we do, we will need to extract the name. int dotIndex = varName.indexOf("."); if (dotIndex > 0) { varName = varName.substring(0, dotIndex); } // Check to see if this variable was declared inside a record ResolveConceptualElement element = myCurrentAssertiveCode.getInstantiatingElement(); if (element instanceof RepresentationDec) { RepresentationDec dec = (RepresentationDec) element; if (dec.getRepresentation() instanceof RecordTy) { SymbolTableEntry repSte = Utilities.searchProgramType(dec.getLocation(), null, dec.getName(), myCurrentModuleScope); ProgramTypeDefinitionEntry representationTypeEntry = repSte.toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); // Create a variable expression from the type exemplar VarExp representationExemplar = Utilities .createVarExp( varDec.getLocation(), null, Utilities .createPosSymbol(representationTypeEntry .getExemplar() .getName()), representationTypeEntry .getModelType(), null); // Create a dotted expression edu.clemson.cs.r2jt.collections.List<Exp> expList = new edu.clemson.cs.r2jt.collections.List<Exp>(); expList.add(representationExemplar); expList.add(varDecExp); DotExp dotExp = Utilities.createDotExp(loc, expList, varDecExp .getMathType()); // Replace the initialization clauses appropriately init = Utilities.replace(init, varDecExp, dotExp); } } // Check if our confirm clause uses this variable if (finalConfirm.containsVar(varName, false)) { // Add the new assume clause to our assertive code. myCurrentAssertiveCode.addAssume((Location) loc.clone(), init, false); } } // Since the type is generic, we can only use the is_initial predicate // to ensure that the value is initial value. else { // Obtain the original dec from the AST Location varLoc = varDec.getLocation(); // Create an is_initial dot expression DotExp isInitialExp = Utilities.createInitExp(varDec, MTYPE, BOOLEAN); if (varLoc != null) { Location loc = (Location) varLoc.clone(); loc.setDetails("Initial Value for " + varDec.getName().getName()); Utilities.setLocation(isInitialExp, loc); } // Add to our assertive code as an assume myCurrentAssertiveCode.addAssume(varLoc, isInitialExp, false); } // NY YS // Initialization duration for this variable if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { ConfirmStmt finalConfirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp finalConfirm = finalConfirmStmt.getAssertion(); Location loc = ((NameTy) varDec.getTy()).getName().getLocation(); VarExp cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(finalConfirm)), myTypeGraph.R, null); Exp initDur = Utilities.createInitAnyDur(varDec, myTypeGraph.R); InfixExp sumInitDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), initDur); sumInitDur.setMathType(myTypeGraph.R); finalConfirm = Utilities.replace(finalConfirm, cumDur, sumInitDur); myCurrentAssertiveCode.setFinalConfirm(finalConfirm, finalConfirmStmt.getSimplify()); } // Verbose Mode Debug Messages myVCBuffer.append("\nVariable Declaration Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Ty not handled. Utilities.tyNotHandled(varDec.getTy(), varDec.getLocation()); } } /** * <p>Applies the while statement rule.</p> * * @param stmt Our current <code>WhileStmt</code>. */ private void applyWhileStmtRule(WhileStmt stmt) { // Obtain the loop invariant Exp invariant; boolean simplifyInvariant = false; if (stmt.getMaintaining() != null) { invariant = Exp.copy(stmt.getMaintaining()); invariant.setMathType(stmt.getMaintaining().getMathType()); // Simplify if we just have true if (invariant.isLiteralTrue()) { simplifyInvariant = true; } } else { invariant = myTypeGraph.getTrueVarExp(); simplifyInvariant = true; } // NY YS // Obtain the elapsed time duration of loop Exp elapsedTimeDur = null; if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { if (stmt.getElapsed_Time() != null) { elapsedTimeDur = Exp.copy(stmt.getElapsed_Time()); elapsedTimeDur.setMathType(myTypeGraph.R); } } // Confirm the base case of invariant Exp baseCase = Exp.copy(invariant); Location baseLoc; if (invariant.getLocation() != null) { baseLoc = (Location) invariant.getLocation().clone(); } else { baseLoc = (Location) stmt.getLocation().clone(); } baseLoc.setDetails("Base Case of the Invariant of While Statement"); Utilities.setLocation(baseCase, baseLoc); // NY YS // Confirm that elapsed time is 0.0 if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC) && elapsedTimeDur != null) { Exp initElapseDurExp = Exp.copy(elapsedTimeDur); Location initElapseLoc; if (elapsedTimeDur != null && elapsedTimeDur.getLocation() != null) { initElapseLoc = (Location) elapsedTimeDur.getLocation().clone(); } else { initElapseLoc = (Location) elapsedTimeDur.getLocation().clone(); } initElapseLoc .setDetails("Base Case of Elapsed Time Duration of While Statement"); Utilities.setLocation(initElapseDurExp, initElapseLoc); Exp zeroEqualExp = new EqualsExp((Location) initElapseLoc.clone(), initElapseDurExp, 1, Utilities.createVarExp( (Location) initElapseLoc.clone(), null, Utilities.createPosSymbol("0.0"), myTypeGraph.R, null)); zeroEqualExp.setMathType(BOOLEAN); baseCase = myTypeGraph.formConjunct(baseCase, zeroEqualExp); } myCurrentAssertiveCode.addConfirm((Location) baseLoc.clone(), baseCase, simplifyInvariant); // Add the change rule if (stmt.getChanging() != null) { myCurrentAssertiveCode.addChange(stmt.getChanging()); } // Assume the invariant and NQV(RP, P_Val) = P_Exp Location whileLoc = stmt.getLocation(); Exp assume; Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm().getAssertion(); boolean simplifyFinalConfirm = myCurrentAssertiveCode.getFinalConfirm().getSimplify(); Exp decreasingExp = stmt.getDecreasing(); Exp nqv; if (decreasingExp != null) { VarExp pval = Utilities.createPValExp((Location) whileLoc.clone(), myCurrentModuleScope); nqv = Utilities.createQuestionMarkVariable(finalConfirm, pval); nqv.setMathType(pval.getMathType()); Exp equalPExp = new EqualsExp((Location) whileLoc.clone(), Exp.copy(nqv), 1, Exp.copy(decreasingExp)); equalPExp.setMathType(BOOLEAN); assume = myTypeGraph.formConjunct(Exp.copy(invariant), equalPExp); } else { decreasingExp = myTypeGraph.getTrueVarExp(); nqv = myTypeGraph.getTrueVarExp(); assume = Exp.copy(invariant); } // NY YS // Also assume NQV(RP, Cum_Dur) = El_Dur_Exp Exp nqv2 = null; if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC) & elapsedTimeDur != null) { VarExp cumDurExp = Utilities.createVarExp((Location) whileLoc.clone(), null, Utilities.createPosSymbol("Cum_Dur"), myTypeGraph.R, null); nqv2 = Utilities.createQuestionMarkVariable(finalConfirm, cumDurExp); nqv2.setMathType(cumDurExp.getMathType()); Exp equalPExp = new EqualsExp((Location) whileLoc.clone(), Exp.copy(nqv2), 1, Exp.copy(elapsedTimeDur)); equalPExp.setMathType(BOOLEAN); assume = myTypeGraph.formConjunct(assume, equalPExp); } myCurrentAssertiveCode.addAssume((Location) whileLoc.clone(), assume, false); // if statement body (need to deep copy!) edu.clemson.cs.r2jt.collections.List<Statement> ifStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); edu.clemson.cs.r2jt.collections.List<Statement> whileStmtList = stmt.getStatements(); for (Statement s : whileStmtList) { ifStmtList.add((Statement) s.clone()); } // Confirm the inductive case of invariant Exp inductiveCase = Exp.copy(invariant); Location inductiveLoc; if (invariant.getLocation() != null) { inductiveLoc = (Location) invariant.getLocation().clone(); } else { inductiveLoc = (Location) stmt.getLocation().clone(); } inductiveLoc .setDetails("Inductive Case of Invariant of While Statement"); Utilities.setLocation(inductiveCase, inductiveLoc); ifStmtList.add(new ConfirmStmt(inductiveLoc, inductiveCase, simplifyInvariant)); // Confirm the termination of the loop. if (decreasingExp != null) { Location decreasingLoc = (Location) decreasingExp.getLocation().clone(); if (decreasingLoc != null) { decreasingLoc.setDetails("Termination of While Statement"); } // Create a new infix expression IntegerExp oneExp = new IntegerExp(); oneExp.setValue(1); oneExp.setMathType(decreasingExp.getMathType()); InfixExp leftExp = new InfixExp(stmt.getLocation(), oneExp, Utilities .createPosSymbol("+"), Exp.copy(decreasingExp)); leftExp.setMathType(decreasingExp.getMathType()); Exp infixExp = Utilities.createLessThanEqExp(decreasingLoc, leftExp, Exp .copy(nqv), BOOLEAN); // Confirm NQV(RP, Cum_Dur) <= El_Dur_Exp if (nqv2 != null) { Location elapsedTimeLoc = (Location) elapsedTimeDur.getLocation().clone(); if (elapsedTimeLoc != null) { elapsedTimeLoc.setDetails("Termination of While Statement"); } Exp infixExp2 = Utilities.createLessThanEqExp(elapsedTimeLoc, Exp .copy(nqv2), Exp.copy(elapsedTimeDur), BOOLEAN); infixExp = myTypeGraph.formConjunct(infixExp, infixExp2); infixExp.setLocation(decreasingLoc); } ifStmtList.add(new ConfirmStmt(decreasingLoc, infixExp, false)); } else { throw new RuntimeException("No decreasing clause!"); } // empty elseif pair edu.clemson.cs.r2jt.collections.List<ConditionItem> elseIfPairList = new edu.clemson.cs.r2jt.collections.List<ConditionItem>(); // else body Location elseConfirmLoc; if (finalConfirm.getLocation() != null) { elseConfirmLoc = (Location) finalConfirm.getLocation().clone(); } else { elseConfirmLoc = (Location) whileLoc.clone(); } edu.clemson.cs.r2jt.collections.List<Statement> elseStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); // NY YS // Form the confirm clause for the else Exp elseConfirm = Exp.copy(finalConfirm); if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC) & elapsedTimeDur != null) { Location loc = stmt.getLocation(); VarExp cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(elseConfirm)), myTypeGraph.R, null); InfixExp sumWhileDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), Exp .copy(elapsedTimeDur)); sumWhileDur.setMathType(myTypeGraph.R); elseConfirm = Utilities.replace(elseConfirm, cumDur, sumWhileDur); } elseStmtList.add(new ConfirmStmt(elseConfirmLoc, elseConfirm, simplifyFinalConfirm)); // condition ProgramExp condition = (ProgramExp) Exp.copy(stmt.getTest()); if (condition.getLocation() != null) { Location condLoc = (Location) condition.getLocation().clone(); condLoc.setDetails("While Loop Condition"); Utilities.setLocation(condition, condLoc); } // add it back to your assertive code IfStmt newIfStmt = new IfStmt(condition, ifStmtList, elseIfPairList, elseStmtList); myCurrentAssertiveCode.addCode(newIfStmt); // Change our final confirm to "True" Exp trueVarExp = myTypeGraph.getTrueVarExp(); trueVarExp.setLocation((Location) whileLoc.clone()); myCurrentAssertiveCode.setFinalConfirm(trueVarExp, true); // Verbose Mode Debug Messages myVCBuffer.append("\nWhile Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } }
src/main/java/edu/clemson/cs/r2jt/vcgeneration/VCGenerator.java
/** * VCGenerator.java * --------------------------------- * Copyright (c) 2015 * RESOLVE Software Research Group * School of Computing * Clemson University * All rights reserved. * --------------------------------- * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ package edu.clemson.cs.r2jt.vcgeneration; /* * Libraries */ import edu.clemson.cs.r2jt.ResolveCompiler; import edu.clemson.cs.r2jt.absyn.*; import edu.clemson.cs.r2jt.data.*; import edu.clemson.cs.r2jt.init.CompileEnvironment; import edu.clemson.cs.r2jt.rewriteprover.VC; import edu.clemson.cs.r2jt.treewalk.TreeWalker; import edu.clemson.cs.r2jt.treewalk.TreeWalkerVisitor; import edu.clemson.cs.r2jt.typeandpopulate.*; import edu.clemson.cs.r2jt.typeandpopulate.entry.*; import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTGeneric; import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTType; import edu.clemson.cs.r2jt.typereasoning.TypeGraph; import edu.clemson.cs.r2jt.misc.Flag; import edu.clemson.cs.r2jt.misc.FlagDependencies; import edu.clemson.cs.r2jt.vcgeneration.treewalkers.NestedFuncWalker; import java.io.File; import java.util.*; import java.util.List; /** * TODO: Write a description of this module */ public class VCGenerator extends TreeWalkerVisitor { // =========================================================== // Global Variables // =========================================================== // Symbol table related items private final MathSymbolTableBuilder mySymbolTable; private final TypeGraph myTypeGraph; private final MTType BOOLEAN; private final MTType MTYPE; private MTType Z; private ModuleScope myCurrentModuleScope; // Module level global variables private Exp myGlobalRequiresExp; private Exp myGlobalConstraintExp; // Conventions/Correspondence private Exp myConventionExp; private Exp myCorrespondenceExp; // Operation/Procedure level global variables private OperationEntry myCurrentOperationEntry; private OperationProfileEntry myCurrentOperationProfileEntry; private Exp myOperationDecreasingExp; /** * <p>The current assertion we are applying * VC rules to.</p> */ private AssertiveCode myCurrentAssertiveCode; /** * <p>A map of facility declarations to <code>Exp</code>, where the expression * contains the things we can assume from the facility declaration.</p> */ private Map<FacilityDec, Exp> myFacilityDeclarationMap; // TODO: Change this! /** * <p>A map of facility declarations to a list of formal and actual constraints.</p> */ private Map<FacilityDec, List<EqualsExp>> myFacilityFormalActualMap; /** * <p>A list that will be built up with <code>AssertiveCode</code> * objects, each representing a VC or group of VCs that must be * satisfied to verify a parsed program.</p> */ private Collection<AssertiveCode> myFinalAssertiveCodeList; /** * <p>A stack that is used to keep track of the <code>AssertiveCode</code> * that we still need to apply proof rules to.</p> */ private Stack<AssertiveCode> myIncAssertiveCodeStack; /** * <p>A stack that is used to keep track of the information that we * haven't printed for the <code>AssertiveCode</code> * that we still need to apply proof rules to.</p> */ private Stack<String> myIncAssertiveCodeStackInfo; /** * <p>The current compile environment used throughout * the compiler.</p> */ private CompileEnvironment myInstanceEnvironment; /** * <p>This object creates the different VC outputs.</p> */ private OutputVCs myOutputGenerator; /** * <p>This string buffer holds all the steps * the VC generator takes to generate VCs.</p> */ private StringBuffer myVCBuffer; // =========================================================== // Flag Strings // =========================================================== private static final String FLAG_ALTSECTION_NAME = "GenerateVCs"; private static final String FLAG_DESC_ATLVERIFY_VC = "Generate VCs."; private static final String FLAG_DESC_ATTPVCS_VC = "Generate Performance VCs"; // =========================================================== // Flags // =========================================================== public static final Flag FLAG_ALTVERIFY_VC = new Flag(FLAG_ALTSECTION_NAME, "altVCs", FLAG_DESC_ATLVERIFY_VC); public static final Flag FLAG_ALTPVCS_VC = new Flag(FLAG_ALTSECTION_NAME, "PVCs", FLAG_DESC_ATTPVCS_VC); public static final void setUpFlags() { FlagDependencies.addImplies(FLAG_ALTPVCS_VC, FLAG_ALTVERIFY_VC); } // =========================================================== // Constructors // =========================================================== public VCGenerator(ScopeRepository table, final CompileEnvironment env) { // Symbol table items mySymbolTable = (MathSymbolTableBuilder) table; myTypeGraph = mySymbolTable.getTypeGraph(); BOOLEAN = myTypeGraph.BOOLEAN; MTYPE = myTypeGraph.CLS; Z = null; // Current items myConventionExp = null; myCorrespondenceExp = null; myCurrentModuleScope = null; myCurrentOperationEntry = null; myCurrentOperationProfileEntry = null; myGlobalConstraintExp = null; myGlobalRequiresExp = null; myOperationDecreasingExp = null; // Instance Environment myInstanceEnvironment = env; // VCs + Debugging String myCurrentAssertiveCode = null; myFacilityDeclarationMap = new HashMap<FacilityDec, Exp>(); myFacilityFormalActualMap = new HashMap<FacilityDec, List<EqualsExp>>(); myFinalAssertiveCodeList = new LinkedList<AssertiveCode>(); myIncAssertiveCodeStack = new Stack<AssertiveCode>(); myIncAssertiveCodeStackInfo = new Stack<String>(); myOutputGenerator = null; myVCBuffer = new StringBuffer(); } // =========================================================== // Visitor Methods // =========================================================== // ----------------------------------------------------------- // ConceptBodyModuleDec // ----------------------------------------------------------- @Override public void preConceptBodyModuleDec(ConceptBodyModuleDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" VC Generation Details "); myVCBuffer.append(" =========================\n"); myVCBuffer.append("\n Concept Realization Name:\t"); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append("\n Concept Name:\t"); myVCBuffer.append(dec.getConceptName().getName()); myVCBuffer.append("\n"); myVCBuffer.append("\n===================================="); myVCBuffer.append("======================================\n"); myVCBuffer.append("\n"); // Set the current module scope try { myCurrentModuleScope = mySymbolTable.getModuleScope(new ModuleIdentifier(dec)); // Get "Z" from the TypeGraph Z = Utilities.getMathTypeZ(dec.getLocation(), myCurrentModuleScope); // From the list of imports, obtain the global constraints // of the imported modules. myGlobalConstraintExp = getConstraints(dec.getLocation(), myCurrentModuleScope .getImports()); // Store the global requires clause myGlobalRequiresExp = getRequiresClause(dec.getLocation(), dec); // Obtain the global requires clause from the Concept ConceptModuleDec conceptModuleDec = (ConceptModuleDec) mySymbolTable .getModuleScope( new ModuleIdentifier(dec.getConceptName() .getName())).getDefiningElement(); Exp conceptRequires = getRequiresClause(conceptModuleDec.getLocation(), conceptModuleDec); if (!conceptRequires.isLiteralTrue()) { if (myGlobalRequiresExp.isLiteralTrue()) { myGlobalRequiresExp = conceptRequires; } else { myGlobalRequiresExp = myTypeGraph.formConjunct(myGlobalRequiresExp, conceptRequires); } } } catch (NoSuchSymbolException e) { System.err.println("Module " + dec.getName() + " does not exist or is not in scope."); Utilities.noSuchModule(dec.getLocation()); } } @Override public void postConceptBodyModuleDec(ConceptBodyModuleDec dec) { // Set the module level global variables to null myCurrentModuleScope = null; myGlobalConstraintExp = null; myGlobalRequiresExp = null; } // ----------------------------------------------------------- // EnhancementBodyModuleDec // ----------------------------------------------------------- @Override public void preEnhancementBodyModuleDec(EnhancementBodyModuleDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" VC Generation Details "); myVCBuffer.append(" =========================\n"); myVCBuffer.append("\n Enhancement Realization Name:\t"); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append("\n Enhancement Name:\t"); myVCBuffer.append(dec.getEnhancementName().getName()); myVCBuffer.append("\n Concept Name:\t"); myVCBuffer.append(dec.getConceptName().getName()); myVCBuffer.append("\n"); myVCBuffer.append("\n===================================="); myVCBuffer.append("======================================\n"); myVCBuffer.append("\n"); // Set the current module scope try { myCurrentModuleScope = mySymbolTable.getModuleScope(new ModuleIdentifier(dec)); // Get "Z" from the TypeGraph Z = Utilities.getMathTypeZ(dec.getLocation(), myCurrentModuleScope); // From the list of imports, obtain the global constraints // of the imported modules. myGlobalConstraintExp = getConstraints(dec.getLocation(), myCurrentModuleScope .getImports()); // Store the global requires clause myGlobalRequiresExp = getRequiresClause(dec.getLocation(), dec); // Obtain the global requires clause from the Concept ConceptModuleDec conceptModuleDec = (ConceptModuleDec) mySymbolTable .getModuleScope( new ModuleIdentifier(dec.getConceptName() .getName())).getDefiningElement(); Exp conceptRequires = getRequiresClause(conceptModuleDec.getLocation(), conceptModuleDec); if (!conceptRequires.isLiteralTrue()) { if (myGlobalRequiresExp.isLiteralTrue()) { myGlobalRequiresExp = conceptRequires; } else { myGlobalRequiresExp = myTypeGraph.formConjunct(myGlobalRequiresExp, conceptRequires); } } // Obtain the global requires clause from the Enhancement EnhancementModuleDec enhancementModuleDec = (EnhancementModuleDec) mySymbolTable.getModuleScope( new ModuleIdentifier(dec.getEnhancementName() .getName())).getDefiningElement(); Exp enhancementRequires = getRequiresClause(enhancementModuleDec.getLocation(), enhancementModuleDec); if (!enhancementRequires.isLiteralTrue()) { if (myGlobalRequiresExp.isLiteralTrue()) { myGlobalRequiresExp = enhancementRequires; } else { myGlobalRequiresExp = myTypeGraph.formConjunct(myGlobalRequiresExp, enhancementRequires); } } } catch (NoSuchSymbolException e) { System.err.println("Module " + dec.getName() + " does not exist or is not in scope."); Utilities.noSuchModule(dec.getLocation()); } } @Override public void postEnhancementBodyModuleDec(EnhancementBodyModuleDec dec) { // Set the module level global variables to null myCurrentModuleScope = null; myGlobalConstraintExp = null; myGlobalRequiresExp = null; } // ----------------------------------------------------------- // FacilityDec // ----------------------------------------------------------- @Override public void postFacilityDec(FacilityDec dec) { // Applies the facility declaration rule applyFacilityDeclRule(dec); // Loop through assertive code stack loopAssertiveCodeStack(); } // ----------------------------------------------------------- // FacilityModuleDec // ----------------------------------------------------------- @Override public void preFacilityModuleDec(FacilityModuleDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" VC Generation Details "); myVCBuffer.append(" =========================\n"); myVCBuffer.append("\n Facility Name:\t"); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append("\n"); myVCBuffer.append("\n===================================="); myVCBuffer.append("======================================\n"); myVCBuffer.append("\n"); // Set the current module scope try { myCurrentModuleScope = mySymbolTable.getModuleScope(new ModuleIdentifier(dec)); // Get "Z" from the TypeGraph Z = Utilities.getMathTypeZ(dec.getLocation(), myCurrentModuleScope); // From the list of imports, obtain the global constraints // of the imported modules. myGlobalConstraintExp = getConstraints(dec.getLocation(), myCurrentModuleScope .getImports()); // Store the global requires clause myGlobalRequiresExp = getRequiresClause(dec.getLocation(), dec); } catch (NoSuchSymbolException e) { System.err.println("Module " + dec.getName() + " does not exist or is not in scope."); Utilities.noSuchModule(dec.getLocation()); } } @Override public void postFacilityModuleDec(FacilityModuleDec dec) { // Set the module level global variables to null myCurrentModuleScope = null; myGlobalConstraintExp = null; myGlobalRequiresExp = null; } // ----------------------------------------------------------- // FacilityOperationDec // ----------------------------------------------------------- @Override public void preFacilityOperationDec(FacilityOperationDec dec) { // Keep the current operation dec List<PTType> argTypes = new LinkedList<PTType>(); for (ParameterVarDec p : dec.getParameters()) { argTypes.add(p.getTy().getProgramTypeValue()); } myCurrentOperationEntry = Utilities.searchOperation(dec.getLocation(), null, dec .getName(), argTypes, myCurrentModuleScope); // Obtain the performance duration clause if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { myCurrentOperationProfileEntry = Utilities.searchOperationProfile(dec.getLocation(), null, dec.getName(), argTypes, myCurrentModuleScope); } } @Override public void postFacilityOperationDec(FacilityOperationDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" Procedure: "); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append(" =========================\n"); // The current assertive code myCurrentAssertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Obtains items from the current operation Location loc = dec.getLocation(); String name = dec.getName().getName(); boolean isLocal = Utilities.isLocationOperation(dec.getName().getName(), myCurrentModuleScope); Exp requires = modifyRequiresClause(getRequiresClause(loc, dec), loc, name, isLocal); Exp ensures = modifyEnsuresClause(getEnsuresClause(loc, dec), loc, name, isLocal); List<Statement> statementList = dec.getStatements(); List<VarDec> variableList = dec.getAllVariables(); Exp decreasing = dec.getDecreasing(); Exp procDur = null; Exp varFinalDur = null; // Obtain type constrains from parameter // TODO: Only add type constraints if they use the facility; Exp typeConstraint = null; for (FacilityDec fDec : myFacilityDeclarationMap.keySet()) { Exp temp = Exp.copy(myFacilityDeclarationMap.get(fDec)); if (typeConstraint == null) { typeConstraint = temp; } else { typeConstraint = myTypeGraph.formConjunct(typeConstraint, temp); } } // NY YS if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { procDur = myCurrentOperationProfileEntry.getDurationClause(); // Loop through local variables to get their finalization duration for (VarDec v : dec.getVariables()) { Exp finalVarDur = Utilities.createFinalizAnyDur(v, myTypeGraph.R); // Create/Add the duration expression if (varFinalDur == null) { varFinalDur = finalVarDur; } else { varFinalDur = new InfixExp((Location) loc.clone(), varFinalDur, Utilities.createPosSymbol("+"), finalVarDur); } varFinalDur.setMathType(myTypeGraph.R); } } // Apply the procedure declaration rule applyProcedureDeclRule(loc, name, requires, ensures, decreasing, procDur, varFinalDur, typeConstraint, variableList, statementList, isLocal); // Add this to our stack of to be processed assertive codes. myIncAssertiveCodeStack.push(myCurrentAssertiveCode); myIncAssertiveCodeStackInfo.push(""); // Set the current assertive code to null // YS: (We the modify requires and ensures clause needs to have // and current assertive code to work. Not very clean way to // solve the problem, but should work.) myCurrentAssertiveCode = null; // Loop through assertive code stack loopAssertiveCodeStack(); myOperationDecreasingExp = null; myCurrentOperationEntry = null; myCurrentOperationProfileEntry = null; } // ----------------------------------------------------------- // ModuleDec // ----------------------------------------------------------- @Override public void postModuleDec(ModuleDec dec) { // Create the output generator and finalize output myOutputGenerator = new OutputVCs(myInstanceEnvironment, myFinalAssertiveCodeList, myVCBuffer); // Check if it is generating VCs for WebIDE or not. if (myInstanceEnvironment.flags.isFlagSet(ResolveCompiler.FLAG_XML_OUT)) { myOutputGenerator.outputToJSON(); } else { // Print to file if we are in debug mode // TODO: Add debug flag here String filename; if (myInstanceEnvironment.getOutputFilename() != null) { filename = myInstanceEnvironment.getOutputFilename(); } else { filename = createVCFileName(); } myOutputGenerator.outputToFile(filename); } } // ----------------------------------------------------------- // ProcedureDec // ----------------------------------------------------------- @Override public void preProcedureDec(ProcedureDec dec) { // Keep the current operation dec List<PTType> argTypes = new LinkedList<PTType>(); for (ParameterVarDec p : dec.getParameters()) { argTypes.add(p.getTy().getProgramTypeValue()); } myCurrentOperationEntry = Utilities.searchOperation(dec.getLocation(), null, dec .getName(), argTypes, myCurrentModuleScope); // Obtain the performance duration clause if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { myCurrentOperationProfileEntry = Utilities.searchOperationProfile(dec.getLocation(), null, dec.getName(), argTypes, myCurrentModuleScope); } } @Override public void postProcedureDec(ProcedureDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" Procedure: "); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append(" =========================\n"); // The current assertive code myCurrentAssertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Obtains items from the current operation OperationDec opDec = (OperationDec) myCurrentOperationEntry.getDefiningElement(); Location loc = dec.getLocation(); String name = dec.getName().getName(); boolean isLocal = Utilities.isLocationOperation(dec.getName().getName(), myCurrentModuleScope); Exp requires = modifyRequiresClause(getRequiresClause(loc, opDec), loc, name, isLocal); Exp ensures = modifyEnsuresClause(getEnsuresClause(loc, opDec), loc, name, isLocal); List<Statement> statementList = dec.getStatements(); List<VarDec> variableList = dec.getAllVariables(); Exp decreasing = dec.getDecreasing(); Exp procDur = null; Exp varFinalDur = null; // Obtain type constrains from parameter // TODO: Only add type constraints if they use the facility; Exp facTypeConstraint = null; for (FacilityDec fDec : myFacilityDeclarationMap.keySet()) { Exp temp = Exp.copy(myFacilityDeclarationMap.get(fDec)); if (facTypeConstraint == null) { facTypeConstraint = temp; } else { facTypeConstraint = myTypeGraph.formConjunct(facTypeConstraint, temp); } } // NY YS if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { procDur = myCurrentOperationProfileEntry.getDurationClause(); // Loop through local variables to get their finalization duration for (VarDec v : dec.getVariables()) { Exp finalVarDur = Utilities.createFinalizAnyDur(v, BOOLEAN); // Create/Add the duration expression if (varFinalDur == null) { varFinalDur = finalVarDur; } else { varFinalDur = new InfixExp((Location) loc.clone(), varFinalDur, Utilities.createPosSymbol("+"), finalVarDur); } varFinalDur.setMathType(myTypeGraph.R); } } // Apply the procedure declaration rule applyProcedureDeclRule(loc, name, requires, ensures, decreasing, procDur, varFinalDur, facTypeConstraint, variableList, statementList, isLocal); // Add this to our stack of to be processed assertive codes. myIncAssertiveCodeStack.push(myCurrentAssertiveCode); myIncAssertiveCodeStackInfo.push(""); // Set the current assertive code to null // YS: (We the modify requires and ensures clause needs to have // and current assertive code to work. Not very clean way to // solve the problem, but should work.) myCurrentAssertiveCode = null; // Loop through assertive code stack loopAssertiveCodeStack(); myOperationDecreasingExp = null; myCurrentOperationEntry = null; myCurrentOperationProfileEntry = null; } // ----------------------------------------------------------- // RepresentationDec // ----------------------------------------------------------- @Override public void postRepresentationDec(RepresentationDec dec) { // Applies the initialization rule applyInitializationRule(dec); // Applies the correspondence rule applyCorrespondenceRule(dec); // Loop through assertive code stack loopAssertiveCodeStack(); } // =========================================================== // Public Methods // =========================================================== // ----------------------------------------------------------- // Prover Mode // ----------------------------------------------------------- /** * <p>The set of immmutable VCs that the in house provers can use.</p> * * @return VCs to be proved. */ public List<VC> proverOutput() { return myOutputGenerator.getProverOutput(); } // =========================================================== // Private Methods // =========================================================== /** * <p>Loop through the list of <code>VarDec</code>, search * for their corresponding <code>ProgramVariableEntry</code> * and add the result to the list of free variables.</p> * * @param variableList List of the all variables as * <code>VarDec</code>. */ private void addVarDecsAsFreeVars(List<VarDec> variableList) { // Loop through the variable list for (VarDec v : variableList) { myCurrentAssertiveCode.addFreeVar(Utilities.createVarExp(v .getLocation(), null, v.getName(), v.getTy() .getMathTypeValue(), null)); } } /** * <p>Creates the name of the output file.</p> * * @return Name of the file */ private String createVCFileName() { File file = myInstanceEnvironment.getTargetFile(); ModuleID cid = myInstanceEnvironment.getModuleID(file); file = myInstanceEnvironment.getFile(cid); String filename = file.toString(); int temp = filename.indexOf("."); String tempfile = filename.substring(0, temp); String mainFileName; mainFileName = tempfile + ".asrt_new"; return mainFileName; } /** * <p>Returns all the constraint clauses combined together for the * for the current <code>ModuleDec</code>.</p> * * @param loc The location of the <code>ModuleDec</code>. * @param imports The list of imported modules. * * @return The constraint clause <code>Exp</code>. */ private Exp getConstraints(Location loc, List<ModuleIdentifier> imports) { Exp retExp = null; List<String> importedConceptName = new LinkedList<String>(); // Loop for (ModuleIdentifier mi : imports) { try { ModuleDec dec = mySymbolTable.getModuleScope(mi).getDefiningElement(); List<Exp> contraintExpList = null; // Handling for facility imports if (dec instanceof ShortFacilityModuleDec) { FacilityDec facDec = ((ShortFacilityModuleDec) dec).getDec(); dec = mySymbolTable.getModuleScope( new ModuleIdentifier(facDec .getConceptName().getName())) .getDefiningElement(); } if (dec instanceof ConceptModuleDec && !importedConceptName.contains(dec.getName() .getName())) { contraintExpList = ((ConceptModuleDec) dec).getConstraints(); // Copy all the constraints for (Exp e : contraintExpList) { // Deep copy and set the location detail Exp constraint = Exp.copy(e); if (constraint.getLocation() != null) { Location theLoc = constraint.getLocation(); theLoc.setDetails("Constraint of Module: " + dec.getName()); Utilities.setLocation(constraint, theLoc); } // Form conjunct if needed. if (retExp == null) { retExp = Exp.copy(e); } else { retExp = myTypeGraph.formConjunct(retExp, Exp .copy(e)); } } // Avoid importing constraints for the same concept twice importedConceptName.add(dec.getName().getName()); } } catch (NoSuchSymbolException e) { System.err.println("Module " + mi.toString() + " does not exist or is not in scope."); Utilities.noSuchModule(loc); } } return retExp; } /** * <p>Returns the ensures clause for the current <code>Dec</code>.</p> * * @param location The location of the ensures clause. * @param dec The corresponding <code>Dec</code>. * * @return The ensures clause <code>Exp</code>. */ private Exp getEnsuresClause(Location location, Dec dec) { PosSymbol name = dec.getName(); Exp ensures = null; Exp retExp; // Check for each kind of ModuleDec possible if (dec instanceof FacilityOperationDec) { ensures = ((FacilityOperationDec) dec).getEnsures(); } else if (dec instanceof OperationDec) { ensures = ((OperationDec) dec).getEnsures(); } // Deep copy and fill in the details of this location if (ensures != null) { retExp = Exp.copy(ensures); } else { retExp = myTypeGraph.getTrueVarExp(); } if (retExp.getLocation() != null) { Location loc = (Location) location.clone(); loc.setDetails("Ensures Clause of " + name); Utilities.setLocation(retExp, loc); } return retExp; } /** * <p>Locate and return the corresponding operation dec based on the qualifier, * name, and arguments.</p> * * @param loc Location of the calling statement. * @param qual Qualifier of the operation * @param name Name of the operation. * @param args List of arguments for the operation. * * @return The operation corresponding to the calling statement in <code>OperationDec</code> form. */ private OperationDec getOperationDec(Location loc, PosSymbol qual, PosSymbol name, List<ProgramExp> args) { // Obtain the corresponding OperationEntry and OperationDec List<PTType> argTypes = new LinkedList<PTType>(); for (ProgramExp arg : args) { argTypes.add(arg.getProgramType()); } OperationEntry opEntry = Utilities.searchOperation(loc, qual, name, argTypes, myCurrentModuleScope); // Obtain an OperationDec from the OperationEntry ResolveConceptualElement element = opEntry.getDefiningElement(); OperationDec opDec; if (element instanceof OperationDec) { opDec = (OperationDec) opEntry.getDefiningElement(); } else { FacilityOperationDec fOpDec = (FacilityOperationDec) opEntry.getDefiningElement(); opDec = new OperationDec(fOpDec.getName(), fOpDec.getParameters(), fOpDec.getReturnTy(), fOpDec.getStateVars(), fOpDec .getRequires(), fOpDec.getEnsures()); } return opDec; } /** * <p>Returns the requires clause for the current <code>Dec</code>.</p> * * @param location The location of the requires clause. * @param dec The corresponding <code>Dec</code>. * * @return The requires clause <code>Exp</code>. */ private Exp getRequiresClause(Location location, Dec dec) { PosSymbol name = dec.getName(); Exp requires = null; Exp retExp; // Check for each kind of ModuleDec possible if (dec instanceof FacilityOperationDec) { requires = ((FacilityOperationDec) dec).getRequires(); } else if (dec instanceof OperationDec) { requires = ((OperationDec) dec).getRequires(); } else if (dec instanceof ConceptModuleDec) { requires = ((ConceptModuleDec) dec).getRequirement(); } else if (dec instanceof ConceptBodyModuleDec) { requires = ((ConceptBodyModuleDec) dec).getRequires(); } else if (dec instanceof EnhancementModuleDec) { requires = ((EnhancementModuleDec) dec).getRequirement(); } else if (dec instanceof EnhancementBodyModuleDec) { requires = ((EnhancementBodyModuleDec) dec).getRequires(); } else if (dec instanceof FacilityModuleDec) { requires = ((FacilityModuleDec) dec).getRequirement(); } // Deep copy and fill in the details of this location if (requires != null) { retExp = Exp.copy(requires); } else { retExp = myTypeGraph.getTrueVarExp(); } if (location != null) { Location loc = (Location) location.clone(); loc.setDetails("Requires Clause for " + name); Utilities.setLocation(retExp, loc); } return retExp; } /** * <p>Loop through our stack of incomplete assertive codes.</p> */ private void loopAssertiveCodeStack() { // Loop until our to process assertive code stack is empty while (!myIncAssertiveCodeStack.empty()) { // Set the incoming assertive code as our current assertive // code we are working on. myCurrentAssertiveCode = myIncAssertiveCodeStack.pop(); myVCBuffer.append("\n***********************"); myVCBuffer.append("***********************\n"); // Append any information that still needs to be added to our // Debug VC Buffer myVCBuffer.append(myIncAssertiveCodeStackInfo.pop()); // Apply proof rules applyRules(); myVCBuffer.append("\n***********************"); myVCBuffer.append("***********************\n"); // Add it to our list of final assertive codes if we don't have confirm true // as our goal. if (!myCurrentAssertiveCode.getFinalConfirm().getAssertion() .isLiteralTrue()) { myFinalAssertiveCodeList.add(myCurrentAssertiveCode); } // Set the current assertive code to null myCurrentAssertiveCode = null; } } /** * <p>Modify the argument expression list if we have a * nested function call.</p> * * @param callArgs The original list of arguments. * * @return The modified list of arguments. */ private List<Exp> modifyArgumentList(List<ProgramExp> callArgs) { // Find all the replacements that needs to happen to the requires // and ensures clauses List<Exp> replaceArgs = new ArrayList<Exp>(); for (ProgramExp p : callArgs) { // Check for nested function calls in ProgramDotExp // and ProgramParamExp. if (p instanceof ProgramDotExp || p instanceof ProgramParamExp) { NestedFuncWalker nfw = new NestedFuncWalker(myCurrentOperationEntry, myOperationDecreasingExp, mySymbolTable, myCurrentModuleScope, myCurrentAssertiveCode); TreeWalker tw = new TreeWalker(nfw); tw.visit(p); // Add the requires clause as something we need to confirm Exp pRequires = nfw.getRequiresClause(); if (!pRequires.isLiteralTrue()) { myCurrentAssertiveCode.addConfirm(pRequires.getLocation(), pRequires, false); } // Add the modified ensures clause as the new expression we want // to replace in the CallStmt's ensures clause. replaceArgs.add(nfw.getEnsuresClause()); } // For all other types of arguments, simply add it to the list to be replaced else { replaceArgs.add(p); } } return replaceArgs; } /** * <p>Modifies the ensures clause based on the parameter mode.</p> * * @param ensures The <code>Exp</code> containing the ensures clause. * @param opLocation The <code>Location</code> for the operation * @param opName The name of the operation. * @param parameterVarDecList The list of parameter variables for the operation. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified ensures clause <code>Exp</code>. */ private Exp modifyEnsuresByParameter(Exp ensures, Location opLocation, String opName, List<ParameterVarDec> parameterVarDecList, boolean isLocal) { // Loop through each parameter for (ParameterVarDec p : parameterVarDecList) { // Ty is NameTy if (p.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) p.getTy(); // Exp form of the parameter variable VarExp parameterExp = new VarExp(p.getLocation(), null, p.getName().copy()); parameterExp.setMathType(pNameTy.getMathTypeValue()); // Create an old exp (#parameterExp) OldExp oldParameterExp = new OldExp(p.getLocation(), Exp.copy(parameterExp)); oldParameterExp.setMathType(pNameTy.getMathTypeValue()); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy.getQualifier(), pNameTy.getName(), myCurrentModuleScope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste .toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); } // Preserves or Restores mode if (p.getMode() == Mode.PRESERVES || p.getMode() == Mode.RESTORES) { // Create an equals expression of the form "#parameterExp = parameterExp" EqualsExp equalsExp = new EqualsExp(opLocation, oldParameterExp, EqualsExp.EQUAL, parameterExp); equalsExp.setMathType(BOOLEAN); // Set the details for the new location Location equalLoc; if (ensures != null && ensures.getLocation() != null) { Location enLoc = ensures.getLocation(); equalLoc = ((Location) enLoc.clone()); } else { equalLoc = ((Location) opLocation.clone()); equalLoc.setDetails("Ensures Clause of " + opName); } equalLoc.setDetails(equalLoc.getDetails() + " (Condition from \"" + p.getMode().getModeName() + "\" parameter mode)"); equalsExp.setLocation(equalLoc); // Create an AND infix expression with the ensures clause if (ensures != null && !ensures.equals(myTypeGraph.getTrueVarExp())) { Location newEnsuresLoc = (Location) ensures.getLocation().clone(); ensures = myTypeGraph.formConjunct(ensures, equalsExp); ensures.setLocation(newEnsuresLoc); } // Make new expression the ensures clause else { ensures = equalsExp; } } // Clears mode else if (p.getMode() == Mode.CLEARS) { Exp init; if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Obtain the exemplar in VarExp form VarExp exemplar = new VarExp(null, null, type.getExemplar()); exemplar.setMathType(pNameTy.getMathTypeValue()); // Deep copy the original initialization ensures and the constraint init = Exp.copy(type.getInitialization().getEnsures()); // Replace the formal with the actual init = Utilities.replace(init, exemplar, parameterExp); // Set the details for the new location if (init.getLocation() != null) { Location initLoc; if (ensures != null && ensures.getLocation() != null) { Location reqLoc = ensures.getLocation(); initLoc = ((Location) reqLoc.clone()); } else { initLoc = ((Location) opLocation.clone()); initLoc.setDetails("Ensures Clause of " + opName); } initLoc.setDetails(initLoc.getDetails() + " (Condition from \"" + p.getMode().getModeName() + "\" parameter mode)"); init.setLocation(initLoc); } } // Since the type is generic, we can only use the is_initial predicate // to ensure that the value is initial value. else { // Obtain the original dec from the AST Location varLoc = p.getLocation(); // Create an is_initial dot expression init = Utilities.createInitExp(new VarDec(p.getName(), p.getTy()), MTYPE, BOOLEAN); if (varLoc != null) { Location loc = (Location) varLoc.clone(); loc.setDetails("Initial Value for " + p.getName().getName()); Utilities.setLocation(init, loc); } } // Create an AND infix expression with the ensures clause if (ensures != null && !ensures.equals(myTypeGraph.getTrueVarExp())) { Location newEnsuresLoc = (Location) ensures.getLocation().clone(); ensures = myTypeGraph.formConjunct(ensures, init); ensures.setLocation(newEnsuresLoc); } // Make initialization expression the ensures clause else { ensures = init; } } // If the type is a type representation, then our requires clause // should really say something about the conceptual type and not // the variable if (ste instanceof RepresentationTypeEntry && !isLocal) { Exp conceptualExp = Utilities.createConcVarExp(opLocation, parameterExp, parameterExp.getMathType(), BOOLEAN); OldExp oldConceptualExp = new OldExp(opLocation, Exp.copy(conceptualExp)); ensures = Utilities.replace(ensures, parameterExp, conceptualExp); ensures = Utilities.replace(ensures, oldParameterExp, oldConceptualExp); } } else { // Ty not handled. Utilities.tyNotHandled(p.getTy(), p.getLocation()); } } return ensures; } /** * <p>Returns the ensures clause.</p> * * @param ensures The <code>Exp</code> containing the ensures clause. * @param opLocation The <code>Location</code> for the operation. * @param opName The name for the operation. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified ensures clause <code>Exp</code>. */ private Exp modifyEnsuresClause(Exp ensures, Location opLocation, String opName, boolean isLocal) { // Obtain the list of parameters for the current operation List<ParameterVarDec> parameterVarDecList; if (myCurrentOperationEntry.getDefiningElement() instanceof FacilityOperationDec) { parameterVarDecList = ((FacilityOperationDec) myCurrentOperationEntry .getDefiningElement()).getParameters(); } else { parameterVarDecList = ((OperationDec) myCurrentOperationEntry .getDefiningElement()).getParameters(); } // Modifies the existing ensures clause based on // the parameter modes. ensures = modifyEnsuresByParameter(ensures, opLocation, opName, parameterVarDecList, isLocal); return ensures; } /** * <p>Modifies the requires clause based on .</p> * * @param requires The <code>Exp</code> containing the requires clause. * * @return The modified requires clause <code>Exp</code>. */ private Exp modifyRequiresByGlobalMode(Exp requires) { return requires; } /** * <p>Modifies the requires clause based on the parameter mode.</p> * * @param requires The <code>Exp</code> containing the requires clause. * @param opLocation The <code>Location</code> for the operation. * @param opName The name for the operation. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified requires clause <code>Exp</code>. */ private Exp modifyRequiresByParameter(Exp requires, Location opLocation, String opName, boolean isLocal) { // Obtain the list of parameters List<ParameterVarDec> parameterVarDecList; if (myCurrentOperationEntry.getDefiningElement() instanceof FacilityOperationDec) { parameterVarDecList = ((FacilityOperationDec) myCurrentOperationEntry .getDefiningElement()).getParameters(); } else { parameterVarDecList = ((OperationDec) myCurrentOperationEntry .getDefiningElement()).getParameters(); } // Loop through each parameter for (ParameterVarDec p : parameterVarDecList) { ProgramTypeEntry typeEntry; // Ty is NameTy if (p.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) p.getTy(); PTType ptType = pNameTy.getProgramTypeValue(); // Only deal with actual types and don't deal // with entry types passed in to the concept realization if (!(ptType instanceof PTGeneric)) { // Convert p to a VarExp VarExp parameterExp = new VarExp(null, null, p.getName()); parameterExp.setMathType(pNameTy.getMathTypeValue()); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy.getQualifier(), pNameTy.getName(), myCurrentModuleScope); if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); } // Obtain the original dec from the AST VarExp exemplar = null; Exp constraint = null; if (typeEntry.getDefiningElement() instanceof TypeDec) { TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Obtain the exemplar in VarExp form exemplar = new VarExp(null, null, type.getExemplar()); exemplar.setMathType(pNameTy.getMathTypeValue()); // If we have a type representation, then there are no initialization // or constraint clauses. if (ste instanceof ProgramTypeEntry) { // Deep copy the constraint if (type.getConstraint() != null) { constraint = Exp.copy(type.getConstraint()); } } } // Other than the replaces mode, constraints for the // other parameter modes needs to be added // to the requires clause as conjuncts. if (p.getMode() != Mode.REPLACES) { if (constraint != null && !constraint.equals(myTypeGraph .getTrueVarExp())) { // Replace the formal with the actual if (exemplar != null) { constraint = Utilities.replace(constraint, exemplar, parameterExp); } // Set the details for the new location if (constraint.getLocation() != null) { Location constLoc; if (requires != null && requires.getLocation() != null) { Location reqLoc = requires.getLocation(); constLoc = ((Location) reqLoc.clone()); } else { // Append the name of the current procedure String details = ""; if (myCurrentOperationEntry != null) { details = " in Procedure " + myCurrentOperationEntry .getName(); } constLoc = ((Location) opLocation.clone()); constLoc.setDetails("Requires Clause of " + opName + details); } constLoc.setDetails(constLoc.getDetails() + " (Constraint from \"" + p.getMode().getModeName() + "\" parameter mode)"); constraint.setLocation(constLoc); } // Create an AND infix expression with the requires clause if (requires != null && !requires.equals(myTypeGraph .getTrueVarExp())) { requires = myTypeGraph.formConjunct(requires, constraint); requires.setLocation((Location) opLocation .clone()); } // Make constraint expression the requires clause else { requires = constraint; } } } // If the type is a type representation, then our requires clause // should really say something about the conceptual type and not // the variable if (ste instanceof RepresentationTypeEntry && !isLocal) { requires = Utilities.replace(requires, parameterExp, Utilities .createConcVarExp(opLocation, parameterExp, parameterExp .getMathType(), BOOLEAN)); } } // Add the current variable to our list of free variables myCurrentAssertiveCode.addFreeVar(Utilities.createVarExp(p .getLocation(), null, p.getName(), pNameTy .getMathTypeValue(), null)); } else { // Ty not handled. Utilities.tyNotHandled(p.getTy(), p.getLocation()); } } return requires; } /** * <p>Modifies the requires clause.</p> * * @param requires The <code>Exp</code> containing the requires clause. * @param opLocation The <code>Location</code> for the operation. * @param opName The name of the operation. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified requires clause <code>Exp</code>. */ private Exp modifyRequiresClause(Exp requires, Location opLocation, String opName, boolean isLocal) { // Modifies the existing requires clause based on // the parameter modes. requires = modifyRequiresByParameter(requires, opLocation, opName, isLocal); // Modifies the existing requires clause based on // the parameter modes. // TODO: Ask Murali what this means requires = modifyRequiresByGlobalMode(requires); return requires; } /** * <p>Replace the formal with the actual variables * inside the ensures clause.</p> * * @param ensures The ensures clause. * @param paramList The list of parameter variables. * @param stateVarList The list of state variables. * @param argList The list of arguments from the operation call. * @param isSimple Check if it is a simple replacement. * * @return The ensures clause in <code>Exp</code> form. */ private Exp replaceFormalWithActualEns(Exp ensures, List<ParameterVarDec> paramList, List<AffectsItem> stateVarList, List<Exp> argList, boolean isSimple) { // Current final confirm Exp newConfirm; // List to hold temp and real values of variables in case // of duplicate spec and real variables List<Exp> undRepList = new ArrayList<Exp>(); List<Exp> replList = new ArrayList<Exp>(); // Replace state variables in the ensures clause // and create new confirm statements if needed. for (int i = 0; i < stateVarList.size(); i++) { ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); newConfirm = confirmStmt.getAssertion(); AffectsItem stateVar = stateVarList.get(i); // Only deal with Alters/Reassigns/Replaces/Updates modes if (stateVar.getMode() == Mode.ALTERS || stateVar.getMode() == Mode.REASSIGNS || stateVar.getMode() == Mode.REPLACES || stateVar.getMode() == Mode.UPDATES) { // Obtain the variable from our free variable list Exp globalFreeVar = myCurrentAssertiveCode.getFreeVar(stateVar.getName(), true); if (globalFreeVar != null) { VarExp oldNamesVar = new VarExp(); oldNamesVar.setName(stateVar.getName()); // Create a local free variable if it is not there Exp localFreeVar = myCurrentAssertiveCode.getFreeVar(stateVar .getName(), false); if (localFreeVar == null) { // TODO: Don't have a type for state variables? localFreeVar = new VarExp(null, null, stateVar.getName()); localFreeVar = Utilities.createQuestionMarkVariable( myTypeGraph.formConjunct(ensures, newConfirm), (VarExp) localFreeVar); myCurrentAssertiveCode.addFreeVar(localFreeVar); } else { localFreeVar = Utilities.createQuestionMarkVariable( myTypeGraph.formConjunct(ensures, newConfirm), (VarExp) localFreeVar); } // Creating "#" expressions and replace these in the // ensures clause. OldExp osVar = new OldExp(null, Exp.copy(globalFreeVar)); OldExp oldNameOSVar = new OldExp(null, Exp.copy(oldNamesVar)); ensures = Utilities.replace(ensures, oldNamesVar, globalFreeVar); ensures = Utilities.replace(ensures, oldNameOSVar, osVar); // If it is not simple replacement, replace all ensures clauses // with the appropriate expressions. if (!isSimple) { ensures = Utilities.replace(ensures, globalFreeVar, localFreeVar); ensures = Utilities .replace(ensures, osVar, globalFreeVar); newConfirm = Utilities.replace(newConfirm, globalFreeVar, localFreeVar); } // Set newConfirm as our new final confirm statement myCurrentAssertiveCode.setFinalConfirm(newConfirm, confirmStmt.getSimplify()); } // Error: Why isn't it a free variable. else { Utilities.notInFreeVarList(stateVar.getName(), stateVar .getLocation()); } } } // Replace postcondition variables in the ensures clause for (int i = 0; i < argList.size(); i++) { ParameterVarDec varDec = paramList.get(i); Exp exp = argList.get(i); PosSymbol VDName = varDec.getName(); ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); newConfirm = confirmStmt.getAssertion(); // VarExp form of the parameter variable VarExp oldExp = new VarExp(null, null, VDName); oldExp.setMathType(exp.getMathType()); oldExp.setMathTypeValue(exp.getMathTypeValue()); // Convert the pExp into a something we can use Exp repl = Utilities.convertExp(exp); Exp undqRep = null, quesRep = null; OldExp oSpecVar, oRealVar; String replName = null; // Case #1: ProgramIntegerExp // Case #2: ProgramCharExp // Case #3: ProgramStringExp if (exp instanceof ProgramIntegerExp || exp instanceof ProgramCharExp || exp instanceof ProgramStringExp) { Exp convertExp = Utilities.convertExp(exp); if (exp instanceof ProgramIntegerExp) { replName = Integer.toString(((IntegerExp) convertExp) .getValue()); } else if (exp instanceof ProgramCharExp) { replName = Character.toString(((CharExp) convertExp) .getValue()); } else { replName = ((StringExp) convertExp).getValue(); } // Create a variable expression of the form "_?[Argument Name]" undqRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_?" + replName), exp .getMathType(), exp.getMathTypeValue()); // Create a variable expression of the form "?[Argument Name]" quesRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("?" + replName), exp .getMathType(), exp.getMathTypeValue()); } // Case #4: VariableDotExp else if (exp instanceof VariableDotExp) { if (repl instanceof DotExp) { Exp pE = ((DotExp) repl).getSegments().get(0); replName = pE.toString(0); // Create a variable expression of the form "_?[Argument Name]" undqRep = Exp.copy(repl); edu.clemson.cs.r2jt.collections.List<Exp> segList = ((DotExp) undqRep).getSegments(); VariableNameExp undqNameRep = new VariableNameExp(null, null, Utilities .createPosSymbol("_?" + replName)); undqNameRep.setMathType(pE.getMathType()); segList.set(0, undqNameRep); ((DotExp) undqRep).setSegments(segList); // Create a variable expression of the form "?[Argument Name]" quesRep = Exp.copy(repl); segList = ((DotExp) quesRep).getSegments(); segList.set(0, ((VariableDotExp) exp).getSegments().get(0)); ((DotExp) quesRep).setSegments(segList); } else if (repl instanceof VariableDotExp) { Exp pE = ((VariableDotExp) repl).getSegments().get(0); replName = pE.toString(0); // Create a variable expression of the form "_?[Argument Name]" undqRep = Exp.copy(repl); edu.clemson.cs.r2jt.collections.List<VariableExp> segList = ((VariableDotExp) undqRep).getSegments(); VariableNameExp undqNameRep = new VariableNameExp(null, null, Utilities .createPosSymbol("_?" + replName)); undqNameRep.setMathType(pE.getMathType()); segList.set(0, undqNameRep); ((VariableDotExp) undqRep).setSegments(segList); // Create a variable expression of the form "?[Argument Name]" quesRep = Exp.copy(repl); segList = ((VariableDotExp) quesRep).getSegments(); segList.set(0, ((VariableDotExp) exp).getSegments().get(0)); ((VariableDotExp) quesRep).setSegments(segList); } // Error: Case not handled! else { Utilities.expNotHandled(exp, exp.getLocation()); } } // Case #5: VariableNameExp else if (exp instanceof VariableNameExp) { // Name of repl in string form replName = ((VariableNameExp) exp).getName().getName(); // Create a variable expression of the form "_?[Argument Name]" undqRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_?" + replName), exp .getMathType(), exp.getMathTypeValue()); // Create a variable expression of the form "?[Argument Name]" quesRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("?" + replName), exp .getMathType(), exp.getMathTypeValue()); } // Case #6: Result from a nested function call else { // Name of repl in string form replName = varDec.getName().getName(); // Create a variable expression of the form "_?[Argument Name]" undqRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_?" + replName), exp .getMathType(), exp.getMathTypeValue()); // Create a variable expression of the form "?[Argument Name]" quesRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("?" + replName), exp .getMathType(), exp.getMathTypeValue()); } // "#" versions of oldExp and repl oSpecVar = new OldExp(null, Exp.copy(oldExp)); oRealVar = new OldExp(null, Exp.copy(repl)); // Nothing can be null! if (oldExp != null && quesRep != null && oSpecVar != null && repl != null && oRealVar != null) { // Alters, Clears, Reassigns, Replaces, Updates if (varDec.getMode() == Mode.ALTERS || varDec.getMode() == Mode.CLEARS || varDec.getMode() == Mode.REASSIGNS || varDec.getMode() == Mode.REPLACES || varDec.getMode() == Mode.UPDATES) { Exp quesVar; // Obtain the free variable VarExp freeVar = (VarExp) myCurrentAssertiveCode.getFreeVar( Utilities.createPosSymbol(replName), false); if (freeVar == null) { freeVar = Utilities .createVarExp( varDec.getLocation(), null, Utilities .createPosSymbol(replName), varDec.getTy() .getMathTypeValue(), null); } // Apply the question mark to the free variable freeVar = Utilities .createQuestionMarkVariable(myTypeGraph .formConjunct(ensures, newConfirm), freeVar); if (exp instanceof ProgramDotExp || exp instanceof VariableDotExp) { // Make a copy from repl quesVar = Exp.copy(repl); // Replace the free variable in the question mark variable as the first element // in the dot expression. VarExp tmpVar = new VarExp(null, null, freeVar.getName()); tmpVar.setMathType(myTypeGraph.BOOLEAN); edu.clemson.cs.r2jt.collections.List<Exp> segs = ((DotExp) quesVar).getSegments(); segs.set(0, tmpVar); ((DotExp) quesVar).setSegments(segs); } else { // Create a variable expression from free variable quesVar = new VarExp(null, null, freeVar.getName()); quesVar.setMathType(freeVar.getMathType()); quesVar.setMathTypeValue(freeVar.getMathTypeValue()); } // Add the new free variable to free variable list myCurrentAssertiveCode.addFreeVar(freeVar); // Check if our ensures clause has the parameter variable in it. if (ensures.containsVar(VDName.getName(), true) || ensures.containsVar(VDName.getName(), false)) { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, undqRep); ensures = Utilities.replace(ensures, oSpecVar, repl); // Add it to our list of variables to be replaced later undRepList.add(undqRep); replList.add(quesVar); } else { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, quesRep); ensures = Utilities.replace(ensures, oSpecVar, repl); } // Update our final confirm with the parameter argument newConfirm = Utilities.replace(newConfirm, repl, quesVar); myCurrentAssertiveCode.setFinalConfirm(newConfirm, confirmStmt.getSimplify()); } // All other modes else { // Check if our ensures clause has the parameter variable in it. if (ensures.containsVar(VDName.getName(), true) || ensures.containsVar(VDName.getName(), false)) { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, undqRep); ensures = Utilities.replace(ensures, oSpecVar, undqRep); // Add it to our list of variables to be replaced later undRepList.add(undqRep); replList.add(repl); } else { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, repl); ensures = Utilities.replace(ensures, oSpecVar, repl); } } } } // Replace the temp values with the actual values for (int i = 0; i < undRepList.size(); i++) { ensures = Utilities.replace(ensures, undRepList.get(i), replList .get(i)); } return ensures; } /** * <p>Replace the formal with the actual variables * inside the requires clause.</p> * * @param requires The requires clause. * @param paramList The list of parameter variables. * @param argList The list of arguments from the operation call. * * @return The requires clause in <code>Exp</code> form. */ private Exp replaceFormalWithActualReq(Exp requires, List<ParameterVarDec> paramList, List<Exp> argList) { // List to hold temp and real values of variables in case // of duplicate spec and real variables List<Exp> undRepList = new ArrayList<Exp>(); List<Exp> replList = new ArrayList<Exp>(); // Replace precondition variables in the requires clause for (int i = 0; i < argList.size(); i++) { ParameterVarDec varDec = paramList.get(i); Exp exp = argList.get(i); // Convert the pExp into a something we can use Exp repl = Utilities.convertExp(exp); // VarExp form of the parameter variable VarExp oldExp = Utilities.createVarExp(null, null, varDec.getName(), exp .getMathType(), exp.getMathTypeValue()); // New VarExp VarExp newExp = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_" + varDec.getName().getName()), repl.getMathType(), repl.getMathTypeValue()); // Replace the old with the new in the requires clause requires = Utilities.replace(requires, oldExp, newExp); // Add it to our list undRepList.add(newExp); replList.add(repl); } // Replace the temp values with the actual values for (int i = 0; i < undRepList.size(); i++) { requires = Utilities.replace(requires, undRepList.get(i), replList .get(i)); } return requires; } /** * <p>Simplify the assume statement where possible.</p> * * @param stmt The assume statement we want to simplify. * @param exp The current expression we are dealing with. * * @return The modified expression in <code>Exp/code> form. */ private Exp simplifyAssumeRule(AssumeStmt stmt, Exp exp) { // Variables Exp assumeExp = stmt.getAssertion(); List<Exp> assumeExpList = Utilities.splitConjunctExp(assumeExp, new ArrayList<Exp>()); for (int i = 0; i < assumeExpList.size(); i++) { Exp currentExp = assumeExpList.get(i); } // EqualsExp if (assumeExp instanceof EqualsExp) { EqualsExp equalsExp = (EqualsExp) assumeExp; // Do simplifications if we have an equals if (equalsExp.getOperator() == EqualsExp.EQUAL) { // Check to see if the left hand side is an expression // we can replace. if (Utilities.containsReplaceableExp(equalsExp.getLeft())) { // Create a temp expression where left is replaced with the right Exp tmp = Utilities.replace(exp, equalsExp.getLeft(), equalsExp.getRight()); // If tmp hasn't changed, then check to see if the right hand side // is an expression we can replace. if (tmp.equals(exp) && (Utilities.containsReplaceableExp(equalsExp .getRight()))) { tmp = Utilities.replace(exp, equalsExp.getRight(), equalsExp.getLeft()); } // Update exp if we did a replacement if (!tmp.equals(exp)) { exp = tmp; // If this is not a stipulate assume clause, // we can safely get rid of it, otherwise we keep it. if (!stmt.getIsStipulate()) { assumeExp = null; } } } } } // InfixExp else if (assumeExp instanceof InfixExp) { InfixExp infixExp = (InfixExp) assumeExp; // Only do simplifications if we have an and operator if (infixExp.getOpName().equals("and")) { // Recursively call simplify on the left and on the right AssumeStmt left = new AssumeStmt(stmt.getLocation(), Exp.copy(infixExp .getLeft()), stmt.getIsStipulate()); AssumeStmt right = new AssumeStmt(stmt.getLocation(), Exp.copy(infixExp .getRight()), stmt.getIsStipulate()); exp = simplifyAssumeRule(left, exp); exp = simplifyAssumeRule(right, exp); // Case #1: Nothing on the left and nothing on the right if (left.getAssertion() == null && right.getAssertion() == null) { assumeExp = null; } // Case #2: Both still have assertions else if (left.getAssertion() != null && right.getAssertion() != null) { assumeExp = myTypeGraph.formConjunct(left.getAssertion(), right .getAssertion()); } // Case #3: Left still has assertions else if (left.getAssertion() != null) { assumeExp = left.getAssertion(); } // Case #4: Right still has assertions else { assumeExp = right.getAssertion(); } } } // Store the new assertion stmt.setAssertion(assumeExp); return exp; } // ----------------------------------------------------------- // Proof Rules // ----------------------------------------------------------- /** * <p>Applies the assume rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>AssumeStmt</code>. */ private void applyAssumeStmtRule(AssumeStmt stmt) { // Check to see if our assertion just has "True" Exp assertion = stmt.getAssertion(); if (assertion instanceof VarExp && assertion.equals(myTypeGraph.getTrueVarExp())) { // Verbose Mode Debug Messages myVCBuffer.append("\nAssume Rule Applied and Simplified: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Apply simplification ConfirmStmt finalConfirm = myCurrentAssertiveCode.getFinalConfirm(); boolean simplify = finalConfirm.getSimplify(); Exp currentFinalConfirm = simplifyAssumeRule(stmt, finalConfirm.getAssertion()); // Only create an implies expression if the goal is not just "true". // If the goal is "true", then simplify should be true as well. if (stmt.getAssertion() != null && !simplify) { // Create a new implies expression currentFinalConfirm = myTypeGraph.formImplies(stmt.getAssertion(), currentFinalConfirm); simplify = false; } // Set this as our new final confirm myCurrentAssertiveCode.setFinalConfirm(currentFinalConfirm, simplify); // Verbose Mode Debug Messages myVCBuffer.append("\nAssume Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } } /** * <p>Applies the change rule.</p> * * @param change The change clause */ private void applyChangeRule(VerificationStatement change) { List<VariableExp> changeList = (List<VariableExp>) change.getAssertion(); ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp finalConfirm = confirmStmt.getAssertion(); // Loop through each variable for (VariableExp v : changeList) { // v is an instance of VariableNameExp if (v instanceof VariableNameExp) { VariableNameExp vNameExp = (VariableNameExp) v; // Create VarExp for vNameExp VarExp vExp = Utilities.createVarExp(vNameExp.getLocation(), vNameExp .getQualifier(), vNameExp.getName(), vNameExp .getMathType(), vNameExp.getMathTypeValue()); // Create a new question mark variable VarExp newV = Utilities .createQuestionMarkVariable(finalConfirm, vExp); // Add this new variable to our list of free variables myCurrentAssertiveCode.addFreeVar(newV); // Replace all instances of vExp with newV finalConfirm = Utilities.replace(finalConfirm, vExp, newV); } } // Set the modified statement as our new final confirm myCurrentAssertiveCode.setFinalConfirm(finalConfirm, confirmStmt .getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nChange Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the call statement rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>CallStmt</code>. */ private void applyCallStmtRule(CallStmt stmt) { // Call a method to locate the operation dec for this call OperationDec opDec = getOperationDec(stmt.getLocation(), stmt.getQualifier(), stmt .getName(), stmt.getArguments()); boolean isLocal = Utilities.isLocationOperation(stmt.getName().getName(), myCurrentModuleScope); // Get the ensures clause for this operation // Note: If there isn't an ensures clause, it is set to "True" Exp ensures; if (opDec.getEnsures() != null) { ensures = Exp.copy(opDec.getEnsures()); } else { ensures = myTypeGraph.getTrueVarExp(); } // Get the requires clause for this operation Exp requires; boolean simplify = false; if (opDec.getRequires() != null) { requires = Exp.copy(opDec.getRequires()); // Simplify if we just have true if (requires.isLiteralTrue()) { simplify = true; } } else { requires = myTypeGraph.getTrueVarExp(); simplify = true; } // Find all the replacements that needs to happen to the requires // and ensures clauses List<ProgramExp> callArgs = stmt.getArguments(); List<Exp> replaceArgs = modifyArgumentList(callArgs); // Modify ensures using the parameter modes ensures = modifyEnsuresByParameter(ensures, stmt.getLocation(), opDec .getName().getName(), opDec.getParameters(), isLocal); // Replace PreCondition variables in the requires clause requires = replaceFormalWithActualReq(requires, opDec.getParameters(), replaceArgs); // Replace PostCondition variables in the ensures clause ensures = replaceFormalWithActualEns(ensures, opDec.getParameters(), opDec.getStateVars(), replaceArgs, false); // NY YS // Duration for CallStmt if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = (Location) stmt.getLocation().clone(); ConfirmStmt finalConfirm = myCurrentAssertiveCode.getFinalConfirm(); Exp finalConfirmExp = finalConfirm.getAssertion(); // Obtain the corresponding OperationProfileEntry List<PTType> argTypes = new LinkedList<PTType>(); for (ProgramExp arg : stmt.getArguments()) { argTypes.add(arg.getProgramType()); } OperationProfileEntry ope = Utilities.searchOperationProfile(loc, stmt.getQualifier(), stmt.getName(), argTypes, myCurrentModuleScope); // Add the profile ensures as additional assume Exp profileEnsures = ope.getEnsuresClause(); if (profileEnsures != null) { profileEnsures = replaceFormalWithActualEns(profileEnsures, opDec .getParameters(), opDec.getStateVars(), replaceArgs, false); // Obtain the current location if (stmt.getName().getLocation() != null) { // Set the details of the current location Location ensuresLoc = (Location) loc.clone(); ensuresLoc.setDetails("Ensures Clause of " + opDec.getName() + " from Profile " + ope.getName()); Utilities.setLocation(profileEnsures, ensuresLoc); } ensures = myTypeGraph.formConjunct(ensures, profileEnsures); } // Construct the Duration Clause Exp opDur = Exp.copy(ope.getDurationClause()); // Replace PostCondition variables in the duration clause opDur = replaceFormalWithActualEns(opDur, opDec.getParameters(), opDec.getStateVars(), replaceArgs, false); VarExp cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(finalConfirmExp)), myTypeGraph.R, null); Exp durCallExp = Utilities.createDurCallExp((Location) loc.clone(), Integer .toString(opDec.getParameters().size()), Z, myTypeGraph.R); InfixExp sumEvalDur = new InfixExp((Location) loc.clone(), opDur, Utilities .createPosSymbol("+"), durCallExp); sumEvalDur.setMathType(myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), sumEvalDur); sumEvalDur.setMathType(myTypeGraph.R); // For any evaluates mode expression, we need to finalize the variable edu.clemson.cs.r2jt.collections.List<ProgramExp> assignExpList = stmt.getArguments(); for (int i = 0; i < assignExpList.size(); i++) { ParameterVarDec p = opDec.getParameters().get(i); VariableExp pExp = (VariableExp) assignExpList.get(i); if (p.getMode() == Mode.EVALUATES) { VarDec v = new VarDec(Utilities.getVarName(pExp), p.getTy()); FunctionExp finalDur = Utilities.createFinalizAnyDur(v, myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), sumEvalDur, Utilities.createPosSymbol("+"), finalDur); sumEvalDur.setMathType(myTypeGraph.R); } } // Replace Cum_Dur in our final ensures clause finalConfirmExp = Utilities.replace(finalConfirmExp, cumDur, sumEvalDur); myCurrentAssertiveCode.setFinalConfirm(finalConfirmExp, finalConfirm.getSimplify()); } // Modify the location of the requires clause and add it to myCurrentAssertiveCode if (requires != null) { // Obtain the current location // Note: If we don't have a location, we create one Location loc; if (stmt.getName().getLocation() != null) { loc = (Location) stmt.getName().getLocation().clone(); } else { loc = new Location(null, null); } // Append the name of the current procedure String details = ""; if (myCurrentOperationEntry != null) { details = " in Procedure " + myCurrentOperationEntry.getName(); } // Set the details of the current location loc.setDetails("Requires Clause of " + opDec.getName() + details); Utilities.setLocation(requires, loc); // Add this to our list of things to confirm myCurrentAssertiveCode.addConfirm((Location) loc.clone(), requires, simplify); } // Modify the location of the requires clause and add it to myCurrentAssertiveCode if (ensures != null) { // Obtain the current location Location loc = null; if (stmt.getName().getLocation() != null) { // Set the details of the current location loc = (Location) stmt.getName().getLocation().clone(); loc.setDetails("Ensures Clause of " + opDec.getName()); Utilities.setLocation(ensures, loc); } // Add this to our list of things to assume myCurrentAssertiveCode.addAssume(loc, ensures, false); } // Verbose Mode Debug Messages myVCBuffer.append("\nOperation Call Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies different rules to code statements.</p> * * @param statement The different statements. */ private void applyCodeRules(Statement statement) { // Apply each statement rule here. if (statement instanceof AssumeStmt) { applyAssumeStmtRule((AssumeStmt) statement); } else if (statement instanceof CallStmt) { applyCallStmtRule((CallStmt) statement); } else if (statement instanceof ConfirmStmt) { applyConfirmStmtRule((ConfirmStmt) statement); } else if (statement instanceof FuncAssignStmt) { applyFuncAssignStmtRule((FuncAssignStmt) statement); } else if (statement instanceof IfStmt) { applyIfStmtRule((IfStmt) statement); } else if (statement instanceof MemoryStmt) { // TODO: Deal with Forget if (((MemoryStmt) statement).isRemember()) { applyRememberRule(); } } else if (statement instanceof SwapStmt) { applySwapStmtRule((SwapStmt) statement); } else if (statement instanceof WhileStmt) { applyWhileStmtRule((WhileStmt) statement); } } /** * <p>Applies the confirm rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>ConfirmStmt</code>. */ private void applyConfirmStmtRule(ConfirmStmt stmt) { // Check to see if our assertion can be simplified Exp assertion = stmt.getAssertion(); if (stmt.getSimplify()) { // Verbose Mode Debug Messages myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Obtain the current final confirm statement ConfirmStmt currentFinalConfirm = myCurrentAssertiveCode.getFinalConfirm(); // Check to see if we can simplify the final confirm if (currentFinalConfirm.getSimplify()) { // Obtain the current location if (assertion.getLocation() != null) { // Set the details of the current location Location loc = (Location) assertion.getLocation().clone(); Utilities.setLocation(assertion, loc); } myCurrentAssertiveCode.setFinalConfirm(assertion, stmt .getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Create a new and expression InfixExp newConf = myTypeGraph.formConjunct(assertion, currentFinalConfirm .getAssertion()); // Set this new expression as the new final confirm myCurrentAssertiveCode.setFinalConfirm(newConf, false); // Verbose Mode Debug Messages myVCBuffer.append("\nConfirm Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } } } /** * <p>Applies the correspondence rule.</p> * * @param dec Representation declaration object. */ private void applyCorrespondenceRule(RepresentationDec dec) { // Create a new assertive code to hold the correspondence VCs AssertiveCode assertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Obtain the location for each assume clause Location decLoc = dec.getLocation(); // Add the global constraints as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalConstraintExp, false); // Add the global require clause as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalRequiresExp, false); // Add the convention as given assertiveCode.addAssume((Location) decLoc.clone(), dec.getConvention(), false); // Add the correspondence as given myCorrespondenceExp = dec.getCorrespondence(); assertiveCode.addAssume((Location) decLoc.clone(), myCorrespondenceExp, false); // Search for the type we are implementing SymbolTableEntry ste = Utilities.searchProgramType(dec.getLocation(), null, dec .getName(), myCurrentModuleScope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(dec.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry(dec.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type .getExemplar(), typeEntry.getModelType(), null); DotExp conceptualVar = Utilities.createConcVarExp(null, exemplar, typeEntry .getModelType(), BOOLEAN); // Make sure we have a constraint Exp constraint; if (type.getConstraint() == null) { constraint = myTypeGraph.getTrueVarExp(); } else { constraint = Exp.copy(type.getConstraint()); } constraint = Utilities.replace(constraint, exemplar, conceptualVar); // Set the location for the constraint Location loc; if (myCorrespondenceExp.getLocation() != null) { loc = (Location) myCorrespondenceExp.getLocation().clone(); } else { loc = (Location) type.getLocation().clone(); } loc.setDetails("Well Defined Correspondence for " + dec.getName().getName()); Utilities.setLocation(constraint, loc); // We need to make sure the constraints for the type we are // implementing is met. boolean simplify = false; // Simplify if we just have true if (constraint.isLiteralTrue()) { simplify = true; } assertiveCode.setFinalConfirm(constraint, simplify); // Add the constraints for the implementing facility // or for each of the fields inside the record. Exp fieldConstraints = myTypeGraph.getTrueVarExp(); if (dec.getRepresentation() instanceof NameTy) { NameTy ty = (NameTy) dec.getRepresentation(); fieldConstraints = Utilities.retrieveConstraint(ty.getLocation(), ty .getQualifier(), ty.getName(), exemplar, myCurrentModuleScope); } else { RecordTy ty = (RecordTy) dec.getRepresentation(); // Find the constraints for each field inside the record. for (VarDec v : ty.getFields()) { NameTy vTy = (NameTy) v.getTy(); // Create the name of the variable VarExp vName = Utilities.createVarExp(null, null, v.getName(), vTy .getMathType(), vTy.getMathTypeValue()); // Create [Exemplar].[v] dotted expression edu.clemson.cs.r2jt.collections.List<Exp> dotExpList = new edu.clemson.cs.r2jt.collections.List<Exp>(); dotExpList.add(exemplar); dotExpList.add(vName); DotExp varNameExp = Utilities.createDotExp(v.getLocation(), dotExpList, v.getMathType()); Exp vConstraint = Utilities.retrieveConstraint(vTy.getLocation(), vTy .getQualifier(), vTy.getName(), varNameExp, myCurrentModuleScope); if (fieldConstraints.isLiteralTrue()) { fieldConstraints = vConstraint; } else { fieldConstraints = myTypeGraph.formConjunct(fieldConstraints, vConstraint); } } } // Only add the field constraints if we don't have true if (!fieldConstraints.isLiteralTrue()) { assertiveCode.addAssume(loc, fieldConstraints, false); } } // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(assertiveCode); // Verbose Mode Debug Messages String newString = "\n========================= Type Representation Name:\t" + dec.getName().getName() + " =========================\n"; newString += "\nCorrespondence Rule Applied: \n"; newString += assertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } /** * <p>Applies the facility declaration rule.</p> * * @param dec Facility declaration object. */ private void applyFacilityDeclRule(FacilityDec dec) { // Create a new assertive code to hold the facility declaration VCs AssertiveCode assertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Location for the assume clauses Location decLoc = dec.getLocation(); // Add the global constraints as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalConstraintExp, false); // Add the global require clause as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalRequiresExp, false); // TODO: Loop through every enhancement/enhancement realization declaration, if any. // Obtain the concept module for the facility try { ConceptModuleDec facConceptDec = (ConceptModuleDec) mySymbolTable .getModuleScope( new ModuleIdentifier(dec.getConceptName() .getName())).getDefiningElement(); // Concept parameters List<ModuleArgumentItem> conceptParams = dec.getConceptParams(); // Concept requires clause Exp req = getRequiresClause(facConceptDec.getLocation(), facConceptDec); Location loc = (Location) dec.getName().getLocation().clone(); loc.setDetails("Facility Declaration Rule"); req = Utilities.replaceFacilityDeclarationVariables(req, facConceptDec.getParameters(), conceptParams); req.setLocation(loc); boolean simplify = false; // Simplify if we just have true if (req.isLiteralTrue()) { simplify = true; } assertiveCode.setFinalConfirm(req, simplify); // Obtain the constraint of the concept type Exp assumeExp = null; // TODO: This is ugly! Need to clean this up! List<ModuleParameterDec> moduleParameterList = facConceptDec.getParameters(); List<EqualsExp> formalToActualList = new LinkedList<EqualsExp>(); for (int i = 0; i < moduleParameterList.size(); i++) { ModuleParameterDec m = moduleParameterList.get(i); if (m.getWrappedDec() instanceof ConstantParamDec) { ConstantParamDec constantParamDec = (ConstantParamDec) m.getWrappedDec(); VarDec tempDec = new VarDec(constantParamDec.getName(), constantParamDec.getTy()); // Search for the ProgramTypeEntry // Ty is NameTy if (tempDec.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) tempDec.getTy(); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities .searchProgramType(pNameTy .getLocation(), pNameTy .getQualifier(), pNameTy .getName(), myCurrentModuleScope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy .getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); } // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the declared variable VarExp varDecExp = Utilities.createVarExp(tempDec.getLocation(), null, tempDec.getName(), typeEntry .getModelType(), null); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type.getExemplar(), typeEntry .getModelType(), null); // Make sure we have a constraint Exp constraint; if (type.getConstraint() == null) { constraint = myTypeGraph.getTrueVarExp(); } else { constraint = Exp.copy(type.getConstraint()); } constraint = Utilities.replace(constraint, exemplar, varDecExp); // Set the location for the constraint Location constraintLoc; if (constraint.getLocation() != null) { constraintLoc = (Location) constraint.getLocation().clone(); } else { constraintLoc = (Location) type.getLocation().clone(); } constraintLoc.setDetails("Constraints on " + tempDec.getName().getName()); Utilities.setLocation(constraint, constraintLoc); // Replace with facility declaration variables constraint = Utilities .replaceFacilityDeclarationVariables( constraint, facConceptDec .getParameters(), conceptParams); if (assumeExp == null) { assumeExp = constraint; } else { assumeExp = myTypeGraph.formConjunct(assumeExp, constraint); } // TODO: Change this! This is such a hack! // Create an equals expression from formal to actual Exp actualExp; if (conceptParams.get(i).getEvalExp() != null) { actualExp = Utilities.convertExp(conceptParams.get(i) .getEvalExp()); } else { actualExp = Exp.copy(varDecExp); } EqualsExp formalEq = new EqualsExp(dec.getLocation(), varDecExp, 1, actualExp); formalEq.setMathType(BOOLEAN); formalToActualList.add(formalEq); } else { // Ty not handled. Utilities.tyNotHandled(tempDec.getTy(), tempDec .getLocation()); } } } // Make sure it is not null if (assumeExp == null) { assumeExp = myTypeGraph.getTrueVarExp(); } myFacilityDeclarationMap.put(dec, assumeExp); myFacilityFormalActualMap.put(dec, formalToActualList); } catch (NoSuchSymbolException e) { Utilities.noSuchModule(dec.getLocation()); } // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(assertiveCode); // Verbose Mode Debug Messages String newString = "\n========================= Facility Dec Name:\t" + dec.getName().getName() + " =========================\n"; newString += "\nFacility Declaration Rule Applied: \n"; newString += assertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } /** * <p>Applies the function assignment rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>FuncAssignStmt</code>. */ private void applyFuncAssignStmtRule(FuncAssignStmt stmt) { PosSymbol qualifier = null; ProgramExp assignExp = stmt.getAssign(); ProgramParamExp assignParamExp = null; // Replace all instances of the variable on the left hand side // in the ensures clause with the expression on the right. Exp leftVariable; // We have a variable inside a record as the variable being assigned. if (stmt.getVar() instanceof VariableDotExp) { VariableDotExp v = (VariableDotExp) stmt.getVar(); List<VariableExp> vList = v.getSegments(); edu.clemson.cs.r2jt.collections.List<Exp> newSegments = new edu.clemson.cs.r2jt.collections.List<Exp>(); // Loot through each variable expression and add it to our dot list for (VariableExp vr : vList) { VarExp varExp = new VarExp(); if (vr instanceof VariableNameExp) { varExp.setName(((VariableNameExp) vr).getName()); varExp.setMathType(vr.getMathType()); varExp.setMathTypeValue(vr.getMathTypeValue()); newSegments.add(varExp); } } // Expression to be replaced leftVariable = new DotExp(v.getLocation(), newSegments, null); leftVariable.setMathType(v.getMathType()); leftVariable.setMathTypeValue(v.getMathTypeValue()); } // We have a regular variable being assigned. else { // Expression to be replaced VariableNameExp v = (VariableNameExp) stmt.getVar(); leftVariable = new VarExp(v.getLocation(), null, v.getName()); leftVariable.setMathType(v.getMathType()); leftVariable.setMathTypeValue(v.getMathTypeValue()); } // Simply replace the numbers/characters/strings if (assignExp instanceof ProgramIntegerExp || assignExp instanceof ProgramCharExp || assignExp instanceof ProgramStringExp) { Exp replaceExp = Utilities.convertExp(assignExp); // Replace all instances of the left hand side // variable in the current final confirm statement. ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp newConf = confirmStmt.getAssertion(); newConf = Utilities.replace(newConf, leftVariable, replaceExp); // Set this as our new final confirm statement. myCurrentAssertiveCode.setFinalConfirm(newConf, confirmStmt .getSimplify()); } else { // Check to see what kind of expression is on the right hand side if (assignExp instanceof ProgramParamExp) { // Cast to a ProgramParamExp assignParamExp = (ProgramParamExp) assignExp; } else if (assignExp instanceof ProgramDotExp) { // Cast to a ProgramParamExp ProgramDotExp dotExp = (ProgramDotExp) assignExp; assignParamExp = (ProgramParamExp) dotExp.getExp(); qualifier = dotExp.getQualifier(); } // Call a method to locate the operation dec for this call OperationDec opDec = getOperationDec(stmt.getLocation(), qualifier, assignParamExp.getName(), assignParamExp .getArguments()); // Check for recursive call of itself if (myCurrentOperationEntry != null && myCurrentOperationEntry.getName().equals( opDec.getName().getName()) && myCurrentOperationEntry.getReturnType() != null) { // Create a new confirm statement using P_val and the decreasing clause VarExp pVal = Utilities.createPValExp(myOperationDecreasingExp .getLocation(), myCurrentModuleScope); // Create a new infix expression IntegerExp oneExp = new IntegerExp(); oneExp.setValue(1); oneExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp leftExp = new InfixExp(stmt.getLocation(), oneExp, Utilities .createPosSymbol("+"), Exp .copy(myOperationDecreasingExp)); leftExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp exp = Utilities.createLessThanEqExp(stmt.getLocation(), leftExp, pVal, BOOLEAN); // Create the new confirm statement Location loc; if (myOperationDecreasingExp.getLocation() != null) { loc = (Location) myOperationDecreasingExp.getLocation() .clone(); } else { loc = (Location) stmt.getLocation().clone(); } loc.setDetails("Show Termination of Recursive Call"); Utilities.setLocation(exp, loc); ConfirmStmt conf = new ConfirmStmt(loc, exp, false); // Add it to our list of assertions myCurrentAssertiveCode.addCode(conf); } // Get the requires clause for this operation Exp requires; boolean simplify = false; if (opDec.getRequires() != null) { requires = Exp.copy(opDec.getRequires()); // Simplify if we just have true if (requires.isLiteralTrue()) { simplify = true; } } else { requires = myTypeGraph.getTrueVarExp(); simplify = true; } // Find all the replacements that needs to happen to the requires // and ensures clauses List<ProgramExp> callArgs = assignParamExp.getArguments(); List<Exp> replaceArgs = modifyArgumentList(callArgs); // Replace PreCondition variables in the requires clause requires = replaceFormalWithActualReq(requires, opDec.getParameters(), replaceArgs); // Modify the location of the requires clause and add it to myCurrentAssertiveCode // Obtain the current location // Note: If we don't have a location, we create one Location reqloc; if (assignParamExp.getName().getLocation() != null) { reqloc = (Location) assignParamExp.getName().getLocation() .clone(); } else { reqloc = new Location(null, null); } // Append the name of the current procedure String details = ""; if (myCurrentOperationEntry != null) { details = " in Procedure " + myCurrentOperationEntry.getName(); } // Set the details of the current location reqloc .setDetails("Requires Clause of " + opDec.getName() + details); Utilities.setLocation(requires, reqloc); // Add this to our list of things to confirm myCurrentAssertiveCode.addConfirm((Location) reqloc.clone(), requires, simplify); // Get the ensures clause for this operation // Note: If there isn't an ensures clause, it is set to "True" Exp ensures, opEnsures; if (opDec.getEnsures() != null) { opEnsures = Exp.copy(opDec.getEnsures()); // Make sure we have an EqualsExp, else it is an error. if (opEnsures instanceof EqualsExp) { // Has to be a VarExp on the left hand side (containing the name // of the function operation) if (((EqualsExp) opEnsures).getLeft() instanceof VarExp) { VarExp leftExp = (VarExp) ((EqualsExp) opEnsures).getLeft(); // Check if it has the name of the operation if (leftExp.getName().equals(opDec.getName())) { ensures = ((EqualsExp) opEnsures).getRight(); // Obtain the current location if (assignParamExp.getName().getLocation() != null) { // Set the details of the current location Location loc = (Location) assignParamExp.getName() .getLocation().clone(); loc.setDetails("Ensures Clause of " + opDec.getName()); Utilities.setLocation(ensures, loc); } // Replace the formal with the actual ensures = replaceFormalWithActualEns(ensures, opDec .getParameters(), opDec .getStateVars(), replaceArgs, true); // Replace all instances of the left hand side // variable in the current final confirm statement. ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp newConf = confirmStmt.getAssertion(); newConf = Utilities.replace(newConf, leftVariable, ensures); // Set this as our new final confirm statement. myCurrentAssertiveCode.setFinalConfirm(newConf, confirmStmt.getSimplify()); // NY YS // Duration for CallStmt if (myInstanceEnvironment.flags .isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = (Location) stmt.getLocation().clone(); ConfirmStmt finalConfirm = myCurrentAssertiveCode .getFinalConfirm(); Exp finalConfirmExp = finalConfirm.getAssertion(); // Obtain the corresponding OperationProfileEntry List<PTType> argTypes = new LinkedList<PTType>(); for (ProgramExp arg : assignParamExp .getArguments()) { argTypes.add(arg.getProgramType()); } OperationProfileEntry ope = Utilities.searchOperationProfile(loc, qualifier, assignParamExp .getName(), argTypes, myCurrentModuleScope); // Add the profile ensures as additional assume Exp profileEnsures = ope.getEnsuresClause(); if (profileEnsures != null) { profileEnsures = replaceFormalWithActualEns( profileEnsures, opDec .getParameters(), opDec.getStateVars(), replaceArgs, false); // Obtain the current location if (assignParamExp.getLocation() != null) { // Set the details of the current location Location ensuresLoc = (Location) loc.clone(); ensuresLoc .setDetails("Ensures Clause of " + opDec.getName() + " from Profile " + ope.getName()); Utilities.setLocation(profileEnsures, ensuresLoc); } finalConfirmExp = myTypeGraph.formConjunct( finalConfirmExp, profileEnsures); } // Construct the Duration Clause Exp opDur = Exp.copy(ope.getDurationClause()); // Replace PostCondition variables in the duration clause opDur = replaceFormalWithActualEns(opDur, opDec .getParameters(), opDec .getStateVars(), replaceArgs, false); VarExp cumDur = Utilities .createVarExp( (Location) loc.clone(), null, Utilities .createPosSymbol(Utilities .getCumDur(finalConfirmExp)), myTypeGraph.R, null); Exp durCallExp = Utilities .createDurCallExp( (Location) loc.clone(), Integer .toString(opDec .getParameters() .size()), Z, myTypeGraph.R); InfixExp sumEvalDur = new InfixExp((Location) loc.clone(), opDur, Utilities .createPosSymbol("+"), durCallExp); sumEvalDur.setMathType(myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities .createPosSymbol("+"), sumEvalDur); sumEvalDur.setMathType(myTypeGraph.R); // For any evaluates mode expression, we need to finalize the variable edu.clemson.cs.r2jt.collections.List<ProgramExp> assignExpList = assignParamExp.getArguments(); for (int i = 0; i < assignExpList.size(); i++) { ParameterVarDec p = opDec.getParameters().get(i); VariableExp pExp = (VariableExp) assignExpList.get(i); if (p.getMode() == Mode.EVALUATES) { VarDec v = new VarDec(Utilities .getVarName(pExp), p .getTy()); FunctionExp finalDur = Utilities.createFinalizAnyDur( v, myTypeGraph.R); sumEvalDur = new InfixExp( (Location) loc.clone(), sumEvalDur, Utilities .createPosSymbol("+"), finalDur); sumEvalDur.setMathType(myTypeGraph.R); } } // Add duration of assignment and finalize the temporary variable Exp assignDur = Utilities.createVarExp((Location) loc .clone(), null, Utilities .createPosSymbol("Dur_Assgn"), myTypeGraph.R, null); sumEvalDur = new InfixExp((Location) loc.clone(), sumEvalDur, Utilities .createPosSymbol("+"), assignDur); sumEvalDur.setMathType(myTypeGraph.R); Exp finalExpDur = Utilities.createFinalizAnyDurExp(stmt .getVar(), myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), sumEvalDur, Utilities .createPosSymbol("+"), finalExpDur); sumEvalDur.setMathType(myTypeGraph.R); // Replace Cum_Dur in our final ensures clause finalConfirmExp = Utilities.replace(finalConfirmExp, cumDur, sumEvalDur); myCurrentAssertiveCode.setFinalConfirm( finalConfirmExp, finalConfirm .getSimplify()); } } else { Utilities.illegalOperationEnsures(opDec .getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } } // Verbose Mode Debug Messages myVCBuffer.append("\nFunction Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the if statement rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>IfStmt</code>. */ private void applyIfStmtRule(IfStmt stmt) { // Note: In the If Rule, we will have two instances of the assertive code. // One for when the if condition is true and one for the else condition. // The current global assertive code variable is going to be used for the if path, // and we are going to create a new assertive code for the else path (this includes // the case when there is no else clause). ProgramExp ifCondition = stmt.getTest(); // Negation of If (Need to make a copy before we start modifying // the current assertive code for the if part) AssertiveCode negIfAssertiveCode = new AssertiveCode(myCurrentAssertiveCode); // Call a method to locate the operation dec for this call PosSymbol qualifier = null; ProgramParamExp testParamExp = null; // Check to see what kind of expression is on the right hand side if (ifCondition instanceof ProgramParamExp) { // Cast to a ProgramParamExp testParamExp = (ProgramParamExp) ifCondition; } else if (ifCondition instanceof ProgramDotExp) { // Cast to a ProgramParamExp ProgramDotExp dotExp = (ProgramDotExp) ifCondition; testParamExp = (ProgramParamExp) dotExp.getExp(); qualifier = dotExp.getQualifier(); } else { Utilities.expNotHandled(ifCondition, stmt.getLocation()); } Location ifConditionLoc; if (ifCondition.getLocation() != null) { ifConditionLoc = (Location) ifCondition.getLocation().clone(); } else { ifConditionLoc = (Location) stmt.getLocation().clone(); } OperationDec opDec = getOperationDec(ifCondition.getLocation(), qualifier, testParamExp.getName(), testParamExp.getArguments()); // Check for recursive call of itself if (myCurrentOperationEntry != null && myCurrentOperationEntry.getName().equals( opDec.getName().getName()) && myCurrentOperationEntry.getReturnType() != null) { // Create a new confirm statement using P_val and the decreasing clause VarExp pVal = Utilities.createPValExp(myOperationDecreasingExp .getLocation(), myCurrentModuleScope); // Create a new infix expression IntegerExp oneExp = new IntegerExp(); oneExp.setValue(1); oneExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp leftExp = new InfixExp(stmt.getLocation(), oneExp, Utilities .createPosSymbol("+"), Exp .copy(myOperationDecreasingExp)); leftExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp exp = Utilities.createLessThanEqExp(stmt.getLocation(), leftExp, pVal, BOOLEAN); // Create the new confirm statement Location loc; if (myOperationDecreasingExp.getLocation() != null) { loc = (Location) myOperationDecreasingExp.getLocation().clone(); } else { loc = (Location) stmt.getLocation().clone(); } loc.setDetails("Show Termination of Recursive Call"); Utilities.setLocation(exp, loc); ConfirmStmt conf = new ConfirmStmt(loc, exp, false); // Add it to our list of assertions myCurrentAssertiveCode.addCode(conf); } // Confirm the invoking condition // Get the requires clause for this operation Exp requires; boolean simplify = false; if (opDec.getRequires() != null) { requires = Exp.copy(opDec.getRequires()); // Simplify if we just have true if (requires.isLiteralTrue()) { simplify = true; } } else { requires = myTypeGraph.getTrueVarExp(); simplify = true; } // Find all the replacements that needs to happen to the requires // and ensures clauses List<ProgramExp> callArgs = testParamExp.getArguments(); List<Exp> replaceArgs = modifyArgumentList(callArgs); // Replace PreCondition variables in the requires clause requires = replaceFormalWithActualReq(requires, opDec.getParameters(), replaceArgs); // Modify the location of the requires clause and add it to myCurrentAssertiveCode // Obtain the current location // Note: If we don't have a location, we create one Location reqloc; if (testParamExp.getName().getLocation() != null) { reqloc = (Location) testParamExp.getName().getLocation().clone(); } else { reqloc = new Location(null, null); } // Set the details of the current location reqloc.setDetails("Requires Clause of " + opDec.getName()); Utilities.setLocation(requires, reqloc); // Add this to our list of things to confirm myCurrentAssertiveCode.addConfirm((Location) reqloc.clone(), requires, simplify); // Add the if condition as the assume clause // Get the ensures clause for this operation // Note: If there isn't an ensures clause, it is set to "True" Exp ensures, negEnsures = null, opEnsures; if (opDec.getEnsures() != null) { opEnsures = Exp.copy(opDec.getEnsures()); // Make sure we have an EqualsExp, else it is an error. if (opEnsures instanceof EqualsExp) { // Has to be a VarExp on the left hand side (containing the name // of the function operation) if (((EqualsExp) opEnsures).getLeft() instanceof VarExp) { VarExp leftExp = (VarExp) ((EqualsExp) opEnsures).getLeft(); // Check if it has the name of the operation if (leftExp.getName().equals(opDec.getName())) { ensures = ((EqualsExp) opEnsures).getRight(); // Obtain the current location Location loc = null; if (testParamExp.getName().getLocation() != null) { // Set the details of the current location loc = (Location) testParamExp.getName() .getLocation().clone(); loc.setDetails("If Statement Condition"); Utilities.setLocation(ensures, loc); } // Replace the formals with the actuals. ensures = replaceFormalWithActualEns(ensures, opDec .getParameters(), opDec.getStateVars(), replaceArgs, false); myCurrentAssertiveCode.addAssume(loc, ensures, true); // Negation of the condition negEnsures = Utilities.negateExp(ensures, BOOLEAN); } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } // Create a list for the then clause edu.clemson.cs.r2jt.collections.List<Statement> thenStmtList; if (stmt.getThenclause() != null) { thenStmtList = stmt.getThenclause(); } else { thenStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); } // Modify the confirm details ConfirmStmt ifConfirm = myCurrentAssertiveCode.getFinalConfirm(); Exp ifConfirmExp = ifConfirm.getAssertion(); Location ifLocation; if (ifConfirmExp.getLocation() != null) { ifLocation = (Location) ifConfirmExp.getLocation().clone(); } else { ifLocation = (Location) stmt.getLocation().clone(); } String ifDetail = ifLocation.getDetails() + ", Condition at " + ifConditionLoc.toString() + " is true"; ifLocation.setDetails(ifDetail); ifConfirmExp.setLocation(ifLocation); // NY YS // Duration for If Part InfixExp sumEvalDur = null; if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = (Location) ifLocation.clone(); VarExp cumDur; boolean trueConfirm = false; // Our previous rule must have been a while rule ConfirmStmt conf = null; if (ifConfirmExp.isLiteralTrue() && thenStmtList.size() != 0) { Statement st = thenStmtList.get(thenStmtList.size() - 1); if (st instanceof ConfirmStmt) { conf = (ConfirmStmt) st; cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(conf.getAssertion())), myTypeGraph.R, null); trueConfirm = true; } else { cumDur = null; Utilities.noSuchSymbol(null, "Cum_Dur", loc); } } else { cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(ifConfirmExp)), myTypeGraph.R, null); } // Search for operation profile List<PTType> argTypes = new LinkedList<PTType>(); List<ProgramExp> argsList = testParamExp.getArguments(); for (ProgramExp arg : argsList) { argTypes.add(arg.getProgramType()); } OperationProfileEntry ope = Utilities.searchOperationProfile(loc, qualifier, testParamExp.getName(), argTypes, myCurrentModuleScope); Exp opDur = Exp.copy(ope.getDurationClause()); Exp durCallExp = Utilities.createDurCallExp(loc, Integer.toString(opDec .getParameters().size()), Z, myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), opDur, Utilities .createPosSymbol("+"), durCallExp); sumEvalDur.setMathType(myTypeGraph.R); Exp sumPlusCumDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), Exp .copy(sumEvalDur)); sumPlusCumDur.setMathType(myTypeGraph.R); if (trueConfirm && conf != null) { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" Exp confirm = conf.getAssertion(); confirm = Utilities.replace(confirm, cumDur, Exp .copy(sumPlusCumDur)); conf.setAssertion(confirm); thenStmtList.set(thenStmtList.size() - 1, conf); } else { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" ifConfirmExp = Utilities.replace(ifConfirmExp, cumDur, Exp .copy(sumPlusCumDur)); } } // Add the statements inside the if to the assertive code myCurrentAssertiveCode.addStatements(thenStmtList); // Set the final if confirm myCurrentAssertiveCode.setFinalConfirm(ifConfirmExp, ifConfirm .getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nIf Part Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); // Add the negation of the if condition as the assume clause if (negEnsures != null) { negIfAssertiveCode.addAssume(ifLocation, negEnsures, true); } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } // Create a list for the then clause edu.clemson.cs.r2jt.collections.List<Statement> elseStmtList; if (stmt.getElseclause() != null) { elseStmtList = stmt.getElseclause(); } else { elseStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); } // Modify the confirm details ConfirmStmt negIfConfirm = negIfAssertiveCode.getFinalConfirm(); Exp negIfConfirmExp = negIfConfirm.getAssertion(); Location negIfLocation; if (negIfConfirmExp.getLocation() != null) { negIfLocation = (Location) negIfConfirmExp.getLocation().clone(); } else { negIfLocation = (Location) stmt.getLocation().clone(); } String negIfDetail = negIfLocation.getDetails() + ", Condition at " + ifConditionLoc.toString() + " is false"; negIfLocation.setDetails(negIfDetail); negIfConfirmExp.setLocation(negIfLocation); // NY YS // Duration for Else Part if (sumEvalDur != null) { Location loc = (Location) negIfLocation.clone(); VarExp cumDur; boolean trueConfirm = false; // Our previous rule must have been a while rule ConfirmStmt conf = null; if (negIfConfirmExp.isLiteralTrue() && elseStmtList.size() != 0) { Statement st = elseStmtList.get(elseStmtList.size() - 1); if (st instanceof ConfirmStmt) { conf = (ConfirmStmt) st; cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(conf.getAssertion())), myTypeGraph.R, null); trueConfirm = true; } else { cumDur = null; Utilities.noSuchSymbol(null, "Cum_Dur", loc); } } else { cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(negIfConfirmExp)), myTypeGraph.R, null); } Exp sumPlusCumDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), Exp .copy(sumEvalDur)); sumPlusCumDur.setMathType(myTypeGraph.R); if (trueConfirm && conf != null) { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" Exp confirm = conf.getAssertion(); confirm = Utilities.replace(confirm, cumDur, Exp .copy(sumPlusCumDur)); conf.setAssertion(confirm); elseStmtList.set(elseStmtList.size() - 1, conf); } else { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" negIfConfirmExp = Utilities.replace(negIfConfirmExp, cumDur, Exp .copy(sumPlusCumDur)); } } // Add the statements inside the else to the assertive code negIfAssertiveCode.addStatements(elseStmtList); // Set the final else confirm negIfAssertiveCode.setFinalConfirm(negIfConfirmExp, negIfConfirm .getSimplify()); // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(negIfAssertiveCode); // Verbose Mode Debug Messages String newString = "\nNegation of If Part Rule Applied: \n"; newString += negIfAssertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } /** * <p>Applies the initialization rule.</p> * * @param dec Representation declaration object. */ private void applyInitializationRule(RepresentationDec dec) { // Create a new assertive code to hold the correspondence VCs AssertiveCode assertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Location for the assume clauses Location decLoc = dec.getLocation(); // Add the global constraints as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalConstraintExp, false); // Add the global require clause as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalRequiresExp, false); // Add any variable declarations for records if (dec.getRepresentation() instanceof RecordTy) { RecordTy ty = (RecordTy) dec.getRepresentation(); assertiveCode.addVariableDecs(ty.getFields()); } // Add any statements in the initialization block if (dec.getInitialization() != null) { InitItem initItem = dec.getInitialization(); assertiveCode.addStatements(initItem.getStatements()); } // Search for the type we are implementing SymbolTableEntry ste = Utilities.searchProgramType(dec.getLocation(), null, dec .getName(), myCurrentModuleScope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(dec.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry(dec.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type .getExemplar(), typeEntry.getModelType(), null); // Add the correspondence as given assertiveCode.addAssume((Location) decLoc.clone(), dec .getCorrespondence(), false); // Make sure we have a convention if (dec.getConvention() == null) { myConventionExp = myTypeGraph.getTrueVarExp(); } else { myConventionExp = Exp.copy(dec.getConvention()); } // Set the location for the constraint Location loc; if (myConventionExp.getLocation() != null) { loc = (Location) myConventionExp.getLocation().clone(); } else { loc = (Location) dec.getLocation().clone(); } loc.setDetails("Convention for " + dec.getName().getName()); Utilities.setLocation(myConventionExp, loc); // Add the convention as something we need to confirm boolean simplify = false; // Simplify if we just have true if (myConventionExp.isLiteralTrue()) { simplify = true; } Exp convention = Exp.copy(myConventionExp); Location conventionLoc = (Location) convention.getLocation().clone(); conventionLoc.setDetails(conventionLoc.getDetails() + " generated by Initialization Rule"); Utilities.setLocation(convention, conventionLoc); assertiveCode.addConfirm(loc, convention, simplify); // Create a variable that refers to the conceptual exemplar DotExp conceptualVar = Utilities.createConcVarExp(null, exemplar, typeEntry .getModelType(), BOOLEAN); // Make sure we have a constraint Exp init; if (type.getInitialization().getEnsures() == null) { init = myTypeGraph.getTrueVarExp(); } else { init = Exp.copy(type.getInitialization().getEnsures()); } init = Utilities.replace(init, exemplar, conceptualVar); // Set the location for the constraint Location initLoc; initLoc = (Location) dec.getLocation().clone(); initLoc.setDetails("Initialization Rule for " + dec.getName().getName()); Utilities.setLocation(init, initLoc); // Add the initialization as something we need to confirm simplify = false; // Simplify if we just have true if (init.isLiteralTrue()) { simplify = true; } assertiveCode.addConfirm(loc, init, simplify); } // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(assertiveCode); // Verbose Mode Debug Messages String newString = "\n========================= Type Representation Name:\t" + dec.getName().getName() + " =========================\n"; newString += "\nInitialization Rule Applied: \n"; newString += assertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } /** * <p>Applies the procedure declaration rule.</p> * * @param opLoc Location of the procedure declaration. * @param name Name of the procedure. * @param requires Requires clause * @param ensures Ensures clause * @param decreasing Decreasing clause (if any) * @param procDur Procedure duration clause (if in performance mode) * @param varFinalDur Local variable finalization duration clause (if in performance mode) * @param typeConstraint Facility type constraints (if any) * @param variableList List of all variables for this procedure * @param statementList List of statements for this procedure * @param isLocal True if the it is a local operation. False otherwise. */ private void applyProcedureDeclRule(Location opLoc, String name, Exp requires, Exp ensures, Exp decreasing, Exp procDur, Exp varFinalDur, Exp typeConstraint, List<VarDec> variableList, List<Statement> statementList, boolean isLocal) { // Add the global requires clause if (myGlobalRequiresExp != null) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), myGlobalRequiresExp, false); } // Add the global constraints if (myGlobalConstraintExp != null) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), myGlobalConstraintExp, false); } // Add the convention as something we need to ensure if (myConventionExp != null && !isLocal) { Exp convention = Exp.copy(myConventionExp); myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), convention, false); } // Add the correspondence as a given if (myCorrespondenceExp != null && !isLocal) { Exp correspondence = Exp.copy(myCorrespondenceExp); myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), correspondence, false); } // Add the requires clause if (requires != null) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), requires, false); } // Add the facility formal to actuals Exp formalActualExp = myTypeGraph.getTrueVarExp(); for (FacilityDec fDec : myFacilityFormalActualMap.keySet()) { List<EqualsExp> eList = myFacilityFormalActualMap.get(fDec); for (EqualsExp e : eList) { EqualsExp newEquals = (EqualsExp) Exp.copy(e); VarExp oldLeft = (VarExp) Exp.copy(newEquals.getLeft()); VarExp newLeft; if (formalActualExp.containsVar(oldLeft.getName().getName(), false)) { newLeft = Utilities.createQuestionMarkVariable( formalActualExp, oldLeft); } else { newLeft = oldLeft; } newEquals.setLeft(newLeft); // Get rid of true if (formalActualExp.isLiteralTrue()) { formalActualExp = newEquals; } else { formalActualExp = myTypeGraph .formConjunct(formalActualExp, newEquals); } } } if (!formalActualExp.isLiteralTrue()) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), formalActualExp, false); } // NY - Add any procedure duration clauses if (procDur != null) { // Add Cum_Dur as a free variable VarExp cumDur = Utilities.createVarExp((Location) opLoc.clone(), null, Utilities.createPosSymbol("Cum_Dur"), myTypeGraph.R, null); myCurrentAssertiveCode.addFreeVar(cumDur); // Create 0.0 VarExp zeroPtZero = Utilities.createVarExp(opLoc, null, Utilities .createPosSymbol("0.0"), myTypeGraph.R, null); // Create an equals expression (Cum_Dur = 0.0) EqualsExp equalsExp = new EqualsExp(null, Exp.copy(cumDur), EqualsExp.EQUAL, zeroPtZero); equalsExp.setMathType(BOOLEAN); Location eqLoc = (Location) opLoc.clone(); eqLoc.setDetails("Initialization of Cum_Dur for Procedure " + name); Utilities.setLocation(equalsExp, eqLoc); // Add it to our things to assume myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), equalsExp, false); // Create the duration expression Exp durationExp; if (varFinalDur != null) { durationExp = new InfixExp(null, Exp.copy(cumDur), Utilities .createPosSymbol("+"), varFinalDur); } else { durationExp = Exp.copy(cumDur); } durationExp.setMathType(myTypeGraph.R); Location sumLoc = (Location) opLoc.clone(); sumLoc .setDetails("Summation of Finalization Duration for Procedure " + name); Utilities.setLocation(durationExp, sumLoc); InfixExp greaterEqExp = new InfixExp(null, durationExp, Utilities .createPosSymbol("<="), procDur); greaterEqExp.setMathType(BOOLEAN); Location andLoc = (Location) opLoc.clone(); andLoc.setDetails("Duration Clause of " + name); Utilities.setLocation(greaterEqExp, andLoc); // Append the duration to the ensures clause ensures = myTypeGraph.formConjunct(ensures, greaterEqExp); } // Add the facility type constraints if (typeConstraint != null) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), typeConstraint, false); } // Add the remember rule myCurrentAssertiveCode.addCode(new MemoryStmt((Location) opLoc.clone(), true)); // Add declared variables into the assertion. Also add // them to the list of free variables. myCurrentAssertiveCode.addVariableDecs(variableList); addVarDecsAsFreeVars(variableList); // Check to see if we have a recursive procedure. // If yes, we will need to create an additional assume clause // (P_val = (decreasing clause)) in our list of assertions. if (decreasing != null) { // Store for future use myOperationDecreasingExp = decreasing; // Add P_val as a free variable VarExp pVal = Utilities.createPValExp(decreasing.getLocation(), myCurrentModuleScope); myCurrentAssertiveCode.addFreeVar(pVal); // Create an equals expression EqualsExp equalsExp = new EqualsExp(null, pVal, EqualsExp.EQUAL, Exp .copy(decreasing)); equalsExp.setMathType(BOOLEAN); Location eqLoc = (Location) decreasing.getLocation().clone(); eqLoc.setDetails("Progress Metric for Recursive Procedure"); Utilities.setLocation(equalsExp, eqLoc); // Add it to our things to assume myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), equalsExp, false); } // Add the list of statements myCurrentAssertiveCode.addStatements(statementList); // Add the correspondence as a given again if (myCorrespondenceExp != null && !isLocal) { Exp correspondence = Exp.copy(myCorrespondenceExp); myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), correspondence, false); } // Add the convention as something we need to ensure if (myConventionExp != null && !isLocal) { Exp convention = Exp.copy(myConventionExp); Location conventionLoc = (Location) opLoc.clone(); conventionLoc.setDetails(convention.getLocation().getDetails() + " generated by " + name); Utilities.setLocation(convention, conventionLoc); // Simplify if we just have true boolean simplify = false; if (myConventionExp.isLiteralTrue()) { simplify = true; } myCurrentAssertiveCode.addConfirm(conventionLoc, convention, simplify); } // Simplify if we just have true boolean simplify = false; if (ensures.isLiteralTrue()) { simplify = true; } // Add the final confirms clause myCurrentAssertiveCode.setFinalConfirm(ensures, simplify); // Verbose Mode Debug Messages myVCBuffer.append("\nProcedure Declaration Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the remember rule.</p> */ private void applyRememberRule() { // Obtain the final confirm and apply the remember method for Exp ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp conf = confirmStmt.getAssertion(); conf = conf.remember(); myCurrentAssertiveCode.setFinalConfirm(conf, confirmStmt.getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nRemember Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies each of the proof rules. This <code>AssertiveCode</code> will be * stored for later use and therefore should be considered immutable after * a call to this method.</p> */ private void applyRules() { // Apply a proof rule to each of the assertions while (myCurrentAssertiveCode.hasAnotherAssertion()) { // Work our way from the last assertion VerificationStatement curAssertion = myCurrentAssertiveCode.getLastAssertion(); switch (curAssertion.getType()) { // Change Assertion case VerificationStatement.CHANGE: applyChangeRule(curAssertion); break; // Code case VerificationStatement.CODE: applyCodeRules((Statement) curAssertion.getAssertion()); break; // Variable Declaration Assertion case VerificationStatement.VARIABLE: applyVarDeclRule(curAssertion); break; } } } /** * <p>Applies the swap statement rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>SwapStmt</code>. */ private void applySwapStmtRule(SwapStmt stmt) { // Obtain the current final confirm clause ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp conf = confirmStmt.getAssertion(); // Create a copy of the left and right hand side VariableExp stmtLeft = (VariableExp) Exp.copy(stmt.getLeft()); VariableExp stmtRight = (VariableExp) Exp.copy(stmt.getRight()); // New left and right Exp newLeft = Utilities.convertExp(stmtLeft); Exp newRight = Utilities.convertExp(stmtRight); // Use our final confirm to obtain the math types List lst = conf.getSubExpressions(); for (int i = 0; i < lst.size(); i++) { if (lst.get(i) instanceof VarExp) { VarExp thisExp = (VarExp) lst.get(i); if (newRight instanceof VarExp) { if (thisExp.getName().equals( ((VarExp) newRight).getName().getName())) { newRight.setMathType(thisExp.getMathType()); newRight.setMathTypeValue(thisExp.getMathTypeValue()); } } if (newLeft instanceof VarExp) { if (thisExp.getName().equals( ((VarExp) newLeft).getName().getName())) { newLeft.setMathType(thisExp.getMathType()); newLeft.setMathTypeValue(thisExp.getMathTypeValue()); } } } } // Temp variable VarExp tmp = new VarExp(); tmp.setName(Utilities.createPosSymbol("_" + Utilities.getVarName(stmtLeft).getName())); tmp.setMathType(stmtLeft.getMathType()); tmp.setMathTypeValue(stmtLeft.getMathTypeValue()); // Replace according to the swap rule conf = Utilities.replace(conf, newRight, tmp); conf = Utilities.replace(conf, newLeft, newRight); conf = Utilities.replace(conf, tmp, newLeft); // NY YS // Duration for swap statements if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = stmt.getLocation(); VarExp cumDur = Utilities .createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(conf)), myTypeGraph.R, null); Exp swapDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol("Dur_Swap"), myTypeGraph.R, null); InfixExp sumSwapDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), swapDur); sumSwapDur.setMathType(myTypeGraph.R); conf = Utilities.replace(conf, cumDur, sumSwapDur); } // Set this new expression as the new final confirm myCurrentAssertiveCode.setFinalConfirm(conf, confirmStmt.getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nSwap Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the variable declaration rule.</p> * * @param var A declared variable stored as a * <code>VerificationStatement</code> */ private void applyVarDeclRule(VerificationStatement var) { // Obtain the variable from the verification statement VarDec varDec = (VarDec) var.getAssertion(); ProgramTypeEntry typeEntry; // Ty is NameTy if (varDec.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) varDec.getTy(); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy .getQualifier(), pNameTy.getName(), myCurrentModuleScope); if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry(pNameTy.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the declared variable VarExp varDecExp = Utilities.createVarExp(varDec.getLocation(), null, varDec.getName(), typeEntry.getModelType(), null); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type .getExemplar(), typeEntry.getModelType(), null); // Deep copy the original initialization ensures Exp init = Exp.copy(type.getInitialization().getEnsures()); init = Utilities.replace(init, exemplar, varDecExp); // Set the location for the initialization ensures Location loc; if (init.getLocation() != null) { loc = (Location) init.getLocation().clone(); } else { loc = (Location) type.getLocation().clone(); } loc.setDetails("Initialization ensures on " + varDec.getName().getName()); Utilities.setLocation(init, loc); // Final confirm clause Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm().getAssertion(); // Obtain the string form of the variable String varName = varDec.getName().getName(); // Check to see if we have a variable dot expression. // If we do, we will need to extract the name. int dotIndex = varName.indexOf("."); if (dotIndex > 0) { varName = varName.substring(0, dotIndex); } // Check to see if this variable was declared inside a record ResolveConceptualElement element = myCurrentAssertiveCode.getInstantiatingElement(); if (element instanceof RepresentationDec) { RepresentationDec dec = (RepresentationDec) element; if (dec.getRepresentation() instanceof RecordTy) { SymbolTableEntry repSte = Utilities.searchProgramType(dec.getLocation(), null, dec.getName(), myCurrentModuleScope); ProgramTypeDefinitionEntry representationTypeEntry = repSte.toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); // Create a variable expression from the type exemplar VarExp representationExemplar = Utilities .createVarExp( varDec.getLocation(), null, Utilities .createPosSymbol(representationTypeEntry .getExemplar() .getName()), representationTypeEntry .getModelType(), null); // Create a dotted expression edu.clemson.cs.r2jt.collections.List<Exp> expList = new edu.clemson.cs.r2jt.collections.List<Exp>(); expList.add(representationExemplar); expList.add(varDecExp); DotExp dotExp = Utilities.createDotExp(loc, expList, varDecExp .getMathType()); // Replace the initialization clauses appropriately init = Utilities.replace(init, varDecExp, dotExp); } } // Check if our confirm clause uses this variable if (finalConfirm.containsVar(varName, false)) { // Add the new assume clause to our assertive code. myCurrentAssertiveCode.addAssume((Location) loc.clone(), init, false); } } // Since the type is generic, we can only use the is_initial predicate // to ensure that the value is initial value. else { // Obtain the original dec from the AST Location varLoc = varDec.getLocation(); // Create an is_initial dot expression DotExp isInitialExp = Utilities.createInitExp(varDec, MTYPE, BOOLEAN); if (varLoc != null) { Location loc = (Location) varLoc.clone(); loc.setDetails("Initial Value for " + varDec.getName().getName()); Utilities.setLocation(isInitialExp, loc); } // Add to our assertive code as an assume myCurrentAssertiveCode.addAssume(varLoc, isInitialExp, false); } // NY YS // Initialization duration for this variable if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { ConfirmStmt finalConfirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp finalConfirm = finalConfirmStmt.getAssertion(); Location loc = ((NameTy) varDec.getTy()).getName().getLocation(); VarExp cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(finalConfirm)), myTypeGraph.R, null); Exp initDur = Utilities.createInitAnyDur(varDec, myTypeGraph.R); InfixExp sumInitDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), initDur); sumInitDur.setMathType(myTypeGraph.R); finalConfirm = Utilities.replace(finalConfirm, cumDur, sumInitDur); myCurrentAssertiveCode.setFinalConfirm(finalConfirm, finalConfirmStmt.getSimplify()); } // Verbose Mode Debug Messages myVCBuffer.append("\nVariable Declaration Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Ty not handled. Utilities.tyNotHandled(varDec.getTy(), varDec.getLocation()); } } /** * <p>Applies the while statement rule.</p> * * @param stmt Our current <code>WhileStmt</code>. */ private void applyWhileStmtRule(WhileStmt stmt) { // Obtain the loop invariant Exp invariant; boolean simplifyInvariant = false; if (stmt.getMaintaining() != null) { invariant = Exp.copy(stmt.getMaintaining()); invariant.setMathType(stmt.getMaintaining().getMathType()); // Simplify if we just have true if (invariant.isLiteralTrue()) { simplifyInvariant = true; } } else { invariant = myTypeGraph.getTrueVarExp(); simplifyInvariant = true; } // NY YS // Obtain the elapsed time duration of loop Exp elapsedTimeDur = null; if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { if (stmt.getElapsed_Time() != null) { elapsedTimeDur = Exp.copy(stmt.getElapsed_Time()); elapsedTimeDur.setMathType(myTypeGraph.R); } } // Confirm the base case of invariant Exp baseCase = Exp.copy(invariant); Location baseLoc; if (invariant.getLocation() != null) { baseLoc = (Location) invariant.getLocation().clone(); } else { baseLoc = (Location) stmt.getLocation().clone(); } baseLoc.setDetails("Base Case of the Invariant of While Statement"); Utilities.setLocation(baseCase, baseLoc); // NY YS // Confirm that elapsed time is 0.0 if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC) && elapsedTimeDur != null) { Exp initElapseDurExp = Exp.copy(elapsedTimeDur); Location initElapseLoc; if (elapsedTimeDur != null && elapsedTimeDur.getLocation() != null) { initElapseLoc = (Location) elapsedTimeDur.getLocation().clone(); } else { initElapseLoc = (Location) elapsedTimeDur.getLocation().clone(); } initElapseLoc .setDetails("Base Case of Elapsed Time Duration of While Statement"); Utilities.setLocation(initElapseDurExp, initElapseLoc); Exp zeroEqualExp = new EqualsExp((Location) initElapseLoc.clone(), initElapseDurExp, 1, Utilities.createVarExp( (Location) initElapseLoc.clone(), null, Utilities.createPosSymbol("0.0"), myTypeGraph.R, null)); zeroEqualExp.setMathType(BOOLEAN); baseCase = myTypeGraph.formConjunct(baseCase, zeroEqualExp); } myCurrentAssertiveCode.addConfirm((Location) baseLoc.clone(), baseCase, simplifyInvariant); // Add the change rule if (stmt.getChanging() != null) { myCurrentAssertiveCode.addChange(stmt.getChanging()); } // Assume the invariant and NQV(RP, P_Val) = P_Exp Location whileLoc = stmt.getLocation(); Exp assume; Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm().getAssertion(); boolean simplifyFinalConfirm = myCurrentAssertiveCode.getFinalConfirm().getSimplify(); Exp decreasingExp = stmt.getDecreasing(); Exp nqv; if (decreasingExp != null) { VarExp pval = Utilities.createPValExp((Location) whileLoc.clone(), myCurrentModuleScope); nqv = Utilities.createQuestionMarkVariable(finalConfirm, pval); nqv.setMathType(pval.getMathType()); Exp equalPExp = new EqualsExp((Location) whileLoc.clone(), Exp.copy(nqv), 1, Exp.copy(decreasingExp)); equalPExp.setMathType(BOOLEAN); assume = myTypeGraph.formConjunct(Exp.copy(invariant), equalPExp); } else { decreasingExp = myTypeGraph.getTrueVarExp(); nqv = myTypeGraph.getTrueVarExp(); assume = Exp.copy(invariant); } // NY YS // Also assume NQV(RP, Cum_Dur) = El_Dur_Exp Exp nqv2 = null; if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC) & elapsedTimeDur != null) { VarExp cumDurExp = Utilities.createVarExp((Location) whileLoc.clone(), null, Utilities.createPosSymbol("Cum_Dur"), myTypeGraph.R, null); nqv2 = Utilities.createQuestionMarkVariable(finalConfirm, cumDurExp); nqv2.setMathType(cumDurExp.getMathType()); Exp equalPExp = new EqualsExp((Location) whileLoc.clone(), Exp.copy(nqv2), 1, Exp.copy(elapsedTimeDur)); equalPExp.setMathType(BOOLEAN); assume = myTypeGraph.formConjunct(assume, equalPExp); } myCurrentAssertiveCode.addAssume((Location) whileLoc.clone(), assume, false); // if statement body (need to deep copy!) edu.clemson.cs.r2jt.collections.List<Statement> ifStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); edu.clemson.cs.r2jt.collections.List<Statement> whileStmtList = stmt.getStatements(); for (Statement s : whileStmtList) { ifStmtList.add((Statement) s.clone()); } // Confirm the inductive case of invariant Exp inductiveCase = Exp.copy(invariant); Location inductiveLoc; if (invariant.getLocation() != null) { inductiveLoc = (Location) invariant.getLocation().clone(); } else { inductiveLoc = (Location) stmt.getLocation().clone(); } inductiveLoc .setDetails("Inductive Case of Invariant of While Statement"); Utilities.setLocation(inductiveCase, inductiveLoc); ifStmtList.add(new ConfirmStmt(inductiveLoc, inductiveCase, simplifyInvariant)); // Confirm the termination of the loop. if (decreasingExp != null) { Location decreasingLoc = (Location) decreasingExp.getLocation().clone(); if (decreasingLoc != null) { decreasingLoc.setDetails("Termination of While Statement"); } // Create a new infix expression IntegerExp oneExp = new IntegerExp(); oneExp.setValue(1); oneExp.setMathType(decreasingExp.getMathType()); InfixExp leftExp = new InfixExp(stmt.getLocation(), oneExp, Utilities .createPosSymbol("+"), Exp.copy(decreasingExp)); leftExp.setMathType(decreasingExp.getMathType()); Exp infixExp = Utilities.createLessThanEqExp(decreasingLoc, leftExp, Exp .copy(nqv), BOOLEAN); // Confirm NQV(RP, Cum_Dur) <= El_Dur_Exp if (nqv2 != null) { Location elapsedTimeLoc = (Location) elapsedTimeDur.getLocation().clone(); if (elapsedTimeLoc != null) { elapsedTimeLoc.setDetails("Termination of While Statement"); } Exp infixExp2 = Utilities.createLessThanEqExp(elapsedTimeLoc, Exp .copy(nqv2), Exp.copy(elapsedTimeDur), BOOLEAN); infixExp = myTypeGraph.formConjunct(infixExp, infixExp2); infixExp.setLocation(decreasingLoc); } ifStmtList.add(new ConfirmStmt(decreasingLoc, infixExp, false)); } else { throw new RuntimeException("No decreasing clause!"); } // empty elseif pair edu.clemson.cs.r2jt.collections.List<ConditionItem> elseIfPairList = new edu.clemson.cs.r2jt.collections.List<ConditionItem>(); // else body Location elseConfirmLoc; if (finalConfirm.getLocation() != null) { elseConfirmLoc = (Location) finalConfirm.getLocation().clone(); } else { elseConfirmLoc = (Location) whileLoc.clone(); } edu.clemson.cs.r2jt.collections.List<Statement> elseStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); // NY YS // Form the confirm clause for the else Exp elseConfirm = Exp.copy(finalConfirm); if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC) & elapsedTimeDur != null) { Location loc = stmt.getLocation(); VarExp cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(elseConfirm)), myTypeGraph.R, null); InfixExp sumWhileDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), Exp .copy(elapsedTimeDur)); sumWhileDur.setMathType(myTypeGraph.R); elseConfirm = Utilities.replace(elseConfirm, cumDur, sumWhileDur); } elseStmtList.add(new ConfirmStmt(elseConfirmLoc, elseConfirm, simplifyFinalConfirm)); // condition ProgramExp condition = (ProgramExp) Exp.copy(stmt.getTest()); if (condition.getLocation() != null) { Location condLoc = (Location) condition.getLocation().clone(); condLoc.setDetails("While Loop Condition"); Utilities.setLocation(condition, condLoc); } // add it back to your assertive code IfStmt newIfStmt = new IfStmt(condition, ifStmtList, elseIfPairList, elseStmtList); myCurrentAssertiveCode.addCode(newIfStmt); // Change our final confirm to "True" Exp trueVarExp = myTypeGraph.getTrueVarExp(); trueVarExp.setLocation((Location) whileLoc.clone()); myCurrentAssertiveCode.setFinalConfirm(trueVarExp, true); // Verbose Mode Debug Messages myVCBuffer.append("\nWhile Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } }
Removed redundant code
src/main/java/edu/clemson/cs/r2jt/vcgeneration/VCGenerator.java
Removed redundant code
<ide><path>rc/main/java/edu/clemson/cs/r2jt/vcgeneration/VCGenerator.java <ide> currentFinalConfirm = <ide> myTypeGraph.formImplies(stmt.getAssertion(), <ide> currentFinalConfirm); <del> simplify = false; <ide> } <ide> <ide> // Set this as our new final confirm
Java
apache-2.0
7315c9fa3bfbd1d27060908c4fd2cf12d59dd382
0
Syquel/BushyTail
/* * Copyright 2016, Frederik Boster * * 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. */ package de.syquel.bushytail.serializer; import de.syquel.bushytail.serializer.exception.OlingoSerializerException; import org.apache.commons.beanutils.PropertyUtils; import org.apache.olingo.commons.api.data.Entity; import org.apache.olingo.commons.api.data.Property; import org.apache.olingo.commons.api.data.ValueType; import org.apache.olingo.commons.api.edm.EdmEntityType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; /** * Converts Java objects to Olingo entities. * * @author Clemens Bartz * @author Frederik Boster * @since 1.0 */ public final class OlingoSerializer { /** The logger. */ private static final Logger logger = LoggerFactory.getLogger(OlingoSerializer.class); /** * Hidden constructor. */ private OlingoSerializer() { } /** * Convert an {@link T object} to an {@link Entity Olingo entity}. * @param entityType the type of the entity * @param entityObject the object to convert * @param <T> the type of the entity * @return an Olingo entity * @throws OlingoSerializerException if the method cannot access a property */ public static <T> Entity serialize(EdmEntityType entityType, T entityObject) throws OlingoSerializerException { final Entity olingoEntity = new Entity(); olingoEntity.setType(entityType.getFullQualifiedName().getFullQualifiedNameAsString()); for (String propertyName : entityType.getPropertyNames()) { try { final Method propertyAccessor = PropertyUtils.getPropertyDescriptor(entityObject, propertyName).getReadMethod(); final Object value = propertyAccessor.invoke(entityObject); olingoEntity.addProperty(new Property(null, propertyName, ValueType.PRIMITIVE, value)); } catch (Exception e) { logger.error("Cannot access property '" + propertyName + "' of class '" + entityObject.getClass() + "'", e); throw new OlingoSerializerException("Cannot access property '" + propertyName + "' of class '" + entityObject.getClass() + "'", e); } } return olingoEntity; } }
src/main/java/de/syquel/bushytail/serializer/OlingoSerializer.java
/* * Copyright 2016, Frederik Boster * * 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. */ package de.syquel.bushytail.serializer; import de.syquel.bushytail.serializer.exception.OlingoSerializerException; import org.apache.commons.beanutils.PropertyUtils; import org.apache.olingo.commons.api.data.Entity; import org.apache.olingo.commons.api.data.Property; import org.apache.olingo.commons.api.data.ValueType; import org.apache.olingo.commons.api.edm.EdmEntityType; import java.lang.reflect.Method; /** * Converts Java objects to Olingo entities. * * @author Clemens Bartz * @author Frederik Boster * @since 1.0 */ public class OlingoSerializer { public static <T> Entity serialize(EdmEntityType entityType, T entityObject) throws OlingoSerializerException { Entity olingoEntity = new Entity(); olingoEntity.setType(entityType.getFullQualifiedName().getFullQualifiedNameAsString()); for (String propertyName : entityType.getPropertyNames()) { try { Method propertyAccessor = PropertyUtils.getPropertyDescriptor(entityObject, propertyName).getReadMethod(); Object value = propertyAccessor.invoke(entityObject); olingoEntity.addProperty(new Property(null, propertyName, ValueType.PRIMITIVE, value)); } catch (Exception e) { throw new OlingoSerializerException("Cannot access property '" + propertyName + "' of class '" + entityObject.getClass() + "'", e); } } return olingoEntity; } }
Document seralizer.
src/main/java/de/syquel/bushytail/serializer/OlingoSerializer.java
Document seralizer.
<ide><path>rc/main/java/de/syquel/bushytail/serializer/OlingoSerializer.java <ide> import org.apache.olingo.commons.api.data.Property; <ide> import org.apache.olingo.commons.api.data.ValueType; <ide> import org.apache.olingo.commons.api.edm.EdmEntityType; <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <ide> <ide> import java.lang.reflect.Method; <ide> <ide> * @author Frederik Boster <ide> * @since 1.0 <ide> */ <del>public class OlingoSerializer { <add>public final class OlingoSerializer { <ide> <add> /** The logger. */ <add> private static final Logger logger = LoggerFactory.getLogger(OlingoSerializer.class); <add> <add> /** <add> * Hidden constructor. <add> */ <add> private OlingoSerializer() { <add> <add> } <add> <add> /** <add> * Convert an {@link T object} to an {@link Entity Olingo entity}. <add> * @param entityType the type of the entity <add> * @param entityObject the object to convert <add> * @param <T> the type of the entity <add> * @return an Olingo entity <add> * @throws OlingoSerializerException if the method cannot access a property <add> */ <ide> public static <T> Entity serialize(EdmEntityType entityType, T entityObject) throws OlingoSerializerException { <del> Entity olingoEntity = new Entity(); <add> final Entity olingoEntity = new Entity(); <ide> olingoEntity.setType(entityType.getFullQualifiedName().getFullQualifiedNameAsString()); <ide> <ide> for (String propertyName : entityType.getPropertyNames()) { <ide> try { <del> Method propertyAccessor = PropertyUtils.getPropertyDescriptor(entityObject, propertyName).getReadMethod(); <del> Object value = propertyAccessor.invoke(entityObject); <add> final Method propertyAccessor = PropertyUtils.getPropertyDescriptor(entityObject, propertyName).getReadMethod(); <add> final Object value = propertyAccessor.invoke(entityObject); <ide> <ide> olingoEntity.addProperty(new Property(null, propertyName, ValueType.PRIMITIVE, value)); <ide> } catch (Exception e) { <add> logger.error("Cannot access property '" + propertyName + "' of class '" + entityObject.getClass() + "'", e); <ide> throw new OlingoSerializerException("Cannot access property '" + propertyName + "' of class '" + entityObject.getClass() + "'", e); <ide> } <ide> }
Java
mit
58f9b1e7d184bfe60f496a619d28e24ace651eea
0
rememberber/WePush,rememberber/WePush
package com.fangxuele.tool.wechat.push.util; import com.fangxuele.tool.wechat.push.ui.Init; import com.fangxuele.tool.wechat.push.ui.MainWindow; import com.xiaoleilu.hutool.log.Log; import com.xiaoleilu.hutool.log.LogFactory; import org.apache.commons.lang3.StringUtils; import javax.swing.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * MySQL数据库工具,单例,持久连接 * * @author rememberber(https : / / github.com / rememberber) */ public class DbUtilMySQL { private Connection connection = null; private Statement statement = null; private ResultSet resultSet = null; private static String DBClassName = null; private static String DBUrl = null; private static String DBName = null; private static String DBUser = null; private static String DBPassword = null; private static DbUtilMySQL instance = null; private static final Log logger = LogFactory.get(); /** * 私有的构造 */ private DbUtilMySQL() { loadConfig(); } /** * 获取实例,线程安全 * * @return */ public static synchronized DbUtilMySQL getInstance() { if (instance == null) { instance = new DbUtilMySQL(); } return instance; } /** * 从配置文件加载设置数据库信息 */ private void loadConfig() { try { DBClassName = "com.mysql.cj.jdbc.Driver"; DBUrl = Init.configer.getMysqlUrl(); DBName = Init.configer.getMysqlDatabase(); DBUser = Init.configer.getMysqlUser(); DBPassword = Init.configer.getMysqlPassword(); if (StringUtils.isEmpty(DBUrl) || StringUtils.isEmpty(DBName) || StringUtils.isEmpty(DBUser) || StringUtils.isEmpty(DBPassword)) { JOptionPane.showMessageDialog(MainWindow.mainWindow.getSettingPanel(), "请先在设置中填写并保存MySQL数据库相关配置!", "提示", JOptionPane.INFORMATION_MESSAGE); return; } Class.forName(DBClassName); } catch (Exception e) { logger.error(e.toString()); e.printStackTrace(); } } /** * 获取连接,线程安全 * * @return * @throws SQLException */ public synchronized Connection getConnection() throws SQLException { String user = Init.configer.getMysqlUser(); String password = Init.configer.getMysqlPassword(); // 当DB配置变更时重新获取 if (!Init.configer.getMysqlUrl().equals(DBUrl) || !Init.configer.getMysqlDatabase().equals(DBName) || !Init.configer.getMysqlUser().equals(DBUser) || !Init.configer.getMysqlPassword().equals(DBPassword)) { loadConfig(); // "jdbc:mysql://localhost/pxp2p_branch" connection = DriverManager.getConnection( "jdbc:mysql://" + DBUrl + "/" + DBName + "?useUnicode=true&characterEncoding=utf8", user, password); // 把事务提交方式改为手工提交 connection.setAutoCommit(false); } // 当connection失效时重新获取 if (connection == null || connection.isValid(10) == false) { // "jdbc:mysql://localhost/pxp2p_branch" connection = DriverManager.getConnection( "jdbc:mysql://" + DBUrl + "/" + DBName + "?useUnicode=true&characterEncoding=utf8", user, password); // 把事务提交方式改为手工提交 connection.setAutoCommit(false); } if (connection == null) { logger.error("Can not load MySQL jdbc and get connection."); } return connection; } /** * 测试连接,线程安全 参数从配置文件获取 * * @return * @throws SQLException */ public synchronized Connection testConnection() throws SQLException { loadConfig(); String user = Init.configer.getMysqlUser(); String password = Init.configer.getMysqlPassword(); connection = DriverManager.getConnection("jdbc:mysql://" + DBUrl + "/" + DBName, user, password); // 把事务提交方式改为手工提交 connection.setAutoCommit(false); if (connection == null) { logger.error("Can not load MySQL jdbc and get connection."); } return connection; } /** * 测试连接,线程安全 参数从入参获取 * * @return * @throws SQLException */ public synchronized Connection testConnection(String DBUrl, String DBName, String DBUser, String DBPassword) throws SQLException { loadConfig(); // "jdbc:mysql://localhost/pxp2p_branch" connection = DriverManager.getConnection("jdbc:mysql://" + DBUrl + "/" + DBName, DBUser, DBPassword); // 把事务提交方式改为手工提交 connection.setAutoCommit(false); if (connection == null) { logger.error("Can not load MySQL jdbc and get connection."); } return connection; } /** * 获取数据库声明,私有,线程安全 * * @throws SQLException */ private synchronized void getStatement() throws SQLException { getConnection(); // 仅当statement失效时才重新创建 if (statement == null || statement.isClosed() == true) { statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); } } /** * 关闭(结果集、声明、连接),线程安全 * * @throws SQLException */ public synchronized void close() throws SQLException { if (resultSet != null) { resultSet.close(); resultSet = null; } if (statement != null) { statement.close(); statement = null; } if (connection != null) { connection.close(); connection = null; } } /** * 执行查询,线程安全 * * @param sql * @return * @throws SQLException */ public synchronized ResultSet executeQuery(String sql) throws SQLException { getStatement(); if (resultSet != null && resultSet.isClosed() == false) { resultSet.close(); } resultSet = null; resultSet = statement.executeQuery(sql); return resultSet; } /** * 执行更新,线程安全 * * @param sql * @return * @throws SQLException */ public synchronized int executeUpdate(String sql) throws SQLException { int result = 0; getStatement(); result = statement.executeUpdate(sql); return result; } }
src/main/java/com/fangxuele/tool/wechat/push/util/DbUtilMySQL.java
package com.fangxuele.tool.wechat.push.util; import com.fangxuele.tool.wechat.push.ui.Init; import com.xiaoleilu.hutool.log.Log; import com.xiaoleilu.hutool.log.LogFactory; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * MySQL数据库工具,单例,持久连接 * * @author rememberber(https://github.com/rememberber) */ public class DbUtilMySQL { private Connection connection = null; private Statement statement = null; private ResultSet resultSet = null; private static String DBClassName = null; private static String DBUrl = null; private static String DBName = null; private static String DBUser = null; private static String DBPassword = null; private static DbUtilMySQL instance = null; private static final Log logger = LogFactory.get(); /** * 私有的构造 */ private DbUtilMySQL() { loadConfig(); } /** * 获取实例,线程安全 * * @return */ public static synchronized DbUtilMySQL getInstance() { if (instance == null) { instance = new DbUtilMySQL(); } return instance; } /** * 从配置文件加载设置数据库信息 */ private void loadConfig() { try { DBClassName = "com.mysql.cj.jdbc.Driver"; DBUrl = Init.configer.getMysqlUrl(); DBName = Init.configer.getMysqlDatabase(); DBUser = Init.configer.getMysqlUser(); DBPassword = Init.configer.getMysqlPassword(); Class.forName(DBClassName); } catch (Exception e) { logger.error(e.toString()); e.printStackTrace(); } } /** * 获取连接,线程安全 * * @return * @throws SQLException */ public synchronized Connection getConnection() throws SQLException { String user = Init.configer.getMysqlUser(); String password = Init.configer.getMysqlPassword(); // 当DB配置变更时重新获取 if (!Init.configer.getMysqlUrl().equals(DBUrl) || !Init.configer.getMysqlDatabase().equals(DBName) || !Init.configer.getMysqlUser().equals(DBUser) || !Init.configer.getMysqlPassword().equals(DBPassword)) { loadConfig(); // "jdbc:mysql://localhost/pxp2p_branch" connection = DriverManager.getConnection( "jdbc:mysql://" + DBUrl + "/" + DBName + "?useUnicode=true&characterEncoding=utf8", user, password); // 把事务提交方式改为手工提交 connection.setAutoCommit(false); } // 当connection失效时重新获取 if (connection == null || connection.isValid(10) == false) { // "jdbc:mysql://localhost/pxp2p_branch" connection = DriverManager.getConnection( "jdbc:mysql://" + DBUrl + "/" + DBName + "?useUnicode=true&characterEncoding=utf8", user, password); // 把事务提交方式改为手工提交 connection.setAutoCommit(false); } if (connection == null) { logger.error("Can not load MySQL jdbc and get connection."); } return connection; } /** * 测试连接,线程安全 参数从配置文件获取 * * @return * @throws SQLException */ public synchronized Connection testConnection() throws SQLException { loadConfig(); String user = Init.configer.getMysqlUser(); String password = Init.configer.getMysqlPassword(); connection = DriverManager.getConnection("jdbc:mysql://" + DBUrl + "/" + DBName, user, password); // 把事务提交方式改为手工提交 connection.setAutoCommit(false); if (connection == null) { logger.error("Can not load MySQL jdbc and get connection."); } return connection; } /** * 测试连接,线程安全 参数从入参获取 * * @return * @throws SQLException */ public synchronized Connection testConnection(String DBUrl, String DBName, String DBUser, String DBPassword) throws SQLException { loadConfig(); // "jdbc:mysql://localhost/pxp2p_branch" connection = DriverManager.getConnection("jdbc:mysql://" + DBUrl + "/" + DBName, DBUser, DBPassword); // 把事务提交方式改为手工提交 connection.setAutoCommit(false); if (connection == null) { logger.error("Can not load MySQL jdbc and get connection."); } return connection; } /** * 获取数据库声明,私有,线程安全 * * @throws SQLException */ private synchronized void getStatement() throws SQLException { getConnection(); // 仅当statement失效时才重新创建 if (statement == null || statement.isClosed() == true) { statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); } } /** * 关闭(结果集、声明、连接),线程安全 * * @throws SQLException */ public synchronized void close() throws SQLException { if (resultSet != null) { resultSet.close(); resultSet = null; } if (statement != null) { statement.close(); statement = null; } if (connection != null) { connection.close(); connection = null; } } /** * 执行查询,线程安全 * * @param sql * @return * @throws SQLException */ public synchronized ResultSet executeQuery(String sql) throws SQLException { getStatement(); if (resultSet != null && resultSet.isClosed() == false) { resultSet.close(); } resultSet = null; resultSet = statement.executeQuery(sql); return resultSet; } /** * 执行更新,线程安全 * * @param sql * @return * @throws SQLException */ public synchronized int executeUpdate(String sql) throws SQLException { int result = 0; getStatement(); result = statement.executeUpdate(sql); return result; } }
优化:未在设置中配置数据库信息时,执行导入操作的报错
src/main/java/com/fangxuele/tool/wechat/push/util/DbUtilMySQL.java
优化:未在设置中配置数据库信息时,执行导入操作的报错
<ide><path>rc/main/java/com/fangxuele/tool/wechat/push/util/DbUtilMySQL.java <ide> package com.fangxuele.tool.wechat.push.util; <ide> <ide> import com.fangxuele.tool.wechat.push.ui.Init; <add>import com.fangxuele.tool.wechat.push.ui.MainWindow; <ide> import com.xiaoleilu.hutool.log.Log; <ide> import com.xiaoleilu.hutool.log.LogFactory; <del> <add>import org.apache.commons.lang3.StringUtils; <add> <add>import javax.swing.*; <ide> import java.sql.Connection; <ide> import java.sql.DriverManager; <ide> import java.sql.ResultSet; <ide> /** <ide> * MySQL数据库工具,单例,持久连接 <ide> * <del> * @author rememberber(https://github.com/rememberber) <add> * @author rememberber(https : / / github.com / rememberber) <ide> */ <ide> public class DbUtilMySQL { <ide> private Connection connection = null; <ide> DBName = Init.configer.getMysqlDatabase(); <ide> DBUser = Init.configer.getMysqlUser(); <ide> DBPassword = Init.configer.getMysqlPassword(); <add> <add> if (StringUtils.isEmpty(DBUrl) || StringUtils.isEmpty(DBName) <add> || StringUtils.isEmpty(DBUser) || StringUtils.isEmpty(DBPassword)) { <add> JOptionPane.showMessageDialog(MainWindow.mainWindow.getSettingPanel(), <add> "请先在设置中填写并保存MySQL数据库相关配置!", "提示", <add> JOptionPane.INFORMATION_MESSAGE); <add> return; <add> } <ide> <ide> Class.forName(DBClassName); <ide> } catch (Exception e) {
JavaScript
mit
14ad15d6c296d52f6851659ddba3001bf400dea8
0
FaridSafi/react-native-gifted-messenger,atFriendly/react-native-friendly-chat,slavik0329/react-native-gifted-messenger,FaridSafi/react-native-gifted-chat,gnl/react-native-gifted-messenger,pluralcom/react-native-gifted-chat,pluralcom/react-native-gifted-chat,atFriendly/react-native-friendly-chat,gnl/react-native-gifted-messenger,slavik0329/react-native-gifted-messenger,atFriendly/react-native-friendly-chat,Chatnbook/react-native-gifted-chat,swapkats/react-native-gifted-messenger,Karkin/react-native-gifted-chat,pluralcom/react-native-gifted-chat,swapkats/react-native-gifted-messenger,Karkin/react-native-gifted-chat,FaridSafi/react-native-gifted-chat,ianlin/react-native-gifted-messenger,ianlin/react-native-gifted-messenger,FaridSafi/react-native-gifted-messenger,atFriendly/react-native-friendly-chat,Chatnbook/react-native-gifted-chat,Chatnbook/react-native-gifted-chat
'use strict'; var React = require('react-native'); var { Text, View, ListView, TextInput, Dimensions, Animated, Image, TouchableHighlight, Platform, PixelRatio } = React; var moment = require('moment'); var extend = require('extend'); import InvertibleScrollView from 'react-native-invertible-scroll-view'; var GiftedSpinner = require('react-native-gifted-spinner'); var Button = require('react-native-button'); var GiftedMessenger = React.createClass({ getDefaultProps() { return { displayNames: true, placeholder: 'Type a message...', styles: {}, autoFocus: true, onErrorButtonPress: (message, rowID) => {}, loadEarlierMessagesButton: false, loadEarlierMessagesButtonText: 'Load earlier messages', onLoadEarlierMessages: (oldestMessage, callback) => {}, parseText: false, handleUrlPress: (url) => {}, handlePhonePress: (phone) => {}, handleEmailPress: (email) => {}, initialMessages: [], messages: [], handleSend: (message, rowID) => {}, maxHeight: Dimensions.get('window').height, senderName: 'Sender', senderImage: null, sendButtonText: 'Send', onImagePress: null, inverted: true, hideTextInput: false, submitOnReturn: false, }; }, propTypes: { displayNames: React.PropTypes.bool, placeholder: React.PropTypes.string, styles: React.PropTypes.object, autoFocus: React.PropTypes.bool, onErrorButtonPress: React.PropTypes.func, loadEarlierMessagesButton: React.PropTypes.bool, loadEarlierMessagesButtonText: React.PropTypes.string, onLoadEarlierMessages: React.PropTypes.func, parseText: React.PropTypes.bool, handleUrlPress: React.PropTypes.func, handlePhonePress: React.PropTypes.func, handleEmailPress: React.PropTypes.func, initialMessages: React.PropTypes.array, messages: React.PropTypes.array, handleSend: React.PropTypes.func, onCustomSend: React.PropTypes.func, renderCustomText: React.PropTypes.func, maxHeight: React.PropTypes.number, senderName: React.PropTypes.string, senderImage: React.PropTypes.object, sendButtonText: React.PropTypes.string, onImagePress: React.PropTypes.func, inverted: React.PropTypes.bool, hideTextInput: React.PropTypes.bool, }, getInitialState: function() { this._data = []; this._rowIds = []; var textInputHeight = 0; if (this.props.hideTextInput === false) { textInputHeight = 44; } this.listViewMaxHeight = this.props.maxHeight - textInputHeight; var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => { if (typeof r1.status !== 'undefined') { return true; } return r1 !== r2; }}); return { dataSource: ds.cloneWithRows([]), text: '', disabled: true, height: new Animated.Value(this.listViewMaxHeight), isLoadingEarlierMessages: false, allLoaded: false, }; }, getMessage(rowID) { if (typeof this._rowIds[this._rowIds.indexOf(rowID)] !== 'undefined') { if (typeof this._data[this._rowIds[this._rowIds.indexOf(rowID)]] !== 'undefined') { return this._data[this._rowIds[this._rowIds.indexOf(rowID)]]; } } return null; }, getPreviousMessage(rowID) { if (typeof this._rowIds[this._rowIds.indexOf(rowID - 1)] !== 'undefined') { if (typeof this._data[this._rowIds[this._rowIds.indexOf(rowID - 1)]] !== 'undefined') { return this._data[this._rowIds[this._rowIds.indexOf(rowID - 1)]]; } } return null; }, getNextMessage(rowID) { if (typeof this._rowIds[this._rowIds.indexOf(rowID + 1)] !== 'undefined') { if (typeof this._data[this._rowIds[this._rowIds.indexOf(rowID + 1)]] !== 'undefined') { return this._data[this._rowIds[this._rowIds.indexOf(rowID + 1)]]; } } return null; }, renderName(rowData = {}, rowID = null) { if (this.props.displayNames === true) { var diffMessage = null; if (this.props.inverted === false) { diffMessage = null; // force rendering } else if (rowData.isOld === true) { diffMessage = this.getNextMessage(rowID); } else { diffMessage = this.getPreviousMessage(rowID); } if (diffMessage === null || (this._data[rowID].name !== diffMessage.name || this._data[rowID].id !== diffMessage.id)) { return ( <Text style={[this.styles.name]}> {rowData.name} </Text> ); } } return null; }, renderDate(rowData = {}, rowID = null) { var diffMessage = null; if (this.props.inverted === false) { diffMessage = null; // force rendering } else if (rowData.isOld === true) { diffMessage = this.getNextMessage(rowID); } else { diffMessage = this.getPreviousMessage(rowID); } if (rowData.date instanceof Date) { if (diffMessage === null) { return ( <Text style={[this.styles.date]}> {moment(rowData.date).calendar()} </Text> ); } else if (diffMessage.date instanceof Date) { let diff = moment(rowData.date).diff(moment(diffMessage.date), 'minutes'); if (diff > 5) { return ( <Text style={[this.styles.date]}> {moment(rowData.date).calendar()} </Text> ); } } } return null; }, renderImage(rowData = {}, rowID = null) { if (rowData.image !== null) { var diffMessage = null; if (this.props.inverted === false) { diffMessage = null; // force rendering } else { diffMessage = this.getNextMessage(rowID); } if (diffMessage === null || (this._data[rowID].name !== diffMessage.name || this._data[rowID].id !== diffMessage.id)) { if (typeof this.props.onImagePress === 'function') { return ( <TouchableHighlight underlayColor='transparent' onPress={() => this.props.onImagePress(rowData, rowID)} style={this.styles.imagePosition} > <Image source={rowData.image} style={[this.styles.imagePosition, this.styles.image, (rowData.position === 'left' ? this.styles.imageLeft : this.styles.imageRight)]}/> </TouchableHighlight> ); } else { return ( <Image source={rowData.image} style={[this.styles.imagePosition, this.styles.image, (rowData.position === 'left' ? this.styles.imageLeft : this.styles.imageRight)]}/> ); } } else { return ( <View style={this.styles.imagePosition}/> ); } } return ( <View style={this.styles.spacer}/> ); }, renderErrorButton(rowData = {}, rowID = null) { if (rowData.status === 'ErrorButton') { return ( <ErrorButton onErrorButtonPress={this.props.onErrorButtonPress} rowData={rowData} rowID={rowID} styles={{ errorButtonContainer: this.styles.errorButtonContainer, errorButton: this.styles.errorButton, }} /> ) } return null; }, renderStatus(rowData = {}, rowID = null) { if (rowData.status !== 'ErrorButton' && typeof rowData.status === 'string') { if (rowData.status.length > 0) { return ( <View> <Text style={this.styles.status}>{rowData.status}</Text> </View> ); } } return null; }, renderText(rowData = {}, rowID = null) { /* if (this.props.parseText === true && Platform.OS !== 'android') { let parse = [ {type: 'url', style: [this.styles.link, (rowData.position === 'left' ? this.styles.linkLeft : this.styles.linkRight)], onPress: this.props.handleUrlPress}, {type: 'phone', style: [this.styles.link, (rowData.position === 'left' ? this.styles.linkLeft : this.styles.linkRight)], onPress: this.props.handlePhonePress}, {type: 'email', style: [this.styles.link, (rowData.position === 'left' ? this.styles.linkLeft : this.styles.linkRight)], onPress: this.props.handleEmailPress}, ]; return ( <ParsedText style={[this.styles.text, (rowData.position === 'left' ? this.styles.textLeft : this.styles.textRight)]} parse={parse} > {rowData.text} </ParsedText> ); } */ if (this.props.renderCustomText) { return this.props.renderCustomText(rowData, rowID); } return ( <Text style={[this.styles.text, (rowData.position === 'left' ? this.styles.textLeft : this.styles.textRight)]} > {rowData.text} </Text> ); }, renderRow(rowData = {}, sectionID = null, rowID = null) { return ( <View> {this.renderDate(rowData, rowID)} {rowData.position === 'left' ? this.renderName(rowData, rowID) : null} <View style={this.styles.rowContainer}> {rowData.position === 'left' ? this.renderImage(rowData, rowID) : null} {rowData.position === 'right' ? this.renderErrorButton(rowData, rowID) : null} <View style={[this.styles.bubble, (rowData.position === 'left' ? this.styles.bubbleLeft : this.styles.bubbleRight), (rowData.status === 'ErrorButton' ? this.styles.bubbleError : null)]}> {this.renderText(rowData, rowID)} </View> {rowData.position === 'right' ? this.renderImage(rowData, rowID) : null} </View> {rowData.position === 'right' ? this.renderStatus(rowData, rowID) : null} </View> ); }, onChangeText(text) { this.setState({ text: text }) if (text.trim().length > 0) { this.setState({ disabled: false }) } else { this.setState({ disabled: true }) } }, componentDidMount() { this.scrollResponder = this.refs.listView.getScrollResponder(); if (this.props.messages.length > 0) { this.appendMessages(this.props.messages); } else if (this.props.initialMessages.length > 0) { this.appendMessages(this.props.initialMessages); } else { this.setState({ allLoaded: true }); } }, componentWillReceiveProps(nextProps) { this._data = []; this._rowIds = []; this.appendMessages(nextProps.messages); }, onKeyboardWillHide(e) { Animated.timing(this.state.height, { toValue: this.listViewMaxHeight, duration: 150, }).start(); }, onKeyboardWillShow(e) { Animated.timing(this.state.height, { toValue: this.listViewMaxHeight - (e.endCoordinates ? e.endCoordinates.height : e.end.height), duration: 200, }).start(); }, onSend() { var message = { text: this.state.text.trim(), name: this.props.senderName, image: this.props.senderImage, position: 'right', date: new Date(), }; if (this.props.onCustomSend) { this.props.onCustomSend(message); } else { var rowID = this.appendMessage(message); this.props.handleSend(message, rowID); this.onChangeText(''); this.scrollResponder.scrollTo(0); } }, postLoadEarlierMessages(messages = [], allLoaded = false) { this.prependMessages(messages); this.setState({ isLoadingEarlierMessages: false }); if (allLoaded === true) { this.setState({ allLoaded: true, }); } }, preLoadEarlierMessages() { this.setState({ isLoadingEarlierMessages: true }); this.props.onLoadEarlierMessages(this._data[this._rowIds[this._rowIds.length - 1]], this.postLoadEarlierMessages); }, renderLoadEarlierMessages() { if (this.props.loadEarlierMessagesButton === true) { if (this.state.allLoaded === false) { if (this.state.isLoadingEarlierMessages === true) { return ( <View style={this.styles.loadEarlierMessages}> <GiftedSpinner /> </View> ); } else { return ( <View style={this.styles.loadEarlierMessages}> <Button style={this.styles.loadEarlierMessagesButton} onPress={() => {this.preLoadEarlierMessages()}} > {this.props.loadEarlierMessagesButtonText} </Button> </View> ); } } } return null; }, prependMessages(messages = []) { var rowID = null; for (let i = 0; i < messages.length; i++) { messages[i].isOld = true; this._data.push(messages[i]); this._rowIds.push(this._data.length - 1); rowID = this._data.length - 1; } this.setState({ dataSource: this.state.dataSource.cloneWithRows(this._data, this._rowIds), }); return rowID; }, prependMessage(message = {}) { var rowID = this.prependMessages([message]); return rowID; }, appendMessages(messages = []) { var rowID = null; for (let i = 0; i < messages.length; i++) { this._data.push(messages[i]); this._rowIds.unshift(this._data.length - 1); rowID = this._data.length - 1; } this.setState({ dataSource: this.state.dataSource.cloneWithRows(this._data, this._rowIds), }); return rowID; }, appendMessage(message = {}) { var rowID = this.appendMessages([message]); return rowID; }, refreshRows() { this.setState({ dataSource: this.state.dataSource.cloneWithRows(this._data, this._rowIds), }); }, setMessageStatus(status = '', rowID) { if (status === 'ErrorButton') { if (this._data[rowID].position === 'right') { this._data[rowID].status = 'ErrorButton'; this.refreshRows(); } } else { if (this._data[rowID].position === 'right') { this._data[rowID].status = status; // only 1 message can have a status for (let i = 0; i < this._data.length; i++) { if (i !== rowID && this._data[i].status !== 'ErrorButton') { this._data[i].status = ''; } } this.refreshRows(); } } }, renderAnimatedView() { if (this.props.inverted === true) { return ( <Animated.View style={{ height: this.state.height, }} > <ListView ref='listView' dataSource={this.state.dataSource} renderRow={this.renderRow} renderFooter={this.renderLoadEarlierMessages} style={this.styles.listView} renderScrollComponent={props => <InvertibleScrollView {...props} inverted />} // not working android RN 0.14.2 onKeyboardWillShow={this.onKeyboardWillShow} onKeyboardWillHide={this.onKeyboardWillHide} /* keyboardShouldPersistTaps={false} // @issue keyboardShouldPersistTaps={false} + textInput focused = 2 taps are needed to trigger the ParsedText links keyboardDismissMode='interactive' */ keyboardShouldPersistTaps={true} keyboardDismissMode='on-drag' {...this.props} /> </Animated.View> ); } return ( <Animated.View style={{ height: this.state.height, }} > <ListView ref='listView' dataSource={this.state.dataSource} renderRow={this.renderRow} renderFooter={this.renderLoadEarlierMessages} style={this.styles.listView} // When not inverted: Using Did instead of Will because onKeyboardWillShow is not working in Android RN 0.14.2 onKeyboardDidShow={this.onKeyboardWillShow} onKeyboardDidHide={this.onKeyboardWillHide} /* keyboardShouldPersistTaps={false} // @issue keyboardShouldPersistTaps={false} + textInput focused = 2 taps are needed to trigger the ParsedText links keyboardDismissMode='interactive' */ keyboardShouldPersistTaps={true} keyboardDismissMode='on-drag' {...this.props} /> </Animated.View> ); }, render() { return ( <View style={this.styles.container} ref='container' > {(this.props.inverted === true ? this.renderAnimatedView() : null)} {this.renderTextInput()} {(this.props.inverted === false ? this.renderAnimatedView() : null)} </View> ) }, renderTextInput() { if (this.props.hideTextInput === false) { return ( <View style={this.styles.textInputContainer}> <TextInput style={this.styles.textInput} placeholder={this.props.placeholder} ref='textInput' onChangeText={this.onChangeText} value={this.state.text} autoFocus={this.props.autoFocus} returnKeyType={this.props.submitOnReturn ? 'send' : 'default'} onSubmitEditing={this.props.submitOnReturn ? this.onSend : null} blurOnSubmit={false} /> <Button style={this.styles.sendButton} onPress={this.onSend} disabled={this.state.disabled} > {this.props.sendButtonText} </Button> </View> ); } return null; }, componentWillMount() { this.styles = { container: { flex: 1, backgroundColor: '#FFF', }, listView: { flex: 1, }, textInputContainer: { height: 44, borderTopWidth: 1 / PixelRatio.get(), borderColor: '#b2b2b2', flexDirection: 'row', paddingLeft: 10, paddingRight: 10, }, textInput: { alignSelf: 'center', height: 30, width: 100, backgroundColor: '#FFF', flex: 1, padding: 0, margin: 0, fontSize: 15, }, sendButton: { marginTop: 11, marginLeft: 10, }, name: { color: '#aaaaaa', fontSize: 12, marginLeft: 60, marginBottom: 5, }, date: { color: '#aaaaaa', fontSize: 12, textAlign: 'center', fontWeight: 'bold', marginBottom: 8, }, rowContainer: { flexDirection: 'row', marginBottom: 10, }, imagePosition: { height: 30, width: 30, alignSelf: 'flex-end', marginLeft: 8, marginRight: 8, }, image: { alignSelf: 'center', borderRadius: 15, }, imageLeft: { }, imageRight: { }, bubble: { borderRadius: 15, paddingLeft: 14, paddingRight: 14, paddingBottom: 10, paddingTop: 8, flex: 1, }, text: { color: '#000', }, textLeft: { }, textRight: { color: '#fff', }, bubbleLeft: { marginRight: 70, backgroundColor: '#e6e6eb', }, bubbleRight: { marginLeft: 70, backgroundColor: '#007aff', }, bubbleError: { backgroundColor: '#e01717' }, link: { color: '#007aff', textDecorationLine: 'underline', }, linkLeft: { color: '#000', }, linkRight: { color: '#fff', }, errorButtonContainer: { marginLeft: 8, alignSelf: 'center', justifyContent: 'center', backgroundColor: '#e6e6eb', borderRadius: 15, width: 30, height: 30, }, errorButton: { fontSize: 22, textAlign: 'center', }, status: { color: '#aaaaaa', fontSize: 12, textAlign: 'right', marginRight: 15, marginBottom: 10, marginTop: -5, }, loadEarlierMessages: { height: 44, justifyContent: 'center', alignItems: 'center', }, loadEarlierMessagesButton: { fontSize: 14, }, spacer: { width: 10, }, }; extend(this.styles, this.props.styles); }, }); var ErrorButton = React.createClass({ getInitialState() { return { isLoading: false, }; }, getDefaultProps() { return { onErrorButtonPress: () => {}, rowData: {}, rowID: null, styles: {}, }; }, onPress() { this.setState({ isLoading: true, }); this.props.onErrorButtonPress(this.props.rowData, this.props.rowID); }, render() { if (this.state.isLoading === true) { return ( <View style={[this.props.styles.errorButtonContainer, { backgroundColor: 'transparent', borderRadius: 0, }]}> <GiftedSpinner /> </View> ); } return ( <View style={this.props.styles.errorButtonContainer}> <TouchableHighlight underlayColor='transparent' onPress={this.onPress} > <Text style={this.props.styles.errorButton}>↻</Text> </TouchableHighlight> </View> ); } }); module.exports = GiftedMessenger;
GiftedMessenger.js
'use strict'; var React = require('react-native'); var { Text, View, ListView, TextInput, Dimensions, Animated, Image, TouchableHighlight, Platform, PixelRatio } = React; var moment = require('moment'); var extend = require('extend'); import InvertibleScrollView from 'react-native-invertible-scroll-view'; var GiftedSpinner = require('react-native-gifted-spinner'); var Button = require('react-native-button'); var GiftedMessenger = React.createClass({ getDefaultProps() { return { displayNames: true, placeholder: 'Type a message...', styles: {}, autoFocus: true, onErrorButtonPress: (message, rowID) => {}, loadEarlierMessagesButton: false, loadEarlierMessagesButtonText: 'Load earlier messages', onLoadEarlierMessages: (oldestMessage, callback) => {}, parseText: false, handleUrlPress: (url) => {}, handlePhonePress: (phone) => {}, handleEmailPress: (email) => {}, initialMessages: [], messages: [], handleSend: (message, rowID) => {}, maxHeight: Dimensions.get('window').height, senderName: 'Sender', senderImage: null, sendButtonText: 'Send', onImagePress: null, inverted: true, hideTextInput: false, submitOnReturn: false, }; }, propTypes: { displayNames: React.PropTypes.bool, placeholder: React.PropTypes.string, styles: React.PropTypes.object, autoFocus: React.PropTypes.bool, onErrorButtonPress: React.PropTypes.func, loadEarlierMessagesButton: React.PropTypes.bool, loadEarlierMessagesButtonText: React.PropTypes.string, onLoadEarlierMessages: React.PropTypes.func, parseText: React.PropTypes.bool, handleUrlPress: React.PropTypes.func, handlePhonePress: React.PropTypes.func, handleEmailPress: React.PropTypes.func, initialMessages: React.PropTypes.array, messages: React.PropTypes.array, handleSend: React.PropTypes.func, maxHeight: React.PropTypes.number, senderName: React.PropTypes.string, senderImage: React.PropTypes.object, sendButtonText: React.PropTypes.string, onImagePress: React.PropTypes.func, inverted: React.PropTypes.bool, hideTextInput: React.PropTypes.bool, }, getInitialState: function() { this._data = []; this._rowIds = []; var textInputHeight = 0; if (this.props.hideTextInput === false) { textInputHeight = 44; } this.listViewMaxHeight = this.props.maxHeight - textInputHeight; var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => { if (typeof r1.status !== 'undefined') { return true; } return r1 !== r2; }}); return { dataSource: ds.cloneWithRows([]), text: '', disabled: true, height: new Animated.Value(this.listViewMaxHeight), isLoadingEarlierMessages: false, allLoaded: false, }; }, getMessage(rowID) { if (typeof this._rowIds[this._rowIds.indexOf(rowID)] !== 'undefined') { if (typeof this._data[this._rowIds[this._rowIds.indexOf(rowID)]] !== 'undefined') { return this._data[this._rowIds[this._rowIds.indexOf(rowID)]]; } } return null; }, getPreviousMessage(rowID) { if (typeof this._rowIds[this._rowIds.indexOf(rowID - 1)] !== 'undefined') { if (typeof this._data[this._rowIds[this._rowIds.indexOf(rowID - 1)]] !== 'undefined') { return this._data[this._rowIds[this._rowIds.indexOf(rowID - 1)]]; } } return null; }, getNextMessage(rowID) { if (typeof this._rowIds[this._rowIds.indexOf(rowID + 1)] !== 'undefined') { if (typeof this._data[this._rowIds[this._rowIds.indexOf(rowID + 1)]] !== 'undefined') { return this._data[this._rowIds[this._rowIds.indexOf(rowID + 1)]]; } } return null; }, renderName(rowData = {}, rowID = null) { if (this.props.displayNames === true) { var diffMessage = null; if (this.props.inverted === false) { diffMessage = null; // force rendering } else if (rowData.isOld === true) { diffMessage = this.getNextMessage(rowID); } else { diffMessage = this.getPreviousMessage(rowID); } if (diffMessage === null || (this._data[rowID].name !== diffMessage.name || this._data[rowID].id !== diffMessage.id)) { return ( <Text style={[this.styles.name]}> {rowData.name} </Text> ); } } return null; }, renderDate(rowData = {}, rowID = null) { var diffMessage = null; if (this.props.inverted === false) { diffMessage = null; // force rendering } else if (rowData.isOld === true) { diffMessage = this.getNextMessage(rowID); } else { diffMessage = this.getPreviousMessage(rowID); } if (rowData.date instanceof Date) { if (diffMessage === null) { return ( <Text style={[this.styles.date]}> {moment(rowData.date).calendar()} </Text> ); } else if (diffMessage.date instanceof Date) { let diff = moment(rowData.date).diff(moment(diffMessage.date), 'minutes'); if (diff > 5) { return ( <Text style={[this.styles.date]}> {moment(rowData.date).calendar()} </Text> ); } } } return null; }, renderImage(rowData = {}, rowID = null) { if (rowData.image !== null) { var diffMessage = null; if (this.props.inverted === false) { diffMessage = null; // force rendering } else { diffMessage = this.getNextMessage(rowID); } if (diffMessage === null || (this._data[rowID].name !== diffMessage.name || this._data[rowID].id !== diffMessage.id)) { if (typeof this.props.onImagePress === 'function') { return ( <TouchableHighlight underlayColor='transparent' onPress={() => this.props.onImagePress(rowData, rowID)} style={this.styles.imagePosition} > <Image source={rowData.image} style={[this.styles.imagePosition, this.styles.image, (rowData.position === 'left' ? this.styles.imageLeft : this.styles.imageRight)]}/> </TouchableHighlight> ); } else { return ( <Image source={rowData.image} style={[this.styles.imagePosition, this.styles.image, (rowData.position === 'left' ? this.styles.imageLeft : this.styles.imageRight)]}/> ); } } else { return ( <View style={this.styles.imagePosition}/> ); } } return ( <View style={this.styles.spacer}/> ); }, renderErrorButton(rowData = {}, rowID = null) { if (rowData.status === 'ErrorButton') { return ( <ErrorButton onErrorButtonPress={this.props.onErrorButtonPress} rowData={rowData} rowID={rowID} styles={{ errorButtonContainer: this.styles.errorButtonContainer, errorButton: this.styles.errorButton, }} /> ) } return null; }, renderStatus(rowData = {}, rowID = null) { if (rowData.status !== 'ErrorButton' && typeof rowData.status === 'string') { if (rowData.status.length > 0) { return ( <View> <Text style={this.styles.status}>{rowData.status}</Text> </View> ); } } return null; }, renderText(rowData = {}, rowID = null) { /* if (this.props.parseText === true && Platform.OS !== 'android') { let parse = [ {type: 'url', style: [this.styles.link, (rowData.position === 'left' ? this.styles.linkLeft : this.styles.linkRight)], onPress: this.props.handleUrlPress}, {type: 'phone', style: [this.styles.link, (rowData.position === 'left' ? this.styles.linkLeft : this.styles.linkRight)], onPress: this.props.handlePhonePress}, {type: 'email', style: [this.styles.link, (rowData.position === 'left' ? this.styles.linkLeft : this.styles.linkRight)], onPress: this.props.handleEmailPress}, ]; return ( <ParsedText style={[this.styles.text, (rowData.position === 'left' ? this.styles.textLeft : this.styles.textRight)]} parse={parse} > {rowData.text} </ParsedText> ); } */ return ( <Text style={[this.styles.text, (rowData.position === 'left' ? this.styles.textLeft : this.styles.textRight)]} > {rowData.text} </Text> ); }, renderRow(rowData = {}, sectionID = null, rowID = null) { return ( <View> {this.renderDate(rowData, rowID)} {rowData.position === 'left' ? this.renderName(rowData, rowID) : null} <View style={this.styles.rowContainer}> {rowData.position === 'left' ? this.renderImage(rowData, rowID) : null} {rowData.position === 'right' ? this.renderErrorButton(rowData, rowID) : null} <View style={[this.styles.bubble, (rowData.position === 'left' ? this.styles.bubbleLeft : this.styles.bubbleRight), (rowData.status === 'ErrorButton' ? this.styles.bubbleError : null)]}> {this.renderText(rowData, rowID)} </View> {rowData.position === 'right' ? this.renderImage(rowData, rowID) : null} </View> {rowData.position === 'right' ? this.renderStatus(rowData, rowID) : null} </View> ); }, onChangeText(text) { this.setState({ text: text }) if (text.trim().length > 0) { this.setState({ disabled: false }) } else { this.setState({ disabled: true }) } }, componentDidMount() { this.scrollResponder = this.refs.listView.getScrollResponder(); if (this.props.messages.length > 0) { this.appendMessages(this.props.messages); } else if (this.props.initialMessages.length > 0) { this.appendMessages(this.props.initialMessages); } else { this.setState({ allLoaded: true }); } }, componentWillReceiveProps(nextProps) { this._data = []; this._rowIds = []; this.appendMessages(nextProps.messages); }, onKeyboardWillHide(e) { Animated.timing(this.state.height, { toValue: this.listViewMaxHeight, duration: 150, }).start(); }, onKeyboardWillShow(e) { Animated.timing(this.state.height, { toValue: this.listViewMaxHeight - (e.endCoordinates ? e.endCoordinates.height : e.end.height), duration: 200, }).start(); }, onSend() { var message = { text: this.state.text.trim(), name: this.props.senderName, image: this.props.senderImage, position: 'right', date: new Date(), }; var rowID = this.appendMessage(message); this.props.handleSend(message, rowID); this.onChangeText(''); this.scrollResponder.scrollTo(0); }, postLoadEarlierMessages(messages = [], allLoaded = false) { this.prependMessages(messages); this.setState({ isLoadingEarlierMessages: false }); if (allLoaded === true) { this.setState({ allLoaded: true, }); } }, preLoadEarlierMessages() { this.setState({ isLoadingEarlierMessages: true }); this.props.onLoadEarlierMessages(this._data[this._rowIds[this._rowIds.length - 1]], this.postLoadEarlierMessages); }, renderLoadEarlierMessages() { if (this.props.loadEarlierMessagesButton === true) { if (this.state.allLoaded === false) { if (this.state.isLoadingEarlierMessages === true) { return ( <View style={this.styles.loadEarlierMessages}> <GiftedSpinner /> </View> ); } else { return ( <View style={this.styles.loadEarlierMessages}> <Button style={this.styles.loadEarlierMessagesButton} onPress={() => {this.preLoadEarlierMessages()}} > {this.props.loadEarlierMessagesButtonText} </Button> </View> ); } } } return null; }, prependMessages(messages = []) { var rowID = null; for (let i = 0; i < messages.length; i++) { messages[i].isOld = true; this._data.push(messages[i]); this._rowIds.push(this._data.length - 1); rowID = this._data.length - 1; } this.setState({ dataSource: this.state.dataSource.cloneWithRows(this._data, this._rowIds), }); return rowID; }, prependMessage(message = {}) { var rowID = this.prependMessages([message]); return rowID; }, appendMessages(messages = []) { var rowID = null; for (let i = 0; i < messages.length; i++) { this._data.push(messages[i]); this._rowIds.unshift(this._data.length - 1); rowID = this._data.length - 1; } this.setState({ dataSource: this.state.dataSource.cloneWithRows(this._data, this._rowIds), }); return rowID; }, appendMessage(message = {}) { var rowID = this.appendMessages([message]); return rowID; }, refreshRows() { this.setState({ dataSource: this.state.dataSource.cloneWithRows(this._data, this._rowIds), }); }, setMessageStatus(status = '', rowID) { if (status === 'ErrorButton') { if (this._data[rowID].position === 'right') { this._data[rowID].status = 'ErrorButton'; this.refreshRows(); } } else { if (this._data[rowID].position === 'right') { this._data[rowID].status = status; // only 1 message can have a status for (let i = 0; i < this._data.length; i++) { if (i !== rowID && this._data[i].status !== 'ErrorButton') { this._data[i].status = ''; } } this.refreshRows(); } } }, renderAnimatedView() { if (this.props.inverted === true) { return ( <Animated.View style={{ height: this.state.height, }} > <ListView ref='listView' dataSource={this.state.dataSource} renderRow={this.renderRow} renderFooter={this.renderLoadEarlierMessages} style={this.styles.listView} renderScrollComponent={props => <InvertibleScrollView {...props} inverted />} // not working android RN 0.14.2 onKeyboardWillShow={this.onKeyboardWillShow} onKeyboardWillHide={this.onKeyboardWillHide} /* keyboardShouldPersistTaps={false} // @issue keyboardShouldPersistTaps={false} + textInput focused = 2 taps are needed to trigger the ParsedText links keyboardDismissMode='interactive' */ keyboardShouldPersistTaps={true} keyboardDismissMode='on-drag' {...this.props} /> </Animated.View> ); } return ( <Animated.View style={{ height: this.state.height, }} > <ListView ref='listView' dataSource={this.state.dataSource} renderRow={this.renderRow} renderFooter={this.renderLoadEarlierMessages} style={this.styles.listView} // When not inverted: Using Did instead of Will because onKeyboardWillShow is not working in Android RN 0.14.2 onKeyboardDidShow={this.onKeyboardWillShow} onKeyboardDidHide={this.onKeyboardWillHide} /* keyboardShouldPersistTaps={false} // @issue keyboardShouldPersistTaps={false} + textInput focused = 2 taps are needed to trigger the ParsedText links keyboardDismissMode='interactive' */ keyboardShouldPersistTaps={true} keyboardDismissMode='on-drag' {...this.props} /> </Animated.View> ); }, render() { return ( <View style={this.styles.container} ref='container' > {(this.props.inverted === true ? this.renderAnimatedView() : null)} {this.renderTextInput()} {(this.props.inverted === false ? this.renderAnimatedView() : null)} </View> ) }, renderTextInput() { if (this.props.hideTextInput === false) { return ( <View style={this.styles.textInputContainer}> <TextInput style={this.styles.textInput} placeholder={this.props.placeholder} ref='textInput' onChangeText={this.onChangeText} value={this.state.text} autoFocus={this.props.autoFocus} returnKeyType={this.props.submitOnReturn ? 'send' : 'default'} onSubmitEditing={this.props.submitOnReturn ? this.onSend : null} blurOnSubmit={false} /> <Button style={this.styles.sendButton} onPress={this.onSend} disabled={this.state.disabled} > {this.props.sendButtonText} </Button> </View> ); } return null; }, componentWillMount() { this.styles = { container: { flex: 1, backgroundColor: '#FFF', }, listView: { flex: 1, }, textInputContainer: { height: 44, borderTopWidth: 1 / PixelRatio.get(), borderColor: '#b2b2b2', flexDirection: 'row', paddingLeft: 10, paddingRight: 10, }, textInput: { alignSelf: 'center', height: 30, width: 100, backgroundColor: '#FFF', flex: 1, padding: 0, margin: 0, fontSize: 15, }, sendButton: { marginTop: 11, marginLeft: 10, }, name: { color: '#aaaaaa', fontSize: 12, marginLeft: 60, marginBottom: 5, }, date: { color: '#aaaaaa', fontSize: 12, textAlign: 'center', fontWeight: 'bold', marginBottom: 8, }, rowContainer: { flexDirection: 'row', marginBottom: 10, }, imagePosition: { height: 30, width: 30, alignSelf: 'flex-end', marginLeft: 8, marginRight: 8, }, image: { alignSelf: 'center', borderRadius: 15, }, imageLeft: { }, imageRight: { }, bubble: { borderRadius: 15, paddingLeft: 14, paddingRight: 14, paddingBottom: 10, paddingTop: 8, flex: 1, }, text: { color: '#000', }, textLeft: { }, textRight: { color: '#fff', }, bubbleLeft: { marginRight: 70, backgroundColor: '#e6e6eb', }, bubbleRight: { marginLeft: 70, backgroundColor: '#007aff', }, bubbleError: { backgroundColor: '#e01717' }, link: { color: '#007aff', textDecorationLine: 'underline', }, linkLeft: { color: '#000', }, linkRight: { color: '#fff', }, errorButtonContainer: { marginLeft: 8, alignSelf: 'center', justifyContent: 'center', backgroundColor: '#e6e6eb', borderRadius: 15, width: 30, height: 30, }, errorButton: { fontSize: 22, textAlign: 'center', }, status: { color: '#aaaaaa', fontSize: 12, textAlign: 'right', marginRight: 15, marginBottom: 10, marginTop: -5, }, loadEarlierMessages: { height: 44, justifyContent: 'center', alignItems: 'center', }, loadEarlierMessagesButton: { fontSize: 14, }, spacer: { width: 10, }, }; extend(this.styles, this.props.styles); }, }); var ErrorButton = React.createClass({ getInitialState() { return { isLoading: false, }; }, getDefaultProps() { return { onErrorButtonPress: () => {}, rowData: {}, rowID: null, styles: {}, }; }, onPress() { this.setState({ isLoading: true, }); this.props.onErrorButtonPress(this.props.rowData, this.props.rowID); }, render() { if (this.state.isLoading === true) { return ( <View style={[this.props.styles.errorButtonContainer, { backgroundColor: 'transparent', borderRadius: 0, }]}> <GiftedSpinner /> </View> ); } return ( <View style={this.props.styles.errorButtonContainer}> <TouchableHighlight underlayColor='transparent' onPress={this.onPress} > <Text style={this.props.styles.errorButton}>↻</Text> </TouchableHighlight> </View> ); } }); module.exports = GiftedMessenger;
Add custom renderText and onSend
GiftedMessenger.js
Add custom renderText and onSend
<ide><path>iftedMessenger.js <ide> initialMessages: React.PropTypes.array, <ide> messages: React.PropTypes.array, <ide> handleSend: React.PropTypes.func, <add> onCustomSend: React.PropTypes.func, <add> renderCustomText: React.PropTypes.func, <ide> maxHeight: React.PropTypes.number, <ide> senderName: React.PropTypes.string, <ide> senderImage: React.PropTypes.object, <ide> ); <ide> } <ide> */ <add> if (this.props.renderCustomText) { <add> return this.props.renderCustomText(rowData, rowID); <add> } <ide> return ( <ide> <Text <ide> style={[this.styles.text, (rowData.position === 'left' ? this.styles.textLeft : this.styles.textRight)]} <ide> position: 'right', <ide> date: new Date(), <ide> }; <del> var rowID = this.appendMessage(message); <del> this.props.handleSend(message, rowID); <del> this.onChangeText(''); <del> this.scrollResponder.scrollTo(0); <add> if (this.props.onCustomSend) { <add> this.props.onCustomSend(message); <add> } else { <add> var rowID = this.appendMessage(message); <add> this.props.handleSend(message, rowID); <add> this.onChangeText(''); <add> this.scrollResponder.scrollTo(0); <add> } <ide> }, <ide> <ide> postLoadEarlierMessages(messages = [], allLoaded = false) {
Java
mit
fba7302d90b894c20f067bcd740978337e8a574f
0
koreader/android-luajit-launcher,koreader/android-luajit-launcher,koreader/android-luajit-launcher,koreader/android-luajit-launcher
package org.koreader.launcher; import android.content.Context; import android.content.Intent; import android.net.DhcpInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.text.format.Formatter; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import org.koreader.device.DeviceInfo; import org.koreader.device.EPDController; import org.koreader.device.EPDFactory; public class MainActivity extends android.app.NativeActivity { private final static int SDK_INT = Build.VERSION.SDK_INT; private final static String LOGGER_NAME = "luajit-launcher"; static { System.loadLibrary("luajit"); } private FramelessProgressDialog dialog; private DeviceInfo device; private EPDController epd = EPDFactory.getEPDController(); private Clipboard clipboard; private PowerHelper power; private ScreenHelper screen; public MainActivity() { super(); Log.i(LOGGER_NAME, "Creating luajit launcher main activity"); } /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); clipboard = new Clipboard(this, LOGGER_NAME); power = new PowerHelper(this, LOGGER_NAME); screen = new ScreenHelper(this, LOGGER_NAME); /** Listen to visibility changes */ if (SDK_INT >= Build.VERSION_CODES.KITKAT) { setFullscreenLayout(); View decorView = getWindow().getDecorView(); decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int visibility) { setFullscreenLayout(); } }); } } /** Called when the activity has become visible. */ @Override protected void onResume() { Log.v(LOGGER_NAME, "App resumed"); power.setWakelock(true); super.onResume(); /** switch to fullscreen for older devices */ if (SDK_INT < Build.VERSION_CODES.KITKAT) { final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { setFullscreenLayout(); } }, 500); } } /** Called when another activity is taking focus. */ @Override protected void onPause() { Log.v(LOGGER_NAME, "App paused"); power.setWakelock(false); super.onPause(); } /** Called when the activity is no longer visible. */ @Override protected void onStop() { Log.v(LOGGER_NAME, "App stopped"); super.onStop(); } /** Called just before the activity is destroyed. */ @Override protected void onDestroy() { Log.v(LOGGER_NAME, "App destroyed"); clipboard = null; power = null; screen = null; super.onDestroy(); } /** Called just before the activity is resumed by an intent */ @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); } /** These functions are exposed to lua in assets/android.lua * If you add a new function here remember to write the companion * lua function in that file */ /** clipboard */ public String getClipboardText() { return clipboard.getClipboardText(); } public int hasClipboardTextIntResultWrapper() { return clipboard.hasClipboardText(); } public void setClipboardText(final String text) { clipboard.setClipboardText(text); } /** device */ public String getProduct() { return device.PRODUCT; } public String getVersion() { return android.os.Build.VERSION.RELEASE; } public int isEink() { return (device.IS_EINK_SUPPORTED) ? 1 : 0; } public void einkUpdate(int mode) { String mode_name = "invalid mode"; final View root_view = getWindow().getDecorView().findViewById(android.R.id.content); if (mode == device.EPD_FULL) { mode_name = "EPD_FULL"; } else if (mode == device.EPD_PART) { mode_name = "EPD_PART"; } else if (mode == device.EPD_A2) { mode_name = "EPD_A2"; } else if (mode == device.EPD_AUTO) { mode_name = "EPD_AUTO"; } else { Log.e(LOGGER_NAME, String.format("%s: %d", mode_name, mode)); return; } Log.v(LOGGER_NAME, String.format("requesting eink refresh, type: %s", mode_name)); epd.setEpdMode(root_view, mode_name); } /** dialogs */ public void showProgress(final String title, final String message) { runOnUiThread(new Runnable() { @Override public void run() { dialog = FramelessProgressDialog.show(MainActivity.this, title, message, true, false); } }); } public void dismissProgress() { runOnUiThread(new Runnable() { @Override public void run() { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } } }); } /** power */ public int isCharging() { return power.batteryCharging(); } public int getBatteryLevel() { return power.batteryPercent(); } public void setWakeLock(final boolean enabled) { power.setWakelockState(enabled); } /** screen */ public int getScreenBrightness() { return screen.getScreenBrightness(); } public int getScreenHeight() { return screen.getScreenHeight(); } public int getScreenWidth() { return screen.getScreenWidth(); } public int getStatusBarHeight() { return screen.getStatusBarHeight(); } public int isFullscreen() { return screen.isFullscreen(); } public void setFullscreen(final boolean enabled) { screen.setFullscreen(enabled); } public void setScreenBrightness(final int brightness) { screen.setScreenBrightness(brightness); } /** wifi */ public void setWifiEnabled(final boolean enabled) { runOnUiThread(new Runnable() { @Override public void run() { getWifiManager().setWifiEnabled(enabled); } }); } public int isWifiEnabled() { return getWifiManager().isWifiEnabled() ? 1 : 0; } public String getNetworkInfo() { final WifiInfo wi = getWifiManager().getConnectionInfo(); final DhcpInfo dhcp = getWifiManager().getDhcpInfo(); int ip = wi.getIpAddress(); int gw = dhcp.gateway; String ip_address; String gw_address; if (ip > 0) { ip_address = Formatter.formatIpAddress(ip); } else { ip_address = String.valueOf(ip); } if (gw > 0) { gw_address = Formatter.formatIpAddress(gw); } else { gw_address = String.valueOf(gw); } return String.format("%s;%s;%s", wi.getSSID(), ip_address, gw_address); } // ---------------------------------- private WifiManager getWifiManager() { return (WifiManager) this.getSystemService(Context.WIFI_SERVICE); } private void setFullscreenLayout() { View decorView = getWindow().getDecorView(); if (SDK_INT >= Build.VERSION_CODES.KITKAT) { decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); } else { decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LOW_PROFILE); } } }
src/org/koreader/launcher/MainActivity.java
package org.koreader.launcher; import android.content.Context; import android.content.Intent; import android.net.DhcpInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.text.format.Formatter; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import org.koreader.device.DeviceInfo; import org.koreader.device.EPDController; import org.koreader.device.EPDFactory; public class MainActivity extends android.app.NativeActivity { private final static int SDK_INT = Build.VERSION.SDK_INT; private final static String LOGGER_NAME = "luajit-launcher"; static { System.loadLibrary("luajit"); } private FramelessProgressDialog dialog; private DeviceInfo device; private EPDController epd = EPDFactory.getEPDController(); private Clipboard clipboard; private PowerHelper power; private ScreenHelper screen; public MainActivity() { super(); Log.i(LOGGER_NAME, "Creating luajit launcher main activity"); } /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); clipboard = new Clipboard(this, LOGGER_NAME); power = new PowerHelper(this, LOGGER_NAME); screen = new ScreenHelper(this, LOGGER_NAME); /** Listen to visibility changes */ if (SDK_INT >= Build.VERSION_CODES.KITKAT) { setFullscreenLayout(); View decorView = getWindow().getDecorView(); decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int visibility) { setFullscreenLayout(); } }); } } /** Called when the activity has become visible. */ @Override protected void onResume() { Log.v(LOGGER_NAME, "App resumed"); power.setWakelock(true); super.onResume(); /** switch to fullscreen for older devices */ if (SDK_INT < Build.VERSION_CODES.KITKAT) { final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { setFullscreenLayout(); } }, 500); } } /** Called when another activity is taking focus. */ @Override protected void onPause() { Log.v(LOGGER_NAME, "App paused"); power.setWakelock(false); super.onPause(); } /** Called when the activity is no longer visible. */ @Override protected void onStop() { Log.v(LOGGER_NAME, "App stopped"); super.onStop(); } /** Called just before the activity is destroyed. */ @Override protected void onDestroy() { Log.v(LOGGER_NAME, "App destroyed"); clipboard = null; power = null; screen = null; super.onDestroy(); } /** Called just before the activity is resumed by an intent */ @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); } /** These functions are exposed to lua in assets/android.lua * If you add a new function here remember to write the companion * lua function in that file */ /** clipboard */ public String getClipboardText() { return clipboard.getClipboardText(); } public int hasClipboardTextIntResultWrapper() { return clipboard.hasClipboardText(); } public void setClipboardText(final String text) { clipboard.setClipboardText(text); } /** device */ public String getProduct() { return device.PRODUCT; } public String getVersion() { return android.os.Build.VERSION.RELEASE; } public int isEink() { return (device.IS_EINK_SUPPORTED) ? 1 : 0; } public void einkUpdate(int mode) { String mode_name = "invalid mode"; final View root_view = getWindow().getDecorView().findViewById(android.R.id.content); if (mode == device.EPD_FULL) { mode_name = "EPD_FULL"; } else if (mode == device.EPD_PART) { mode_name = "EPD_PART"; } else if (mode == device.EPD_A2) { mode_name = "EPD_A2"; } else if (mode == device.EPD_AUTO) { mode_name = "EPD_AUTO"; } else { Log.e(LOGGER_NAME, String.format("%s: %d", mode_name, mode)); return; } Log.v(LOGGER_NAME, String.format("requesting eink refresh, type: %s", mode_name)); epd.setEpdMode(root_view, mode_name); } /** dialogs */ public void showProgress(final String title, final String message) { runOnUiThread(new Runnable() { @Override public void run() { dialog = FramelessProgressDialog.show(MainActivity.this, title, message, true, false); } }); } public void dismissProgress() { runOnUiThread(new Runnable() { @Override public void run() { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } } }); } /** power */ public int isCharging() { return power.batteryCharging(); } public int getBatteryLevel() { return power.batteryPercent(); } public void setWakeLock(final boolean enabled) { power.setWakelockState(enabled); } /** screen */ public int getScreenBrightness() { return screen.getScreenBrightness(); } public int getScreenHeight() { return screen.getScreenHeight(); } public int getScreenWidth() { return screen.getScreenWidth(); } public int isFullscreen() { return screen.isFullscreen(); } public void setFullscreen(final boolean enabled) { screen.setFullscreen(enabled); } public void setScreenBrightness(final int brightness) { screen.setScreenBrightness(brightness); } /** wifi */ public void setWifiEnabled(final boolean enabled) { runOnUiThread(new Runnable() { @Override public void run() { getWifiManager().setWifiEnabled(enabled); } }); } public int isWifiEnabled() { return getWifiManager().isWifiEnabled() ? 1 : 0; } public String getNetworkInfo() { final WifiInfo wi = getWifiManager().getConnectionInfo(); final DhcpInfo dhcp = getWifiManager().getDhcpInfo(); int ip = wi.getIpAddress(); int gw = dhcp.gateway; String ip_address; String gw_address; if (ip > 0) { ip_address = Formatter.formatIpAddress(ip); } else { ip_address = String.valueOf(ip); } if (gw > 0) { gw_address = Formatter.formatIpAddress(gw); } else { gw_address = String.valueOf(gw); } return String.format("%s;%s;%s", wi.getSSID(), ip_address, gw_address); } // ---------------------------------- private WifiManager getWifiManager() { return (WifiManager) this.getSystemService(Context.WIFI_SERVICE); } private void setFullscreenLayout() { View decorView = getWindow().getDecorView(); if (SDK_INT >= Build.VERSION_CODES.KITKAT) { decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); } else { decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LOW_PROFILE); } } }
unbreak fullscreen toggle in api14-15 (#119)
src/org/koreader/launcher/MainActivity.java
unbreak fullscreen toggle in api14-15 (#119)
<ide><path>rc/org/koreader/launcher/MainActivity.java <ide> return screen.getScreenWidth(); <ide> } <ide> <add> public int getStatusBarHeight() { <add> return screen.getStatusBarHeight(); <add> } <add> <ide> public int isFullscreen() { <ide> return screen.isFullscreen(); <ide> }
Java
apache-2.0
a3daab37e99fa18fe5235c9bc756de28b3eeaad6
0
dldinternet/resty-gwt,cguillot/resty-gwt,Armageddon-/resty-gwt,BiovistaInc/resty-gwt,dldinternet/resty-gwt,paul-duffy/resty-gwt,resty-gwt/resty-gwt,Armageddon-/resty-gwt,Armageddon-/resty-gwt,ibaca/resty-gwt,cguillot/resty-gwt,cguillot/resty-gwt,BiovistaInc/resty-gwt,BiovistaInc/resty-gwt,ibaca/resty-gwt,paul-duffy/resty-gwt,resty-gwt/resty-gwt,paul-duffy/resty-gwt,ibaca/resty-gwt,resty-gwt/resty-gwt
/** * Copyright (C) 2009-2010 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * 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. */ package org.fusesource.restygwt.client; import java.util.Map; import java.util.Map.Entry; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.json.client.JSONException; import com.google.gwt.json.client.JSONParser; import com.google.gwt.json.client.JSONValue; import com.google.gwt.xml.client.Document; import com.google.gwt.xml.client.XMLParser; /** * * @author <a href="http://hiramchirino.com">Hiram Chirino</a> */ public class Method { /** * GWT hides the full spectrum of methods because safari has a bug: * http://bugs.webkit.org/show_bug.cgi?id=3812 * * We extend assume the server side will also check the * X-HTTP-Method-Override header. * * TODO: add an option to support using this approach to bypass restrictive * firewalls even if the browser does support the setting all the method * types. * * @author chirino */ static private class MethodRequestBuilder extends RequestBuilder { public MethodRequestBuilder(String method, String url) { super(method, url); setHeader("X-HTTP-Method-Override", method); } } RequestBuilder builder; int expectedStatus = 200; Request request; Response response; protected Method() { } public Method(Resource resource, String method) { builder = new MethodRequestBuilder(method, resource.getUri()); } public Method user(String user) { builder.setUser(user); return this; } public Method password(String password) { builder.setPassword(password); return this; } public Method header(String header, String value) { builder.setHeader(header, value); return this; } public Method headers(Map<String, String> headers) { if (headers != null) { for (Entry<String, String> entry : headers.entrySet()) { builder.setHeader(entry.getKey(), entry.getValue()); } } return this; } private void doSetTimeout() { if (Defaults.getRequestTimeout() > -1) { builder.setTimeoutMillis(Defaults.getRequestTimeout()); } } public Method text(String data) { defaultContentType(Resource.CONTENT_TYPE_TEXT); builder.setRequestData(data); return this; } public Method json(JSONValue data) { defaultContentType(Resource.CONTENT_TYPE_JSON); builder.setRequestData(data.toString()); return this; } public Method xml(Document data) { defaultContentType(Resource.CONTENT_TYPE_XML); builder.setRequestData(data.toString()); return this; } public Method timeout(int timeout) { builder.setTimeoutMillis(timeout); return this; } /** * sets the expected response status code. If the response status code does not match * this value then the request is considered to have failed. Defaults to 200. If set to * -1 then any status code is considered a success. */ public Method expect(int status) { this.expectedStatus = status; return this; } public void send(final RequestCallback callback) throws RequestException { doSetTimeout(); builder.setCallback(new RequestCallback() { public void onResponseReceived(Request request, Response response) { callback.onResponseReceived(request, response); } public void onError(Request request, Throwable exception) { callback.onResponseReceived(request, response); } }); GWT.log("Sending http request: " + builder.getHTTPMethod() + " " + builder.getUrl() + " ,timeout:" + builder.getTimeoutMillis(), null); String content = builder.getRequestData(); if (content != null && content.length() > 0) { GWT.log(content, null); } request = builder.send(); } public void send(final TextCallback callback) { defaultAcceptType(Resource.CONTENT_TYPE_TEXT); try { send(new AbstractRequestCallback<String>(this, callback) { protected String parseResult() throws Exception { return response.getText(); } }); } catch (RequestException e) { GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e); callback.onFailure(this, e); } } public void send(final JsonCallback callback) { defaultAcceptType(Resource.CONTENT_TYPE_JSON); try { send(new AbstractRequestCallback<JSONValue>(this, callback) { protected JSONValue parseResult() throws Exception { try { return JSONParser.parse(response.getText()); } catch (Throwable e) { throw new ResponseFormatException("Response was NOT a valid JSON document", e); } } }); } catch (RequestException e) { GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e); callback.onFailure(this, e); } } public void send(final XmlCallback callback) { defaultAcceptType(Resource.CONTENT_TYPE_XML); try { send(new AbstractRequestCallback<Document>(this, callback) { protected Document parseResult() throws Exception { try { return XMLParser.parse(response.getText()); } catch (Throwable e) { throw new ResponseFormatException("Response was NOT a valid XML document", e); } } }); } catch (RequestException e) { GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e); callback.onFailure(this, e); } } public <T extends JavaScriptObject> void send(final OverlayCallback<T> callback) { defaultAcceptType(Resource.CONTENT_TYPE_JSON); try { send(new AbstractRequestCallback<T>(this, callback) { protected T parseResult() throws Exception { try { JSONValue val = JSONParser.parse(response.getText()); if (val.isObject() != null) { return (T) val.isObject().getJavaScriptObject(); } else if (val.isArray() != null) { return (T) val.isArray().getJavaScriptObject(); } else { throw new ResponseFormatException("Response was NOT a JSON object"); } } catch (JSONException e) { throw new ResponseFormatException("Response was NOT a valid JSON document", e); } catch (IllegalArgumentException e) { throw new ResponseFormatException("Response was NOT a valid JSON document", e); } } }); } catch (RequestException e) { GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e); callback.onFailure(this, e); } } public Request getRequest() { return request; } public Response getResponse() { return response; } protected void defaultContentType(String type) { if (builder.getHeader(Resource.HEADER_CONTENT_TYPE) == null) { header(Resource.HEADER_CONTENT_TYPE, type); } } protected void defaultAcceptType(String type) { if (builder.getHeader(Resource.HEADER_ACCEPT) == null) { header(Resource.HEADER_ACCEPT, type); } } }
restygwt/src/main/java/org/fusesource/restygwt/client/Method.java
/** * Copyright (C) 2009-2010 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * 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. */ package org.fusesource.restygwt.client; import java.util.Map; import java.util.Map.Entry; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.json.client.JSONException; import com.google.gwt.json.client.JSONParser; import com.google.gwt.json.client.JSONValue; import com.google.gwt.xml.client.Document; import com.google.gwt.xml.client.XMLParser; /** * * @author <a href="http://hiramchirino.com">Hiram Chirino</a> */ public class Method { /** * GWT hides the full spectrum of methods because safari has a bug: * http://bugs.webkit.org/show_bug.cgi?id=3812 * * We extend assume the server side will also check the * X-HTTP-Method-Override header. * * TODO: add an option to support using this approach to bypass restrictive * firewalls even if the browser does support the setting all the method * types. * * @author chirino */ static private class MethodRequestBuilder extends RequestBuilder { public MethodRequestBuilder(String method, String url) { super(method, url); setHeader("X-HTTP-Method-Override", method); } } RequestBuilder builder; int expectedStatus = 200; Request request; Response response; protected Method() { } public Method(Resource resource, String method) { builder = new MethodRequestBuilder(method, resource.getUri()); } public Method user(String user) { builder.setUser(user); return this; } public Method password(String password) { builder.setPassword(password); return this; } public Method header(String header, String value) { builder.setHeader(header, value); return this; } public Method headers(Map<String, String> headers) { if (headers != null) { for (Entry<String, String> entry : headers.entrySet()) { builder.setHeader(entry.getKey(), entry.getValue()); } } return this; } private void doSetTimeout() { if (Defaults.getRequestTimeout() > -1) { builder.setTimeoutMillis(Defaults.getRequestTimeout()); } } public Method text(String data) { defaultContentType(Resource.CONTENT_TYPE_TEXT); builder.setRequestData(data); return this; } public Method json(JSONValue data) { defaultContentType(Resource.CONTENT_TYPE_JSON); builder.setRequestData(data.toString()); return this; } public Method xml(Document data) { defaultContentType(Resource.CONTENT_TYPE_XML); builder.setRequestData(data.toString()); return this; } public Method timeout(int timeout) { builder.setTimeoutMillis(timeout); return this; } /** * sets the expected response status code. If the response status code does not match * this value then the request is considered to have failed. Defaults to 200. If set to * -1 then any status code is considered a success. */ public Method expect(int status) { this.expectedStatus = status; return this; } public void send(final RequestCallback callback) throws RequestException { doSetTimeout(); builder.setCallback(new RequestCallback() { public void onResponseReceived(Request request, Response response) { callback.onResponseReceived(request, response); } public void onError(Request request, Throwable exception) { callback.onResponseReceived(request, response); } }); GWT.log("Sending http request: " + builder.getHTTPMethod() + " " + builder.getUrl() + " ,timeout:" + builder.getTimeoutMillis(), null); String content = builder.getRequestData(); if (content != null && content.length() > 0) { GWT.log(content, null); } request = builder.send(); } public void send(final TextCallback callback) { defaultAcceptType(Resource.CONTENT_TYPE_TEXT); try { send(new AbstractRequestCallback<String>(this, callback) { protected String parseResult() throws Exception { return response.getText(); } }); } catch (RequestException e) { GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e); callback.onFailure(this, e); } } public void send(final JsonCallback callback) { defaultAcceptType(Resource.CONTENT_TYPE_JSON); try { send(new AbstractRequestCallback<JSONValue>(this, callback) { protected JSONValue parseResult() throws Exception { try { return JSONParser.parse(response.getText()); } catch (Throwable e) { throw new ResponseFormatException("Response was NOT a valid JSON document", e); } } }); } catch (RequestException e) { GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e); callback.onFailure(this, e); } } public void send(final XmlCallback callback) { defaultAcceptType(Resource.CONTENT_TYPE_XML); try { send(new AbstractRequestCallback<Document>(this, callback) { protected Document parseResult() throws Exception { try { return XMLParser.parse(response.getText()); } catch (Throwable e) { throw new ResponseFormatException("Response was NOT a valid XML document", e); } } }); } catch (RequestException e) { GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e); callback.onFailure(this, e); } } public <T extends JavaScriptObject> void send(final OverlayCallback<T> callback) { defaultAcceptType(Resource.CONTENT_TYPE_JSON); try { send(new AbstractRequestCallback<T>(this, callback) { protected T parseResult() throws Exception { try { JSONValue val = JSONParser.parse(response.getText()); if (val.isObject() == null) { throw new ResponseFormatException("Response was NOT a JSON object"); } return (T) val.isObject().getJavaScriptObject(); } catch (JSONException e) { throw new ResponseFormatException("Response was NOT a valid JSON document", e); } catch (IllegalArgumentException e) { throw new ResponseFormatException("Response was NOT a valid JSON document", e); } } }); } catch (RequestException e) { GWT.log("Received http error for: " + builder.getHTTPMethod() + " " + builder.getUrl(), e); callback.onFailure(this, e); } } public Request getRequest() { return request; } public Response getResponse() { return response; } protected void defaultContentType(String type) { if (builder.getHeader(Resource.HEADER_CONTENT_TYPE) == null) { header(Resource.HEADER_CONTENT_TYPE, type); } } protected void defaultAcceptType(String type) { if (builder.getHeader(Resource.HEADER_ACCEPT) == null) { header(Resource.HEADER_ACCEPT, type); } } }
Add support for receiving a Json Array as an Overlay Object
restygwt/src/main/java/org/fusesource/restygwt/client/Method.java
Add support for receiving a Json Array as an Overlay Object
<ide><path>estygwt/src/main/java/org/fusesource/restygwt/client/Method.java <ide> protected T parseResult() throws Exception { <ide> try { <ide> JSONValue val = JSONParser.parse(response.getText()); <del> if (val.isObject() == null) { <add> if (val.isObject() != null) { <add> return (T) val.isObject().getJavaScriptObject(); <add> } else if (val.isArray() != null) { <add> return (T) val.isArray().getJavaScriptObject(); <add> } else { <ide> throw new ResponseFormatException("Response was NOT a JSON object"); <ide> } <del> return (T) val.isObject().getJavaScriptObject(); <ide> } catch (JSONException e) { <ide> throw new ResponseFormatException("Response was NOT a valid JSON document", e); <ide> } catch (IllegalArgumentException e) {
Java
apache-2.0
07c5a3dd48785eeed1672bb30d742007a4ede2f2
0
mikosik/smooth-build,mikosik/smooth-build
package org.smoothbuild.builtin.java; import static org.smoothbuild.fs.base.Path.path; import java.io.IOException; import org.junit.Ignore; import org.junit.Test; import org.smoothbuild.builtin.java.junit.JunitTestFailedError; import org.smoothbuild.fs.base.Path; import org.smoothbuild.integration.IntegrationTestCase; import org.smoothbuild.testing.parse.ScriptBuilder; // TODO @Ignore("For strange reasons this test fails when run by ant") public class JunitSmoothTest extends IntegrationTestCase { Path srcPath = path("src"); Path fakeJunitPath = path("junit"); @Test public void runSuccessfulTest() throws Exception { createTestAnnotation(); createSuccessfulTest(); script(createScript()); smoothApp.run("run"); messages.assertNoProblems(); } @Test public void runFailingTest() throws Exception { createTestAnnotation(); createFailingTest(); script(createScript()); smoothApp.run("run"); messages.assertOnlyProblem(JunitTestFailedError.class); } private String createScript() { ScriptBuilder builder = new ScriptBuilder(); builder.addLine("sources: files(" + srcPath + ");"); builder.addLine("fakeJunitJar: files(" + fakeJunitPath + ") | javac | jar;"); builder.addLine("jarFile: sources | javac(libs=[fakeJunitJar]) | jar;"); builder.addLine("run: junit(libs=[jarFile]);"); String script = builder.build(); return script; } // Creating fake @Test annotation class is the simplest way to compile junit // tests private void createTestAnnotation() throws IOException { ScriptBuilder builder = new ScriptBuilder(); builder.addLine("package org.junit;"); builder.addLine("import java.lang.annotation.ElementType;"); builder.addLine("import java.lang.annotation.Retention;"); builder.addLine("import java.lang.annotation.RetentionPolicy;"); builder.addLine("import java.lang.annotation.Target;"); builder.addLine("@Retention(RetentionPolicy.RUNTIME)"); builder.addLine("@Target({ ElementType.METHOD })"); builder.addLine("public @interface Test {"); builder.addLine(" static class None extends Throwable {"); builder.addLine(" private static final long serialVersionUID = 1L;"); builder.addLine(" private None() {"); builder.addLine(" }"); builder.addLine(" }"); builder.addLine(" Class<? extends Throwable> expected() default None.class;"); builder.addLine(" long timeout() default 0L;"); builder.addLine("}"); String sourceCode = builder.build(); Path path = fakeJunitPath.append(path("org/junit/Test.java")); fileSystem.createFileWithContent(path, sourceCode); } private void createSuccessfulTest() throws IOException { ScriptBuilder builder = new ScriptBuilder(); builder.addLine("public class MyClassTest {"); builder.addLine(" @org.junit.Test"); builder.addLine(" public void testMyMethod() {"); builder.addLine(" }"); builder.addLine("}"); String sourceCode = builder.build(); Path path = srcPath.append(path("MyClassTest.java")); fileSystem.createFileWithContent(path, sourceCode); } private void createFailingTest() throws IOException { ScriptBuilder builder = new ScriptBuilder(); builder.addLine("public class MyClassFailingTest {"); builder.addLine(" @org.junit.Test"); builder.addLine(" public void testMyMethod() {"); builder.addLine(" throw new AssertionError();"); builder.addLine(" }"); builder.addLine("}"); String sourceCode = builder.build(); Path path = srcPath.append(path("MyClassFailingTest.java")); fileSystem.createFileWithContent(path, sourceCode); } }
src/test-integration/org/smoothbuild/builtin/java/JunitSmoothTest.java
package org.smoothbuild.builtin.java; import static org.smoothbuild.fs.base.Path.path; import java.io.IOException; import org.junit.Ignore; import org.junit.Test; import org.smoothbuild.builtin.java.junit.JunitTestFailedError; import org.smoothbuild.fs.base.Path; import org.smoothbuild.integration.IntegrationTestCase; import org.smoothbuild.testing.parse.ScriptBuilder; import org.smoothbuild.testing.type.impl.FakeFile; // TODO @Ignore("For strange reasons this test fails when run by ant") public class JunitSmoothTest extends IntegrationTestCase { Path srcPath = path("src"); Path fakeJunitPath = path("junit"); @Test public void runSuccessfulTest() throws Exception { createTestAnnotation(); createSuccessfulTest(); script(createScript()); smoothApp.run("run"); messages.assertNoProblems(); } @Test public void runFailingTest() throws Exception { createTestAnnotation(); createFailingTest(); script(createScript()); smoothApp.run("run"); messages.assertOnlyProblem(JunitTestFailedError.class); } private String createScript() { ScriptBuilder builder = new ScriptBuilder(); builder.addLine("sources: files(" + srcPath + ");"); builder.addLine("fakeJunitJar: files(" + fakeJunitPath + ") | javac | jar;"); builder.addLine("jarFile: sources | javac(libs=[fakeJunitJar]) | jar;"); builder.addLine("run: junit(libs=[jarFile]);"); String script = builder.build(); return script; } // Creating fake @Test annotation class is the simplest way to compile junit // tests private void createTestAnnotation() throws IOException { ScriptBuilder builder = new ScriptBuilder(); builder.addLine("package org.junit;"); builder.addLine("import java.lang.annotation.ElementType;"); builder.addLine("import java.lang.annotation.Retention;"); builder.addLine("import java.lang.annotation.RetentionPolicy;"); builder.addLine("import java.lang.annotation.Target;"); builder.addLine("@Retention(RetentionPolicy.RUNTIME)"); builder.addLine("@Target({ ElementType.METHOD })"); builder.addLine("public @interface Test {"); builder.addLine(" static class None extends Throwable {"); builder.addLine(" private static final long serialVersionUID = 1L;"); builder.addLine(" private None() {"); builder.addLine(" }"); builder.addLine(" }"); builder.addLine(" Class<? extends Throwable> expected() default None.class;"); builder.addLine(" long timeout() default 0L;"); builder.addLine("}"); String sourceCode = builder.build(); FakeFile classFile = file(fakeJunitPath.append(path("org/junit/Test.java"))); classFile.createContent(sourceCode); } private void createSuccessfulTest() throws IOException { ScriptBuilder builder = new ScriptBuilder(); builder.addLine("public class MyClassTest {"); builder.addLine(" @org.junit.Test"); builder.addLine(" public void testMyMethod() {"); builder.addLine(" }"); builder.addLine("}"); String sourceCode = builder.build(); FakeFile classFile = file(srcPath.append(path("MyClassTest.java"))); classFile.createContent(sourceCode); } private void createFailingTest() throws IOException { ScriptBuilder builder = new ScriptBuilder(); builder.addLine("public class MyClassFailingTest {"); builder.addLine(" @org.junit.Test"); builder.addLine(" public void testMyMethod() {"); builder.addLine(" throw new AssertionError();"); builder.addLine(" }"); builder.addLine("}"); String sourceCode = builder.build(); FakeFile classFile = file(srcPath.append(path("MyClassFailingTest.java"))); classFile.createContent(sourceCode); } }
refactored JunitSmoothTest
src/test-integration/org/smoothbuild/builtin/java/JunitSmoothTest.java
refactored JunitSmoothTest
<ide><path>rc/test-integration/org/smoothbuild/builtin/java/JunitSmoothTest.java <ide> import org.smoothbuild.fs.base.Path; <ide> import org.smoothbuild.integration.IntegrationTestCase; <ide> import org.smoothbuild.testing.parse.ScriptBuilder; <del>import org.smoothbuild.testing.type.impl.FakeFile; <ide> <ide> // TODO <ide> @Ignore("For strange reasons this test fails when run by ant") <ide> <ide> String sourceCode = builder.build(); <ide> <del> FakeFile classFile = file(fakeJunitPath.append(path("org/junit/Test.java"))); <del> classFile.createContent(sourceCode); <add> Path path = fakeJunitPath.append(path("org/junit/Test.java")); <add> fileSystem.createFileWithContent(path, sourceCode); <ide> } <ide> <ide> private void createSuccessfulTest() throws IOException { <ide> builder.addLine("}"); <ide> String sourceCode = builder.build(); <ide> <del> FakeFile classFile = file(srcPath.append(path("MyClassTest.java"))); <del> classFile.createContent(sourceCode); <add> Path path = srcPath.append(path("MyClassTest.java")); <add> fileSystem.createFileWithContent(path, sourceCode); <ide> } <ide> <ide> private void createFailingTest() throws IOException { <ide> builder.addLine("}"); <ide> String sourceCode = builder.build(); <ide> <del> FakeFile classFile = file(srcPath.append(path("MyClassFailingTest.java"))); <del> classFile.createContent(sourceCode); <add> Path path = srcPath.append(path("MyClassFailingTest.java")); <add> fileSystem.createFileWithContent(path, sourceCode); <ide> } <ide> }
JavaScript
mit
0b83fce3a415f5a28981aca98d78870c6aa87291
0
derektliu/Picky-Notes,derektliu/Picky-Notes,folksy-squid/Picky-Notes,inspiredtolive/Picky-Notes,derektliu/Picky-Notes,inspiredtolive/Picky-Notes,folksy-squid/Picky-Notes,inspiredtolive/Picky-Notes,folksy-squid/Picky-Notes
/*jshint esversion: 6 */ const createSocketRoom = (hostId, pathUrl, cb) => { // this is if server is localhost var socket = io(); // if server is not localhost, // then set up io to know where the server is socket.emit('create room', pathUrl, hostId); socket.on('create room success', function(){ console.log('successfully created socket room'); cb(null, pathUrl); return socket; }); }; export default (state = {}, action) => { if (action.type === 'CREATE_ROOM') { // ajax call passing in action.data and then setting state in the success $.ajax({ method: 'POST', url: '/api/rooms', contentType: 'application/json', data: JSON.stringify(action.data), success: function(res, status){ console.log('the response: ', res); return { ...state, socket: createSocketRoom(action.data.hostId, res.pathUrl, action.cb), roomInfo: res } }, error: function( res, status ) { console.log(res); } }); } if (action.type === 'JOIN_SOCKET_ROOM'){ var socket = io(); socket.emit('join room', action.pathUrl, action.userId); socket.on('join room error', () => { console.log('we have failed to join a room'); socket.disconnect(); state.socket = null; action.cb('error'); }); socket.on('join room success', () => { console.log('we have successfully joined a room', socket); state.socket = socket; action.cb(null, 'success'); }); } if (action.type === 'LEAVE_SOCKET_ROOM'){ state.socket.disconnect(); state.socket = null; } var createSocketRoom = (hostId, pathUrl) => { var socket = io(); socket.emit('create room', pathUrl, hostId); return socket; }; if (action.type === 'JOIN_SOCKET_ROOM'){ } if (action.type === 'DELETE_SOCKET_ROOM'){ } return state; };
client/src/reducers/roomReducers.js
/*jshint esversion: 6 */ const createSocketRoom = (hostId, pathUrl, cb) => { // this is if server is localhost var socket = io(); // if server is not localhost, // then set up io to know where the server is socket.emit('create room', pathUrl, hostId); socket.on('create room success', function(){ console.log('successfully created socket room'); cb(null, pathUrl); return socket; }); }; export default (state = {}, action) => { if (action.type === 'CREATE_ROOM') { // ajax call passing in action.data and then setting state in the success $.ajax({ method: 'POST', url: '/api/rooms', contentType: 'application/json', data: JSON.stringify(action.data), success: function(res, status){ console.log('the response: ', res); return { ...state, socket: createSocketRoom(action.data.hostId, res.pathUrl, action.cb), roomInfo: res } }, error: function( res, status ) { console.log(res); } }); } if (action.type === 'JOIN_SOCKET_ROOM'){ var socket = io(); socket.emit('join room', action.pathUrl, action.userId); socket.on('join room error', () => { console.log('we have failed to join a room'); socket.disconnect(); state.socket = null; action.cb('error'); }); socket.on('join room success', () => { console.log('we have successfully joined a room', socket); state.socket = socket; action.cb(null, 'success'); }); } if (action.type === 'LEAVE_SOCKET_ROOM'){ state.socket.disconnect(); state.socket = null; } return state; };
Create Socket Room set up
client/src/reducers/roomReducers.js
Create Socket Room set up
<ide><path>lient/src/reducers/roomReducers.js <ide> state.socket = null; <ide> } <ide> <add> var createSocketRoom = (hostId, pathUrl) => { <add> var socket = io(); <add> socket.emit('create room', pathUrl, hostId); <add> return socket; <add> }; <add> <add> if (action.type === 'JOIN_SOCKET_ROOM'){ <add> <add> } <add> <add> if (action.type === 'DELETE_SOCKET_ROOM'){ <add> <add> } <add> <ide> <ide> return state; <ide> };
Java
agpl-3.0
4194df52adf579f969b2c6a324a65ad10f2361e6
0
clintonhealthaccess/lmis-moz-mobile,clintonhealthaccess/lmis-moz-mobile,clintonhealthaccess/lmis-moz-mobile,clintonhealthaccess/lmis-moz-mobile
/* * This program is part of the OpenLMIS logistics management information * system platform software. * * Copyright © 2015 ThoughtWorks, Inc. * * 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. For additional * information contact [email protected] */ package org.openlmis.core.view.widget; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.text.Editable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewStub; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import org.openlmis.core.LMISApp; import org.openlmis.core.R; import org.openlmis.core.model.Regimen; import org.openlmis.core.model.RegimenItem; import org.openlmis.core.model.RnRForm; import org.openlmis.core.presenter.MMIARequisitionPresenter; import org.openlmis.core.utils.ToastUtil; import org.openlmis.core.view.activity.BaseActivity; import org.openlmis.core.view.activity.SelectProductsActivity; import org.openlmis.core.view.fragment.MMIARequisitionFragment; import org.openlmis.core.view.fragment.SimpleDialogFragment; import java.util.ArrayList; import java.util.List; import rx.Subscriber; public class MMIARegimeList extends LinearLayout { private Context context; private TextView totalView; private List<RegimenItem> dataList; private List<EditText> editTexts; private LayoutInflater layoutInflater; private boolean hasDataChanged = false; private ArrayList<RegimenItem> adults; private ArrayList<RegimenItem> paediatrics; protected MMIARequisitionPresenter presenter; private BaseActivity activity; public MMIARegimeList(Context context) { super(context); init(context); } public MMIARegimeList(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { this.context = context; activity = (BaseActivity) getContext(); setOrientation(LinearLayout.VERTICAL); layoutInflater = LayoutInflater.from(context); } public void initView(TextView totalView, MMIARequisitionPresenter presenter) { this.presenter = presenter; this.dataList = presenter.getRnRForm().getRegimenItemListWrapper(); this.editTexts = new ArrayList<>(); initCategoryList(dataList); this.totalView = totalView; addHeaderView(); for (int i = 0; i < adults.size(); i++) { addItemView(adults.get(i), i); } if (LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_custom_regimen)) { if (isCustomEnable()) { addAdultBtnView(); } } for (int i = 0; i < paediatrics.size(); i++) { addItemView(paediatrics.get(i), adults.size() + i); } if (LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_custom_regimen)) { if (isCustomEnable()) { addPaediatricsBtnView(); } } editTexts.get(editTexts.size() - 1).setImeOptions(EditorInfo.IME_ACTION_DONE); totalView.setText(String.valueOf(getTotal())); } private boolean isCustomEnable() { return !presenter.getRnRForm().isAuthorized() && !presenter.getRnRForm().isMissed(); } private void addAdultBtnView() { final TextView view = (TextView) layoutInflater.inflate(R.layout.item_add_custom_regime, this, false); view.setText(R.string.label_add_adult_regime); view.setBackgroundResource(R.color.color_green_light); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getFragment().startActivityForResult(SelectProductsActivity.getIntentToMe(view.getContext(), Regimen.RegimeType.Adults), MMIARequisitionFragment.REQUEST_FOR_CUSTOM_REGIME); } }); addView(view); } private void addPaediatricsBtnView() { final TextView view = (TextView) layoutInflater.inflate(R.layout.item_add_custom_regime, this, false); view.setText(R.string.label_add_child_regime); view.setBackgroundResource(R.color.color_regime_baby); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getFragment().startActivityForResult(SelectProductsActivity.getIntentToMe(view.getContext(), Regimen.RegimeType.Paediatrics), MMIARequisitionFragment.REQUEST_FOR_CUSTOM_REGIME); } }); addView(view); } private Fragment getFragment() { return ((Activity) getContext()).getFragmentManager().findFragmentById(R.id.fragment_requisition); } private void initCategoryList(List<RegimenItem> regimenItems) { adults = new ArrayList<>(); paediatrics = new ArrayList<>(); for (RegimenItem item : regimenItems) { if (item == null) { continue; } if (Regimen.RegimeType.Paediatrics.equals(item.getRegimen().getType())) { paediatrics.add(item); } else { adults.add(item); } } } public List<RegimenItem> getDataList() { return dataList; } private void addHeaderView() { addItemView(null, true, 0); } private void addItemView(final RegimenItem item, int position) { addItemView(item, false, position); } private void addItemView(final RegimenItem item, boolean isHeaderView, final int position) { View view = layoutInflater.inflate(R.layout.item_regime, this, false); TextView tvName = (TextView) view.findViewById(R.id.tv_name); EditText etTotal = (EditText) view.findViewById(R.id.et_total); if (isHeaderView) { tvName.setGravity(Gravity.CENTER); etTotal.setEnabled(false); view.setBackgroundResource(R.color.color_mmia_speed_list_header); tvName.setText(R.string.label_regime_header_name); etTotal.setText(getResources().getString(R.string.label_total_mmia).toUpperCase()); } else { editTexts.add(etTotal); Regimen regimen = item.getRegimen(); tvName.setText(regimen.getName()); if (item.getAmount() != null) { etTotal.setText(String.valueOf(item.getAmount())); } setBackground(view, regimen); etTotal.addTextChangedListener(new EditTextWatcher(item)); etTotal.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_NEXT) { if ((position + 1) < editTexts.size()) { editTexts.get(position + 1).requestFocus(); return true; } } return false; } }); setDelIconForCustomRegime(item, view); } addView(view); } private void setBackground(View view, Regimen regimen) { if (Regimen.RegimeType.Paediatrics.equals(regimen.getType())) { view.setBackgroundResource(R.color.color_regime_baby); } else { view.setBackgroundResource(R.color.color_green_light); } } private void setDelIconForCustomRegime(final RegimenItem item, View view) { if (item.getRegimen().isCustom() && isCustomEnable()) { View ivDel = ((ViewStub) view.findViewById(R.id.vs_del)).inflate(); ivDel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDelConfirmDialog(item); } }); } } protected void showDelConfirmDialog(final RegimenItem item) { SimpleDialogFragment dialogFragment = SimpleDialogFragment.newInstance( LMISApp.getContext().getString(R.string.msg_regime_del_confirm)); dialogFragment.show(((Activity) getContext()).getFragmentManager(), "del_confirm_dialog"); dialogFragment.setCallBackListener(new SimpleDialogFragment.MsgDialogCallBack() { @Override public void positiveClick(String tag) { activity.loading(); presenter.deleteRegimeItem(item).subscribe(new Subscriber<Void>() { @Override public void onCompleted() { refreshRegimeView(); activity.loaded(); } @Override public void onError(Throwable e) { activity.loaded(); ToastUtil.show(e.getMessage()); } @Override public void onNext(Void aVoid) { } }); } @Override public void negativeClick(String tag) { } }); } public boolean hasDataChanged() { return hasDataChanged; } public void highLightTotal() { totalView.setBackground(getResources().getDrawable(R.drawable.border_bg_red)); } public void deHighLightTotal() { totalView.setBackground(getResources().getDrawable(R.color.color_page_gray)); } public boolean hasEmptyField() { for (RegimenItem item : dataList) { if (null == item.getAmount()) { return true; } } return false; } public void refreshRegimeView() { removeAllViews(); initView(totalView, presenter); } public void addCustomRegimenItem(Regimen regimen) { if (presenter.isRegimeItemExists(regimen)) { ToastUtil.show(R.string.msg_regime_already_exist); return; } activity.loading(); presenter.addCustomRegimenItem(regimen).subscribe(customRegimenItemSubscriber()); } private Subscriber<Void> customRegimenItemSubscriber() { return new Subscriber<Void>() { @Override public void onCompleted() { refreshRegimeView(); activity.loaded(); } @Override public void onError(Throwable e) { activity.loaded(); ToastUtil.show(e.getMessage()); } @Override public void onNext(Void data) { } }; } class EditTextWatcher implements android.text.TextWatcher { private final RegimenItem item; public EditTextWatcher(RegimenItem item) { this.item = item; } @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { hasDataChanged = true; try { item.setAmount(Long.parseLong(editable.toString())); } catch (NumberFormatException e) { item.setAmount(null); } totalView.setText(String.valueOf(getTotal())); } } public boolean isCompleted() { for (EditText editText : editTexts) { if (TextUtils.isEmpty(editText.getText().toString())) { editText.setError(context.getString(R.string.hint_error_input)); editText.requestFocus(); return false; } } return true; } public long getTotal() { return RnRForm.calculateTotalRegimenAmount(dataList); } }
app/src/main/java/org/openlmis/core/view/widget/MMIARegimeList.java
/* * This program is part of the OpenLMIS logistics management information * system platform software. * * Copyright © 2015 ThoughtWorks, Inc. * * 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. For additional * information contact [email protected] */ package org.openlmis.core.view.widget; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.text.Editable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewStub; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import org.openlmis.core.LMISApp; import org.openlmis.core.R; import org.openlmis.core.model.Regimen; import org.openlmis.core.model.RegimenItem; import org.openlmis.core.model.RnRForm; import org.openlmis.core.presenter.MMIARequisitionPresenter; import org.openlmis.core.utils.ToastUtil; import org.openlmis.core.view.activity.BaseActivity; import org.openlmis.core.view.activity.SelectProductsActivity; import org.openlmis.core.view.fragment.MMIARequisitionFragment; import org.openlmis.core.view.fragment.SimpleDialogFragment; import java.util.ArrayList; import java.util.List; import rx.Subscriber; public class MMIARegimeList extends LinearLayout { private Context context; private TextView totalView; private List<RegimenItem> dataList; private List<EditText> editTexts = new ArrayList<>(); private LayoutInflater layoutInflater; private boolean hasDataChanged = false; private ArrayList<RegimenItem> adults; private ArrayList<RegimenItem> paediatrics; protected MMIARequisitionPresenter presenter; private BaseActivity activity; public MMIARegimeList(Context context) { super(context); init(context); } public MMIARegimeList(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { this.context = context; activity = (BaseActivity) getContext(); setOrientation(LinearLayout.VERTICAL); layoutInflater = LayoutInflater.from(context); } public void initView(TextView totalView, MMIARequisitionPresenter presenter) { this.presenter = presenter; this.dataList = presenter.getRnRForm().getRegimenItemListWrapper(); initCategoryList(dataList); this.totalView = totalView; addHeaderView(); for (int i = 0; i < adults.size(); i++) { addItemView(adults.get(i), i); } if (LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_custom_regimen)) { if (isCustomEnable()) { addAdultBtnView(); } } for (int i = 0; i < paediatrics.size(); i++) { addItemView(paediatrics.get(i), adults.size() + i); } if (LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_custom_regimen)) { if (isCustomEnable()) { addPaediatricsBtnView(); } } editTexts.get(editTexts.size() - 1).setImeOptions(EditorInfo.IME_ACTION_DONE); totalView.setText(String.valueOf(getTotal())); } private boolean isCustomEnable() { return !presenter.getRnRForm().isAuthorized() && !presenter.getRnRForm().isMissed(); } private void addAdultBtnView() { final TextView view = (TextView) layoutInflater.inflate(R.layout.item_add_custom_regime, this, false); view.setText(R.string.label_add_adult_regime); view.setBackgroundResource(R.color.color_green_light); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getFragment().startActivityForResult(SelectProductsActivity.getIntentToMe(view.getContext(), Regimen.RegimeType.Adults), MMIARequisitionFragment.REQUEST_FOR_CUSTOM_REGIME); } }); addView(view); } private void addPaediatricsBtnView() { final TextView view = (TextView) layoutInflater.inflate(R.layout.item_add_custom_regime, this, false); view.setText(R.string.label_add_child_regime); view.setBackgroundResource(R.color.color_regime_baby); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getFragment().startActivityForResult(SelectProductsActivity.getIntentToMe(view.getContext(), Regimen.RegimeType.Paediatrics), MMIARequisitionFragment.REQUEST_FOR_CUSTOM_REGIME); } }); addView(view); } private Fragment getFragment() { return ((Activity) getContext()).getFragmentManager().findFragmentById(R.id.fragment_requisition); } private void initCategoryList(List<RegimenItem> regimenItems) { adults = new ArrayList<>(); paediatrics = new ArrayList<>(); for (RegimenItem item : regimenItems) { if (item == null) { continue; } if (Regimen.RegimeType.Paediatrics.equals(item.getRegimen().getType())) { paediatrics.add(item); } else { adults.add(item); } } } public List<RegimenItem> getDataList() { return dataList; } private void addHeaderView() { addItemView(null, true, 0); } private void addItemView(final RegimenItem item, int position) { addItemView(item, false, position); } private void addItemView(final RegimenItem item, boolean isHeaderView, final int position) { View view = layoutInflater.inflate(R.layout.item_regime, this, false); TextView tvName = (TextView) view.findViewById(R.id.tv_name); EditText etTotal = (EditText) view.findViewById(R.id.et_total); if (isHeaderView) { tvName.setGravity(Gravity.CENTER); etTotal.setEnabled(false); view.setBackgroundResource(R.color.color_mmia_speed_list_header); tvName.setText(R.string.label_regime_header_name); etTotal.setText(getResources().getString(R.string.label_total_mmia).toUpperCase()); } else { editTexts.add(etTotal); Regimen regimen = item.getRegimen(); tvName.setText(regimen.getName()); if (item.getAmount() != null) { etTotal.setText(String.valueOf(item.getAmount())); } setBackground(view, regimen); etTotal.addTextChangedListener(new EditTextWatcher(item)); etTotal.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_NEXT) { if ((position + 1) < editTexts.size()) { editTexts.get(position + 1).requestFocus(); return true; } } return false; } }); setDelIconForCustomRegime(item, view); } addView(view); } private void setBackground(View view, Regimen regimen) { if (Regimen.RegimeType.Paediatrics.equals(regimen.getType())) { view.setBackgroundResource(R.color.color_regime_baby); } else { view.setBackgroundResource(R.color.color_green_light); } } private void setDelIconForCustomRegime(final RegimenItem item, View view) { if (item.getRegimen().isCustom() && isCustomEnable()) { View ivDel = ((ViewStub) view.findViewById(R.id.vs_del)).inflate(); ivDel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDelConfirmDialog(item); } }); } } protected void showDelConfirmDialog(final RegimenItem item) { SimpleDialogFragment dialogFragment = SimpleDialogFragment.newInstance( LMISApp.getContext().getString(R.string.msg_regime_del_confirm)); dialogFragment.show(((Activity) getContext()).getFragmentManager(), "del_confirm_dialog"); dialogFragment.setCallBackListener(new SimpleDialogFragment.MsgDialogCallBack() { @Override public void positiveClick(String tag) { activity.loading(); presenter.deleteRegimeItem(item).subscribe(new Subscriber<Void>() { @Override public void onCompleted() { refreshRegimeView(); activity.loaded(); } @Override public void onError(Throwable e) { activity.loaded(); ToastUtil.show(e.getMessage()); } @Override public void onNext(Void aVoid) { } }); } @Override public void negativeClick(String tag) { } }); } public boolean hasDataChanged() { return hasDataChanged; } public void highLightTotal() { totalView.setBackground(getResources().getDrawable(R.drawable.border_bg_red)); } public void deHighLightTotal() { totalView.setBackground(getResources().getDrawable(R.color.color_page_gray)); } public boolean hasEmptyField() { for (RegimenItem item : dataList) { if (null == item.getAmount()) { return true; } } return false; } public void refreshRegimeView() { removeAllViews(); initView(totalView, presenter); } public void addCustomRegimenItem(Regimen regimen) { if (presenter.isRegimeItemExists(regimen)) { ToastUtil.show(R.string.msg_regime_already_exist); return; } activity.loading(); presenter.addCustomRegimenItem(regimen).subscribe(customRegimenItemSubscriber()); } private Subscriber<Void> customRegimenItemSubscriber() { return new Subscriber<Void>() { @Override public void onCompleted() { refreshRegimeView(); activity.loaded(); } @Override public void onError(Throwable e) { activity.loaded(); ToastUtil.show(e.getMessage()); } @Override public void onNext(Void data) { } }; } class EditTextWatcher implements android.text.TextWatcher { private final RegimenItem item; public EditTextWatcher(RegimenItem item) { this.item = item; } @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { hasDataChanged = true; try { item.setAmount(Long.parseLong(editable.toString())); } catch (NumberFormatException e) { item.setAmount(null); } totalView.setText(String.valueOf(getTotal())); } } public boolean isCompleted() { for (EditText editText : editTexts) { if (TextUtils.isEmpty(editText.getText().toString())) { editText.setError(context.getString(R.string.hint_error_input)); editText.requestFocus(); return false; } } return true; } public long getTotal() { return RnRForm.calculateTotalRegimenAmount(dataList); } }
ZS - #219- fix bug when refresh view need refresh edittext list
app/src/main/java/org/openlmis/core/view/widget/MMIARegimeList.java
ZS - #219- fix bug when refresh view need refresh edittext list
<ide><path>pp/src/main/java/org/openlmis/core/view/widget/MMIARegimeList.java <ide> private Context context; <ide> private TextView totalView; <ide> private List<RegimenItem> dataList; <del> private List<EditText> editTexts = new ArrayList<>(); <add> private List<EditText> editTexts; <ide> private LayoutInflater layoutInflater; <ide> private boolean hasDataChanged = false; <ide> private ArrayList<RegimenItem> adults; <ide> public void initView(TextView totalView, MMIARequisitionPresenter presenter) { <ide> this.presenter = presenter; <ide> this.dataList = presenter.getRnRForm().getRegimenItemListWrapper(); <add> this.editTexts = new ArrayList<>(); <ide> initCategoryList(dataList); <ide> this.totalView = totalView; <ide> addHeaderView();
Java
apache-2.0
0e79093b651cbc7c11124702f20c5dff7a467992
0
google/startup-os,google/startup-os,google/startup-os,google/startup-os,google/startup-os,google/startup-os
/* * Copyright 2018 The StartupOS Authors. * * 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 * * https://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. */ package com.google.startupos.common.flags; import javax.annotation.Nonnull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Flag class, with implementations for various flag types. */ // TODO: Add support for lists public abstract class Flag<T> { private static final Logger log = LoggerFactory.getLogger(GflagsParser.class); public static Flag<String> create(String defaultValue) { return new Flag.StringFlag(defaultValue); } public static Flag<Boolean> create(Boolean defaultValue) { return new Flag.BooleanFlag(defaultValue); } public static Flag<Integer> create(Integer defaultValue) { return new Flag.IntegerFlag(defaultValue); } public static Flag<Long> create(Long defaultValue) { return new Flag.LongFlag(defaultValue); } public static Flag<Double> create(Double defaultValue) { return new Flag.DoubleFlag(defaultValue); } private static class StringFlag extends Flag<String> { StringFlag(@Nonnull String defaultValue) { super(defaultValue); } @Override String parse(@Nonnull String value) { return String.valueOf(value); } } private static class BooleanFlag extends Flag<Boolean> { BooleanFlag(@Nonnull Boolean defaultValue) { super(defaultValue); } @Override Boolean parse(@Nonnull String value) { return Boolean.valueOf(value); } } private static class IntegerFlag extends Flag<Integer> { IntegerFlag(@Nonnull Integer defaultValue) { super(defaultValue); } @Override Integer parse(@Nonnull String value) { return Integer.valueOf(value); } } private static class LongFlag extends Flag<Long> { LongFlag(@Nonnull Long defaultValue) { super(defaultValue); } @Override Long parse(@Nonnull String value) { return Long.valueOf(value); } } private static class DoubleFlag extends Flag<Double> { DoubleFlag(@Nonnull Double defaultValue) { super(defaultValue); } @Override Double parse(@Nonnull String value) { return Double.valueOf(value); } } protected T defaultValue; protected T value; protected String name; protected boolean required; public Flag(T defaultValue) { this.defaultValue = defaultValue; } abstract T parse(@Nonnull String value); // This accessor is only used to get the initial default value, which is then // stored in Flags. T getDefault() { return defaultValue; } void setName(String name) { this.name = name; } void setRequired(boolean required) { this.required = required; } public T get() { T prevValue = value; if (Flags.getFlagValue(name) != null) { value = parse(Flags.getFlagValue(name)); } else { value = parse(Flags.getDefaultFlagValue(name)); } Flags.setFlagValue(name, value.toString()); if (prevValue != null && !prevValue.equals(value)) { log.error( String.format( "Flag value has changed between get() calls. " + "Previous value is %s and current is %s", prevValue, value)); } if (required && value.equals(Flags.getDefaultFlagValue(name))) { throw new IllegalArgumentException( String.format("Argument '%s' is required but was not supplied", name)); } return value; } }
common/flags/Flag.java
/* * Copyright 2018 The StartupOS Authors. * * 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 * * https://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. */ package com.google.startupos.common.flags; import javax.annotation.Nonnull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Flag class, with implementations for various flag types. */ // TODO: Add support for lists public abstract class Flag<T> { private static final Logger log = LoggerFactory.getLogger(GflagsParser.class); public static Flag<String> create(String defaultValue) { return new Flag.StringFlag(defaultValue); } public static Flag<Boolean> create(Boolean defaultValue) { return new Flag.BooleanFlag(defaultValue); } public static Flag<Integer> create(Integer defaultValue) { return new Flag.IntegerFlag(defaultValue); } public static Flag<Long> create(Long defaultValue) { return new Flag.LongFlag(defaultValue); } public static Flag<Double> create(Double defaultValue) { return new Flag.DoubleFlag(defaultValue); } private static class StringFlag extends Flag<String> { StringFlag(@Nonnull String defaultValue) { super(defaultValue); } @Override String parse(@Nonnull String value) { return String.valueOf(value); } } private static class BooleanFlag extends Flag<Boolean> { BooleanFlag(@Nonnull Boolean defaultValue) { super(defaultValue); } @Override Boolean parse(@Nonnull String value) { return Boolean.valueOf(value); } } private static class IntegerFlag extends Flag<Integer> { IntegerFlag(@Nonnull Integer defaultValue) { super(defaultValue); } @Override Integer parse(@Nonnull String value) { return Integer.valueOf(value); } } private static class LongFlag extends Flag<Long> { LongFlag(@Nonnull Long defaultValue) { super(defaultValue); } @Override Long parse(@Nonnull String value) { return Long.valueOf(value); } } private static class DoubleFlag extends Flag<Double> { DoubleFlag(@Nonnull Double defaultValue) { super(defaultValue); } @Override Double parse(@Nonnull String value) { return Double.valueOf(value); } } protected T defaultValue; protected T value; protected String name; protected boolean required; public Flag(T defaultValue) { this.defaultValue = defaultValue; } abstract T parse(@Nonnull String value); // This accessor is only used to get the initial default value, which is then // stored in Flags. T getDefault() { return defaultValue; } void setName(String name) { this.name = name; } void setRequired(boolean required) { this.required = required; } public T get() { T prevValue = value; if (Flags.getFlagValue(name) != null) { value = parse(Flags.getFlagValue(name)); } else { value = parse(Flags.getDefaultFlagValue(name)); } Flags.setFlagValue(name, value.toString()); if (prevValue != null && !prevValue.equals(value)) { log.error( String.format( "Flag value has changed between get() calls. " + "Previous value is %s and current is %s", prevValue, value)); } if (required && value.equals(Flags.getDefaultFlagValue(name))) { throw new IllegalArgumentException("Argument is required but was not supplied"); } return value; } }
Specify which flag was not supplied
common/flags/Flag.java
Specify which flag was not supplied
<ide><path>ommon/flags/Flag.java <ide> prevValue, value)); <ide> } <ide> if (required && value.equals(Flags.getDefaultFlagValue(name))) { <del> throw new IllegalArgumentException("Argument is required but was not supplied"); <add> throw new IllegalArgumentException( <add> String.format("Argument '%s' is required but was not supplied", name)); <ide> } <ide> return value; <ide> }
Java
apache-2.0
ba431d8ad472a7bd62cb707bb4b8eb9e417fea13
0
masbog/ios-driver,crashlytics/ios-driver,adataylor/ios-driver,seem-sky/ios-driver,adataylor/ios-driver,ios-driver/ios-driver,crashlytics/ios-driver,darraghgrace/ios-driver,shutkou/ios-driver,adataylor/ios-driver,azaytsev/ios-driver,shutkou/ios-driver,crashlytics/ios-driver,azaytsev/ios-driver,darraghgrace/ios-driver,azaytsev/ios-driver,seem-sky/ios-driver,masbog/ios-driver,seem-sky/ios-driver,azaytsev/ios-driver,shutkou/ios-driver,masbog/ios-driver,adataylor/ios-driver,shutkou/ios-driver,ios-driver/ios-driver,seem-sky/ios-driver,shutkou/ios-driver,crashlytics/ios-driver,darraghgrace/ios-driver,masbog/ios-driver,ios-driver/ios-driver,darraghgrace/ios-driver,adataylor/ios-driver,crashlytics/ios-driver,shutkou/ios-driver,azaytsev/ios-driver,ios-driver/ios-driver,darraghgrace/ios-driver,masbog/ios-driver,ios-driver/ios-driver
/* * Copyright 2012 ios-driver committers. * * 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. */ package org.uiautomation.ios.client.uiamodels.impl; import org.json.JSONException; import org.json.JSONObject; import org.uiautomation.ios.UIAModels.UIAElement; import org.uiautomation.ios.UIAModels.UIAElementArray; import org.uiautomation.ios.UIAModels.UIAPoint; import org.uiautomation.ios.UIAModels.UIARect; import org.uiautomation.ios.UIAModels.predicate.AndCriteria; import org.uiautomation.ios.UIAModels.predicate.Criteria; import org.uiautomation.ios.UIAModels.predicate.TypeCriteria; import org.uiautomation.ios.communication.WebDriverLikeCommand; import org.uiautomation.ios.exceptions.IOSAutomationException; import org.uiautomation.ios.exceptions.NoSuchElementException; import org.uiautomation.ios.exceptions.StaleReferenceException; /** * Main object for all the UIAutomation stuff. Implement part of the Apple API. Some methods are not * implemented as the findElement(s) are covering multiple cases. * * {@link <a href="http://developer.apple.com/library/ios/#documentation/ToolsLanguages/Reference/UIAElementClassReference/UIAElement/UIAElement.html"> Apple doc</a> * for UIAElement } */ public class RemoteUIAElement extends RemoteObject implements UIAElement { public RemoteUIAElement(RemoteUIADriver driver, String reference) { super(driver, reference); } @Override public String getLabel() { return getObject(WebDriverLikeCommand.LABEL); } @Override public String getName() { return getObject(WebDriverLikeCommand.NAME); } @Override public String getValue() { return getObject(WebDriverLikeCommand.VALUE); } @Override public <T> T findElement(Class<T> type, Criteria c) throws NoSuchElementException { Criteria newOne = new AndCriteria(new TypeCriteria(type), c); return (T) findElement(newOne); } @Override public UIAElement findElement(Criteria c) throws NoSuchElementException { try { JSONObject payload = new JSONObject(); payload.put("depth", -1); payload.put("criteria", c.getJSONRepresentation()); return (UIAElement) getRemoteObject(WebDriverLikeCommand.ELEMENT, payload); } catch (JSONException e) { throw new IOSAutomationException(e); } } @Override @SuppressWarnings("unchecked") public UIAElementArray<UIAElement> findElements(Criteria c) { try { JSONObject payload = new JSONObject(); payload.put("depth", -1); payload.put("criteria", c.getJSONRepresentation()); return (UIAElementArray<UIAElement>) getRemoteObject(WebDriverLikeCommand.ELEMENTS, payload); } catch (JSONException e) { throw new IOSAutomationException(e); } } @Override public UIAElementArray<UIAElement> getAncestry() { // TODO Auto-generated method stub return null; } @Override public void tap() { execute(WebDriverLikeCommand.TAP); } @Override public void touchAndHold(int duration) { try { JSONObject payload = new JSONObject(); payload.put("duration", duration); execute(WebDriverLikeCommand.TOUCH_AND_HOLD, payload); } catch (JSONException e) { e.printStackTrace(); } } @Override public void doubleTap() { // TODO Auto-generated method stub } @Override public void twoFingerTap() { // TODO Auto-generated method stub } @Override public void scrollToVisible() { // TODO Auto-generated method stub } @Override public JSONObject logElementTree() throws Exception { return getObject(WebDriverLikeCommand.TREE); } // TODO freynaud fix that server side. @Override public boolean isVisible() { Integer i = getObject(WebDriverLikeCommand.IS_VISIBLE); if (i == 1) { return true; } else { return false; } } @Override public boolean isValid() { try { Boolean stale = getObject(WebDriverLikeCommand.IS_STALE); return !stale; } catch (StaleReferenceException e) { return false; } } @Override public UIAPoint getHitPoint() { // TODO Auto-generated method stub return null; } @Override public UIARect getRect() { return getUIARect(WebDriverLikeCommand.RECT); } @Override public UIAElement getParent() { // TODO Auto-generated method stub return null; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getClass().getSimpleName()); builder.append("int. key:" + getReference()); builder.append(",name:" + getName()); builder.append(",value:" + getValue()); builder.append(",label:" + getLabel()); return builder.toString(); } }
client/src/main/java/org/uiautomation/ios/client/uiamodels/impl/RemoteUIAElement.java
/* * Copyright 2012 ios-driver committers. * * 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. */ package org.uiautomation.ios.client.uiamodels.impl; import org.json.JSONException; import org.json.JSONObject; import org.uiautomation.ios.UIAModels.UIAElement; import org.uiautomation.ios.UIAModels.UIAElementArray; import org.uiautomation.ios.UIAModels.UIAPoint; import org.uiautomation.ios.UIAModels.UIARect; import org.uiautomation.ios.UIAModels.predicate.AndCriteria; import org.uiautomation.ios.UIAModels.predicate.Criteria; import org.uiautomation.ios.UIAModels.predicate.TypeCriteria; import org.uiautomation.ios.communication.WebDriverLikeCommand; import org.uiautomation.ios.exceptions.IOSAutomationException; import org.uiautomation.ios.exceptions.NoSuchElementException; import org.uiautomation.ios.exceptions.StaleReferenceException; /** * Main object for all the UIAutomation stuff. Implement part of the Apple API. Some methods are not * implemented as the findElement(s) are covering multiple cases. * * {@link <a href="http://developer.apple.com/library/ios/#documentation/ToolsLanguages/Reference/UIAElementClassReference/UIAElement/UIAElement.html"> Apple doc</a> * for UIAElement } */ public class RemoteUIAElement extends RemoteObject implements UIAElement { public RemoteUIAElement(RemoteUIADriver driver, String reference) { super(driver, reference); } @Override public String getLabel() { return getObject(WebDriverLikeCommand.LABEL); } @Override public String getName() { return getObject(WebDriverLikeCommand.NAME); } @Override public String getValue() { return getObject(WebDriverLikeCommand.VALUE); } // TODO freynaud private final long timeout = 30000; @Override public <T> T findElement(Class<T> type, Criteria c) throws NoSuchElementException { Criteria newOne = new AndCriteria(new TypeCriteria(type), c); return (T) findElement(newOne); } @Override public UIAElement findElement(Criteria c) throws NoSuchElementException { long deadline = System.currentTimeMillis() + timeout; while (System.currentTimeMillis() < deadline) { try { JSONObject payload = new JSONObject(); payload.put("depth", -1); payload.put("criteria", c.getJSONRepresentation()); return (UIAElement) getRemoteObject(WebDriverLikeCommand.ELEMENT, payload); } catch (JSONException e) { throw new IOSAutomationException(e); } catch (NoSuchElementException ignore) {} } try { throw new NoSuchElementException("timeout after " + timeout + " trying to find " + c.getJSONRepresentation().toString()); } catch (JSONException e) { throw new IOSAutomationException(e); } } @Override @SuppressWarnings("unchecked") public UIAElementArray<UIAElement> findElements(Criteria c) { try { JSONObject payload = new JSONObject(); payload.put("depth", -1); payload.put("criteria", c.getJSONRepresentation()); return (UIAElementArray<UIAElement>) getRemoteObject(WebDriverLikeCommand.ELEMENTS, payload); } catch (JSONException e) { throw new IOSAutomationException(e); } } @Override public UIAElementArray<UIAElement> getAncestry() { // TODO Auto-generated method stub return null; } @Override public void tap() { execute(WebDriverLikeCommand.TAP); } @Override public void touchAndHold(int duration) { try { JSONObject payload = new JSONObject(); payload.put("duration", duration); execute(WebDriverLikeCommand.TOUCH_AND_HOLD, payload); } catch (JSONException e) { e.printStackTrace(); } } @Override public void doubleTap() { // TODO Auto-generated method stub } @Override public void twoFingerTap() { // TODO Auto-generated method stub } @Override public void scrollToVisible() { // TODO Auto-generated method stub } @Override public JSONObject logElementTree() throws Exception { return getObject(WebDriverLikeCommand.TREE); } // TODO freynaud fix that server side. @Override public boolean isVisible() { Integer i = getObject(WebDriverLikeCommand.IS_VISIBLE); if (i == 1) { return true; } else { return false; } } @Override public boolean isValid() { try { Boolean stale = getObject(WebDriverLikeCommand.IS_STALE); return !stale; } catch (StaleReferenceException e) { return false; } } @Override public UIAPoint getHitPoint() { // TODO Auto-generated method stub return null; } @Override public UIARect getRect() { return getUIARect(WebDriverLikeCommand.RECT); } @Override public UIAElement getParent() { // TODO Auto-generated method stub return null; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getClass().getSimpleName()); builder.append("int. key:" + getReference()); builder.append(",name:" + getName()); builder.append(",value:" + getValue()); builder.append(",label:" + getLabel()); return builder.toString(); } }
removing the client side timeout handling
client/src/main/java/org/uiautomation/ios/client/uiamodels/impl/RemoteUIAElement.java
removing the client side timeout handling
<ide><path>lient/src/main/java/org/uiautomation/ios/client/uiamodels/impl/RemoteUIAElement.java <ide> return getObject(WebDriverLikeCommand.VALUE); <ide> } <ide> <del> // TODO freynaud <del> private final long timeout = 30000; <ide> <ide> @Override <ide> public <T> T findElement(Class<T> type, Criteria c) throws NoSuchElementException { <ide> <ide> @Override <ide> public UIAElement findElement(Criteria c) throws NoSuchElementException { <del> long deadline = System.currentTimeMillis() + timeout; <del> <del> while (System.currentTimeMillis() < deadline) { <del> try { <del> JSONObject payload = new JSONObject(); <del> payload.put("depth", -1); <del> payload.put("criteria", c.getJSONRepresentation()); <del> return (UIAElement) getRemoteObject(WebDriverLikeCommand.ELEMENT, payload); <del> } catch (JSONException e) { <del> throw new IOSAutomationException(e); <del> } catch (NoSuchElementException ignore) {} <del> } <ide> try { <del> throw new NoSuchElementException("timeout after " + timeout + " trying to find " <del> + c.getJSONRepresentation().toString()); <add> JSONObject payload = new JSONObject(); <add> payload.put("depth", -1); <add> payload.put("criteria", c.getJSONRepresentation()); <add> return (UIAElement) getRemoteObject(WebDriverLikeCommand.ELEMENT, payload); <ide> } catch (JSONException e) { <ide> throw new IOSAutomationException(e); <ide> } <add> <ide> } <ide> <ide> @Override
Java
mit
05a2f34613aac5cebdde02f31d614549acdb2788
0
ihongs/HongsCORE.new,ihongs/HongsCORE.new,ihongs/HongsCORE.new,ihongs/HongsCORE.new,ihongs/HongsCORE.new
package io.github.ihongs.serv.matrix; import io.github.ihongs.Cnst; import io.github.ihongs.Core; import io.github.ihongs.HongsException; import io.github.ihongs.action.ActionHelper; import io.github.ihongs.action.FormSet; import io.github.ihongs.action.NaviMap; import io.github.ihongs.db.DB; import io.github.ihongs.db.Model; import io.github.ihongs.db.Table; import io.github.ihongs.db.util.FetchCase; import io.github.ihongs.util.Data; import io.github.ihongs.util.Dict; import io.github.ihongs.util.Synt; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.LinkedHashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Iterator; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * 表单模型 * @author Hongs */ public class Form extends Model { protected String centra = "centra/data"; protected String centre = "centre/data"; protected String upload = "static/upload/data"; public Form() throws HongsException { this(DB.getInstance("matrix").getTable("form")); } public Form(Table table) throws HongsException { super(table); } @Override public int put(String id, Map rd) throws HongsException { String stat = Synt.asString(rd.get("state")); String name = Synt.asString(rd.get("name" )); String stax = get(id, "state"); String namx = get(id, "name" ); List conf = parseConf(rd); // 冻结意味着手动修改了配置 // 再操作可能会冲掉自定配置 if (stat == null) { if ("3".equals(stax)) { throw new HongsException(0x1100, "表单冻结, 禁止操作"); } if ("0".equals(stax)) { throw new HongsException(0x1104, "表单缺失, 无法操作"); } } int n = superPut(id, rd); if (n != 0) { // 用旧数据补全 if (stat == null && name != null) { stat = stax; } if (name == null && stat != null) { name = namx; } // 更新配置文件 if (conf != null || stat != null) { updateFormConf(id, stat,conf); } if (name != null || stat != null) { updateFormMenu(id, stat,name); } if (stat != null) { updateUnitMenu(get(id, "unit_id")); } } return n; } @Override public int add(String id, Map rd) throws HongsException { String ud = Synt.asString(rd.get("unit_id")); String stat = Synt.asString(rd.get("state")); String name = Synt.asString(rd.get("name" )); List conf = parseConf(rd); int n = superAdd(id, rd); if (n != 0) { // 更新配置文件 updateFormConf(id, stat, conf); updateFormMenu(id, stat, name); // 更新单元菜单 updateUnitMenu(ud); // 添加表单权限 insertAuthRole(id); } return n; } @Override public int del(String id, FetchCase fc) throws HongsException { String ud = get(id, "unit_id"); int n = superDel(id, fc); if (n != 0) { // 删除配置文件 deleteFormConf(id); deleteFormMenu(id); // 更新单元菜单 updateUnitMenu(ud); // 删除表单权限 deleteAuthRole(id); } return n; } private String get(String id, String fn) throws HongsException { Object fv = table.fetchCase() .filter("id = ?", id) .select(fn) .getOne( ) .get (fn); return Synt.declare( fv, "" ); } protected final int superAdd(String id, Map rd) throws HongsException { return super.add(id, rd); } protected final int superPut(String id, Map rd) throws HongsException { return super.put(id, rd); } protected final int superDel(String id, FetchCase fc) throws HongsException { return super.del(id, fc); } protected List<Map> parseConf(Map rd) { List<Map> flds = null; String conf = (String) rd.get("conf"); String name = (String) rd.get("name"); if (conf != null && !"".equals(conf)) { flds = Synt.asList(Data.toObject(conf)); Set set = Synt.setOf("name", "word", "cuser", "muser", "ctime", "mtime"); Map tdf = null; Map idf = null; Map fld ; Iterator<Map> itr = flds.iterator(); while (itr.hasNext()) { fld = itr.next(); if ( "-".equals(fld.get("__name__"))) { fld.put("__name__", Core.newIdentity()); } else if ( "@".equals(fld.get("__name__"))) { tdf = fld; itr. remove ( ); } else if ( "id".equals(fld.get("__name__"))) { idf = fld; itr. remove ( ); } else if (set.contains(fld.get("__name__"))) { set. remove (fld.get("__name__")); } } if (tdf != null) { flds.add(0, tdf); // 去掉表单的基础属性 tdf.remove("__type__"); tdf.remove("__rule__"); tdf.remove("__required__"); tdf.remove("__repeated__"); } if (idf != null) { flds.add(1, idf); // 去掉主键的基础属性 idf.remove("__required__"); idf.remove("__repeated__"); } conf = Data.toString(flds); rd.put("conf", conf); // 补全表配置项 fld = Synt.mapOf( "__text__", name, "listable", "?", "sortable", "?", "findable", "?", "nameable", "?" ); if (tdf != null) { fld .putAll(tdf); tdf .putAll(fld); } else { flds.add(0, fld); } // 补全编号字段 fld = Synt.mapOf( "__text__", "ID", "__name__", "id", "__type__", "hidden" ); if (idf != null) { fld .putAll(idf); idf .putAll(fld); } else { flds.add(1, fld); } // 增加名称字段 if (set.contains("name")) { flds.add(Synt.mapOf( "__name__", "name", "__type__", "hidden", "readonly", "true", "lucene-type", "stored" )); } // 增加搜索字段 if (set.contains("word")) { flds.add(Synt.mapOf( "__name__", "word", "__type__", "hidden", "readonly", "true", "unstored", "true", "lucene-type", "search", "lucene-smart-parse", "true" )); } // 增加用户字段 if (set.contains("muser")) { flds.add(Synt.mapOf( "__name__", "muser", "__type__", "hidden", "readonly", "true", "default" , "=$uid", "deforce" , "always" )); } if (set.contains("cuser")) { flds.add(Synt.mapOf( "__name__", "cuser", "__type__", "hidden", "readonly", "true", "default" , "=$uid", "deforce" , "create" )); } // 增加时间字段 if (set.contains("mtime")) { flds.add(Synt.mapOf( "__name__", "mtime", "__type__", "datetime", "type" , "timestamp", "readonly", "true", "default" , "=%now", "deforce" , "always" )); } if (set.contains("ctime")) { flds.add(Synt.mapOf( "__name__", "ctime", "__type__", "datetime", "type" , "timestamp", "readonly", "true", "default" , "=%now", "deforce" , "create" )); } } else { rd.remove("conf"); } return flds; } @Override protected void filter(FetchCase caze, Map rd) throws HongsException { super.filter(caze, rd); // 超级管理员不做限制 ActionHelper helper = Core.getInstance (ActionHelper.class); String uid = ( String ) helper.getSessibute( Cnst.UID_SES ); if (Cnst.ADM_UID.equals(uid)) { return; } String mm = caze.getOption("MODEL_START" , ""); if ("getList".equals(mm) || "getInfo".equals(mm)) { mm = "/search"; } else if ("update" .equals(mm) || "delete" .equals(mm)) { mm = "/" + mm ; } else { return; // 非常规动作不限制 } // 从权限串中取表单ID NaviMap nm = NaviMap.getInstance(centra); String pm = centra + "/"; Set<String> ra = nm.getRoleSet( ); Set<String> rs = new HashSet( ); for (String rn : ra) { if (rn.startsWith(pm) && rn. endsWith(mm)) { rs.add(rn.substring(pm.length(), rn.length() - mm.length())); } } // 限制为有权限的表单 caze.filter("`"+table.name+"`.`id` IN (?)", rs); } protected void insertAuthRole(String id) throws HongsException { ActionHelper helper = Core.getInstance(ActionHelper.class); String uid = (String) helper.getSessibute ( Cnst.UID_SES ); String tan ; // 写入权限 tan = (String) table.getParams().get("role.table"); if (tan != null) { Table tab = db.getTable(tan); tab.insert(Synt.mapOf("user_id", uid, "role" , centra + "/" + id + "/search" )); tab.insert(Synt.mapOf("user_id", uid, "role" , centra + "/" + id + "/create" )); tab.insert(Synt.mapOf("user_id", uid, "role" , centra + "/" + id + "/update" )); tab.insert(Synt.mapOf("user_id", uid, "role" , centra + "/" + id + "/delete" )); tab.insert(Synt.mapOf("user_id", uid, "role" , centra + "/" + id + "/revert" )); } // 更新缓存(通过改变权限更新时间) tan = (String) table.getParams().get("user.table"); if (tan != null) { Table tab = db.getTable(tan); tab.update(Synt.mapOf( "rtime", System.currentTimeMillis() / 1000 ) , "`id` = ?" , uid ); } } protected void deleteAuthRole(String id) throws HongsException { ActionHelper helper = Core.getInstance(ActionHelper.class); String uid = (String) helper.getSessibute ( Cnst.UID_SES ); String tan; // 删除权限 tan = (String) table.getParams().get("role.table"); if (tan != null) { Table tab = db.getTable(tan); tab.remove("`role` IN (?)", Synt.setOf(centra + "/" + id + "/search", centra + "/" + id + "/create", centra + "/" + id + "/update", centra + "/" + id + "/delete", centra + "/" + id + "/revert" )); } // 更新缓存(通过改变权限更新时间) tan = (String) table.getParams().get("user.table"); if (tan != null) { Table tab = db.getTable(tan); tab.update(Synt.mapOf( "rtime", System.currentTimeMillis() / 1000 ) , "`id` = ?" , uid ); } } protected void deleteFormMenu(String id) { File fo; fo = new File(Core.CONF_PATH +"/"+ centra +"/"+ id + Cnst.FORM_EXT +".xml"); if (fo.exists()) fo.delete(); fo = new File(Core.CONF_PATH +"/"+ centre +"/"+ id + Cnst.FORM_EXT +".xml"); if (fo.exists()) fo.delete(); } protected void deleteFormConf(String id) { File fo; fo = new File(Core.CONF_PATH +"/"+ centra +"/"+ id + Cnst.NAVI_EXT +".xml"); if (fo.exists()) fo.delete(); fo = new File(Core.CONF_PATH +"/"+ centre +"/"+ id + Cnst.NAVI_EXT +".xml"); if (fo.exists()) fo.delete(); } protected void updateUnitMenu(String id) throws HongsException { new Unit().updateMenus( ); } protected void updateFormMenu(String id, String stat, String name) throws HongsException { Document docm; Element root, menu, role, actn, depn; docm = makeDocument(); root = docm.createElement("root"); docm.appendChild ( root ); menu = docm.createElement("menu"); root.appendChild ( menu ); menu.setAttribute("text", name ); menu.setAttribute("href", centra+"/"+id+"/"); // 会话 role = docm.createElement("rsname"); root.appendChild ( role ); role.appendChild ( docm.createTextNode("@centra")); // 查看 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", centra+"/"+id+"/search"); role.setAttribute("text", "查看"+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/search" + Cnst.ACT_EXT) ); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/counts/search" + Cnst.ACT_EXT) ); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/statis/search" + Cnst.ACT_EXT) ); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/stream/search" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode("centra") ); // 修改 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", centra+"/"+id+"/update"); role.setAttribute("text", "修改"+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/update" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(centra+"/"+id+"/search") ); // 添加 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", centra+"/"+id+"/create"); role.setAttribute("text", "添加"+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/create" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(centra+"/"+id+"/search") ); // 删除 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", centra+"/"+id+"/delete"); role.setAttribute("text", "删除"+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/delete" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(centra+"/"+id+"/search") ); // 回看 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", centra+"/"+id+"/review"); role.setAttribute("text", "回看"+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/revert/search" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(centra+"/"+id+"/search") ); // 恢复 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", centra+"/"+id+"/revert"); role.setAttribute("text", "恢复"+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/revert/update" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(centra+"/"+id+"/update") ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(centra+"/"+id+"/review") ); saveDocument(Core.CONF_PATH+"/"+centra+"/"+id+Cnst.NAVI_EXT+".xml", docm); //** 对外开放 **/ /** * 仅供内部管理用时, * 应确保无开放配置. */ File fo = new File(Core.CONF_PATH+"/"+centre+"/"+id+Cnst.NAVI_EXT+".xml"); if (!"2".equals(stat)) { if (fo.exists()) { fo.delete(); } return; } docm = makeDocument(); root = docm.createElement("root"); docm.appendChild ( root ); menu = docm.createElement("menu"); root.appendChild ( menu ); menu.setAttribute("text", name ); menu.setAttribute("href", centre+"/"+id+"/"); // 会话 role = docm.createElement("rsname"); root.appendChild ( role ); role.appendChild ( docm.createTextNode("@centre")); // 公共读取权限 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", "public"); // 增删改须登录 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", "centre"); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centre+"/"+id+"/create" + Cnst.ACT_EXT) ); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centre+"/"+id+"/update" + Cnst.ACT_EXT) ); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centre+"/"+id+"/delete" + Cnst.ACT_EXT) ); saveDocument(Core.CONF_PATH+"/"+centre+"/"+id+Cnst.NAVI_EXT+".xml", docm); } protected void updateFormConf(String id, String stat, List<Map> conf) throws HongsException { Document docm; Element root, form, item; docm = makeDocument(); root = docm.createElement("root"); docm.appendChild ( root ); form = docm.createElement("form"); root.appendChild ( form ); form.setAttribute("name" , id ); Map types = FormSet.getInstance().getEnum("__types__"); for (Map fiel: conf) { item = docm.createElement("field"); form.appendChild ( item ); String s, n, t; s = (String) fiel.get("__text__"); if (s != null) item.setAttribute("text", s); n = (String) fiel.get("__name__"); if (n != null) item.setAttribute("name", n); t = (String) fiel.get("__type__"); if (t != null) item.setAttribute("type", t); s = (String) fiel.get("__rule__"); if (s != null && s.length() != 0) item.setAttribute("rule", s); s = (String) fiel.get("__required__"); if (s != null && s.length() != 0) item.setAttribute("required", s); s = (String) fiel.get("__repeated__"); if (s != null && s.length() != 0) item.setAttribute("repeated", s); // 默认不要存放要空字符串 if (!fiel.containsKey("defiant")) { fiel.put("defiant", ""); } // 日期类型要指定存储格式 if ("date".equals(types.get(t) )) { if(!fiel.containsKey("type")) { fiel.put("type", "timestamp"); } } else // 文件类型要指定上传路径 if ("file".equals(types.get(t) )) { if(!fiel.containsKey("href")) { fiel.put("href", upload +"/"+ id); } if(!fiel.containsKey("path")) { fiel.put("path", upload +"/"+ id); } } else // 选项表单要指定配置路径 if ("enum".equals(types.get(t) ) || "form".equals(types.get(t) )) { if(!fiel.containsKey("conf")) { fiel.put("conf", centra +"/"+ id); } } else // 可搜索指定存为搜索类型 if ("search".equals(t) || Synt.declare(fiel.get("srchable"), false)) { if(!fiel.containsKey("lucnene-type")) { fiel.put("lucene-type", "search"); } } else // 文本禁搜索则为存储类型 if ("stored".equals(t) ||"textarea".equals(t) ||"textview".equals(t)) { if(!fiel.containsKey("lucnene-type")) { fiel.put("lucene-type", "stored"); } } Map<String,Map<String,String>> preset = null; List<List<String>> select = null; //** 构建字段参数 **/ for(Object ot : fiel.entrySet( )) { Map.Entry et = (Map.Entry) ot; String k = (String) et.getKey( ); String v = (String) et.getValue(); if (k==null || v==null) { continue; } if (k.startsWith("__")) { continue; } if (k.startsWith( "." ) // 外部预置数据 || k.startsWith( ":")) { // 内部预置数据 if (preset == null) { preset = new LinkedHashMap(); } String l; if (n.equals( "@")) { // 表单预置数据 int p = k.indexOf('.', 1); if (p == -1) continue; l = k.substring(1+ p); k = k.substring(0, p); k = id + k ; } else { // 一般枚举选项 l = k.substring(1 ); k = n; } Dict.put(preset, v, k, l); continue; } if (k.equals("datalist")) { select = Synt.asList(Data.toObject(v) ); continue; } Element para = docm.createElement("param"); item.appendChild ( para ); para.setAttribute("name" , k); para.appendChild ( docm.createTextNode(v) ); } //** 构建枚举列表 **/ if (select != null) { Element anum = docm.createElement("enum" ); root.appendChild ( anum ); anum.setAttribute("name" , n); for(List a : select) { String c = Synt.declare( a.get(0), "" ); String l = Synt.declare( a.get(1), "" ); Element valu = docm.createElement("value"); anum.appendChild ( valu ); valu.setAttribute("code" , c); valu.appendChild ( docm.createTextNode(l) ); } } //** 构建预置数据 **/ if (preset != null) { for(Map.Entry<String,Map<String,String>> et0 : preset.entrySet()) { n = et0.getKey(); Element anum = docm.createElement("enum" ); root.appendChild ( anum ); anum.setAttribute("name" , n); for(Map.Entry<String,String> et1 : et0.getValue().entrySet()) { String c = et1.getKey( ); String l = et1.getValue(); Element valu = docm.createElement("value"); anum.appendChild ( valu ); valu.setAttribute("code" , c); valu.appendChild ( docm.createTextNode(l) ); } } } } saveDocument(Core.CONF_PATH+"/"+centra+"/"+id+Cnst.FORM_EXT+".xml", docm); //** 对外开放 **/ /** * 仅供内部管理用时, * 应确保无公开配置. * 开放存在则不处理, * 固定内容无需更新. */ File fo = new File(Core.CONF_PATH+"/"+centre+"/"+id+Cnst.FORM_EXT+".xml"); if (!"2".equals(stat)) { if (fo.exists()) { fo.delete(); } return; } else { if (fo.exists()) { return; } } docm = makeDocument(); root = docm.createElement("root"); docm.appendChild ( root ); form = docm.createElement("form"); root.appendChild ( form ); form.setAttribute("name" , id ); Element defs, defi; // 全局性保护 defs = docm.createElement("enum"); root.appendChild ( defs ); defs.setAttribute("name", id+":defense"); defi = docm.createElement("value"); defs.appendChild ( defi ); defi.setAttribute("code", Cnst.AR_KEY); defi.appendChild ( docm.createTextNode("(null)")); defi = docm.createElement("value"); defs.appendChild ( defi ); defi.setAttribute("code", Cnst.OR_KEY); defi.appendChild ( docm.createTextNode("(null)")); // 保护写接口 defs = docm.createElement("enum"); root.appendChild ( defs ); defs.setAttribute("name", id+":defence"); defi = docm.createElement("value"); defs.appendChild ( defi ); defi.setAttribute("code", Cnst.AR_KEY+".x.cuser"); defi.appendChild ( docm.createTextNode("($session.uid)")); // 我所创建的 defs = docm.createElement("enum"); root.appendChild ( defs ); defs.setAttribute("name", id+".created"); defi = docm.createElement("value"); defs.appendChild ( defi ); defi.setAttribute("code", Cnst.AR_KEY+".x.cuser"); defi.appendChild ( docm.createTextNode("($session.uid)")); saveDocument(Core.CONF_PATH+"/"+centre+"/"+id+Cnst.FORM_EXT+".xml", docm); } private Document makeDocument() throws HongsException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.newDocument(); } catch (ParserConfigurationException e) { throw new HongsException.Common ( e); } } private void saveDocument(String path, Document docm) throws HongsException { File file = new File(path); File fold = file.getParentFile(); if (!fold.exists()) { fold.mkdirs(); } TransformerFactory tf = TransformerFactory.newInstance(); try { Transformer tr = tf.newTransformer(); DOMSource ds = new DOMSource(docm); StreamResult sr = new StreamResult ( new OutputStreamWriter( new FileOutputStream(file), "utf-8")); tr.setOutputProperty(OutputKeys.ENCODING, "utf-8"); tr.setOutputProperty(OutputKeys.METHOD , "xml" ); tr.setOutputProperty(OutputKeys.INDENT , "yes" ); tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); tr.transform(ds, sr); } catch (TransformerConfigurationException e) { throw new HongsException.Common(e); } catch (IllegalArgumentException e) { throw new HongsException.Common(e); } catch (TransformerException e) { throw new HongsException.Common(e); } catch (FileNotFoundException e) { throw new HongsException.Common(e); } catch (UnsupportedEncodingException e) { throw new HongsException.Common(e); } } }
hongs-serv-matrix/src/main/java/io/github/ihongs/serv/matrix/Form.java
package io.github.ihongs.serv.matrix; import io.github.ihongs.Cnst; import io.github.ihongs.Core; import io.github.ihongs.HongsException; import io.github.ihongs.action.ActionHelper; import io.github.ihongs.action.FormSet; import io.github.ihongs.action.NaviMap; import io.github.ihongs.db.DB; import io.github.ihongs.db.Model; import io.github.ihongs.db.Table; import io.github.ihongs.db.util.FetchCase; import io.github.ihongs.util.Data; import io.github.ihongs.util.Dict; import io.github.ihongs.util.Synt; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.LinkedHashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Iterator; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * 表单模型 * @author Hongs */ public class Form extends Model { protected String centra = "centra/data"; protected String centre = "centre/data"; protected String upload = "static/upload/data"; public Form() throws HongsException { this(DB.getInstance("matrix").getTable("form")); } public Form(Table table) throws HongsException { super(table); } @Override public int put(String id, Map rd) throws HongsException { String stat = Synt.asString(rd.get("state")); String name = Synt.asString(rd.get("name" )); String stax = get(id, "state"); String namx = get(id, "name" ); List conf = parseConf(rd); // 冻结意味着手动修改了配置 // 再操作可能会冲掉自定配置 if (stat == null) { if ("3".equals(stax)) { throw new HongsException(0x1100, "表单冻结, 禁止操作"); } if ("0".equals(stax)) { throw new HongsException(0x1104, "表单缺失, 无法操作"); } } int n = superPut(id, rd); if (n != 0) { // 用旧数据补全 if (stat == null && name != null) { stat = stax; } if (name == null && stat != null) { name = namx; } // 更新配置文件 if (conf != null || stat != null) { updateFormConf(id, stat,conf); } if (name != null || stat != null) { updateFormMenu(id, stat,name); } if (stat != null) { updateUnitMenu(get(id, "unit_id")); } } return n; } @Override public int add(String id, Map rd) throws HongsException { String ud = Synt.asString(rd.get("unit_id")); String stat = Synt.asString(rd.get("state")); String name = Synt.asString(rd.get("name" )); List conf = parseConf(rd); int n = superAdd(id, rd); if (n != 0) { // 更新配置文件 updateFormConf(id, stat, conf); updateFormMenu(id, stat, name); // 更新单元菜单 updateUnitMenu(ud); // 添加表单权限 insertAuthRole(id); } return n; } @Override public int del(String id, FetchCase fc) throws HongsException { String ud = get(id, "unit_id"); int n = superDel(id, fc); if (n != 0) { // 删除配置文件 deleteFormConf(id); deleteFormMenu(id); // 更新单元菜单 updateUnitMenu(ud); // 删除表单权限 deleteAuthRole(id); } return n; } private String get(String id, String fn) throws HongsException { Object fv = table.fetchCase() .filter("id = ?", id) .select(fn) .getOne( ) .get (fn); return Synt.declare( fv, "" ); } protected final int superAdd(String id, Map rd) throws HongsException { return super.add(id, rd); } protected final int superPut(String id, Map rd) throws HongsException { return super.put(id, rd); } protected final int superDel(String id, FetchCase fc) throws HongsException { return super.del(id, fc); } protected List<Map> parseConf(Map rd) { List<Map> flds = null; String conf = (String) rd.get("conf"); String name = (String) rd.get("name"); if (conf != null && !"".equals(conf)) { flds = Synt.asList(Data.toObject(conf)); Set set = Synt.setOf("name", "word", "cuser", "muser", "ctime", "mtime"); Map tdf = null; Map idf = null; Map fld ; Iterator<Map> itr = flds.iterator(); while (itr.hasNext()) { fld = itr.next(); if ( "-".equals(fld.get("__name__"))) { fld.put("__name__", Core.newIdentity()); } else if ( "@".equals(fld.get("__name__"))) { tdf = fld; itr. remove ( ); } else if ( "id".equals(fld.get("__name__"))) { idf = fld; itr. remove ( ); } else if (set.contains(fld.get("__name__"))) { set. remove (fld.get("__name__")); } } if (tdf != null) { flds.add(0, tdf); // 去掉表单的基础属性 tdf.remove("__type__"); tdf.remove("__rule__"); tdf.remove("__required__"); tdf.remove("__repeated__"); } if (idf != null) { flds.add(1, idf); // 去掉主键的基础属性 idf.remove("__required__"); idf.remove("__repeated__"); } conf = Data.toString(flds); rd.put("conf", conf); // 补全表配置项 fld = Synt.mapOf( "__text__", name, "listable", "?", "sortable", "?", "findable", "?", "nameable", "?" ); if (tdf != null) { fld .putAll(tdf); tdf .putAll(fld); } else { flds.add(0, fld); } // 补全编号字段 fld = Synt.mapOf( "__text__", "ID", "__name__", "id", "__type__", "hidden" ); if (idf != null) { fld .putAll(idf); idf .putAll(fld); } else { flds.add(1, fld); } // 增加名称字段 if (set.contains("name")) { flds.add(Synt.mapOf( "__name__", "name", "__type__", "hidden", "lucene-type", "stored", "readonly", "true" )); } // 增加搜索字段 if (set.contains("word")) { flds.add(Synt.mapOf( "__name__", "word", "__type__", "hidden", "lucene-type", "search", "readonly", "true", "unstored", "true" )); } // 增加用户字段 if (set.contains("muser")) { flds.add(Synt.mapOf( "__name__", "muser", "__type__", "hidden", "readonly", "true", "default" , "=$uid", "deforce" , "always" )); } if (set.contains("cuser")) { flds.add(Synt.mapOf( "__name__", "cuser", "__type__", "hidden", "readonly", "true", "default" , "=$uid", "deforce" , "create" )); } // 增加时间字段 if (set.contains("mtime")) { flds.add(Synt.mapOf( "__name__", "mtime", "__type__", "datetime", "type" , "timestamp", "readonly", "true", "default" , "=%now", "deforce" , "always" )); } if (set.contains("ctime")) { flds.add(Synt.mapOf( "__name__", "ctime", "__type__", "datetime", "type" , "timestamp", "readonly", "true", "default" , "=%now", "deforce" , "create" )); } } else { rd.remove("conf"); } return flds; } @Override protected void filter(FetchCase caze, Map rd) throws HongsException { super.filter(caze, rd); // 超级管理员不做限制 ActionHelper helper = Core.getInstance (ActionHelper.class); String uid = ( String ) helper.getSessibute( Cnst.UID_SES ); if (Cnst.ADM_UID.equals(uid)) { return; } String mm = caze.getOption("MODEL_START" , ""); if ("getList".equals(mm) || "getInfo".equals(mm)) { mm = "/search"; } else if ("update" .equals(mm) || "delete" .equals(mm)) { mm = "/" + mm ; } else { return; // 非常规动作不限制 } // 从权限串中取表单ID NaviMap nm = NaviMap.getInstance(centra); String pm = centra + "/"; Set<String> ra = nm.getRoleSet( ); Set<String> rs = new HashSet( ); for (String rn : ra) { if (rn.startsWith(pm) && rn. endsWith(mm)) { rs.add(rn.substring(pm.length(), rn.length() - mm.length())); } } // 限制为有权限的表单 caze.filter("`"+table.name+"`.`id` IN (?)", rs); } protected void insertAuthRole(String id) throws HongsException { ActionHelper helper = Core.getInstance(ActionHelper.class); String uid = (String) helper.getSessibute ( Cnst.UID_SES ); String tan ; // 写入权限 tan = (String) table.getParams().get("role.table"); if (tan != null) { Table tab = db.getTable(tan); tab.insert(Synt.mapOf("user_id", uid, "role" , centra + "/" + id + "/search" )); tab.insert(Synt.mapOf("user_id", uid, "role" , centra + "/" + id + "/create" )); tab.insert(Synt.mapOf("user_id", uid, "role" , centra + "/" + id + "/update" )); tab.insert(Synt.mapOf("user_id", uid, "role" , centra + "/" + id + "/delete" )); tab.insert(Synt.mapOf("user_id", uid, "role" , centra + "/" + id + "/revert" )); } // 更新缓存(通过改变权限更新时间) tan = (String) table.getParams().get("user.table"); if (tan != null) { Table tab = db.getTable(tan); tab.update(Synt.mapOf( "rtime", System.currentTimeMillis() / 1000 ) , "`id` = ?" , uid ); } } protected void deleteAuthRole(String id) throws HongsException { ActionHelper helper = Core.getInstance(ActionHelper.class); String uid = (String) helper.getSessibute ( Cnst.UID_SES ); String tan; // 删除权限 tan = (String) table.getParams().get("role.table"); if (tan != null) { Table tab = db.getTable(tan); tab.remove("`role` IN (?)", Synt.setOf(centra + "/" + id + "/search", centra + "/" + id + "/create", centra + "/" + id + "/update", centra + "/" + id + "/delete", centra + "/" + id + "/revert" )); } // 更新缓存(通过改变权限更新时间) tan = (String) table.getParams().get("user.table"); if (tan != null) { Table tab = db.getTable(tan); tab.update(Synt.mapOf( "rtime", System.currentTimeMillis() / 1000 ) , "`id` = ?" , uid ); } } protected void deleteFormMenu(String id) { File fo; fo = new File(Core.CONF_PATH +"/"+ centra +"/"+ id + Cnst.FORM_EXT +".xml"); if (fo.exists()) fo.delete(); fo = new File(Core.CONF_PATH +"/"+ centre +"/"+ id + Cnst.FORM_EXT +".xml"); if (fo.exists()) fo.delete(); } protected void deleteFormConf(String id) { File fo; fo = new File(Core.CONF_PATH +"/"+ centra +"/"+ id + Cnst.NAVI_EXT +".xml"); if (fo.exists()) fo.delete(); fo = new File(Core.CONF_PATH +"/"+ centre +"/"+ id + Cnst.NAVI_EXT +".xml"); if (fo.exists()) fo.delete(); } protected void updateUnitMenu(String id) throws HongsException { new Unit().updateMenus( ); } protected void updateFormMenu(String id, String stat, String name) throws HongsException { Document docm; Element root, menu, role, actn, depn; docm = makeDocument(); root = docm.createElement("root"); docm.appendChild ( root ); menu = docm.createElement("menu"); root.appendChild ( menu ); menu.setAttribute("text", name ); menu.setAttribute("href", centra+"/"+id+"/"); // 会话 role = docm.createElement("rsname"); root.appendChild ( role ); role.appendChild ( docm.createTextNode("@centra")); // 查看 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", centra+"/"+id+"/search"); role.setAttribute("text", "查看"+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/search" + Cnst.ACT_EXT) ); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/counts/search" + Cnst.ACT_EXT) ); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/statis/search" + Cnst.ACT_EXT) ); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/stream/search" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode("centra") ); // 修改 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", centra+"/"+id+"/update"); role.setAttribute("text", "修改"+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/update" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(centra+"/"+id+"/search") ); // 添加 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", centra+"/"+id+"/create"); role.setAttribute("text", "添加"+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/create" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(centra+"/"+id+"/search") ); // 删除 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", centra+"/"+id+"/delete"); role.setAttribute("text", "删除"+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/delete" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(centra+"/"+id+"/search") ); // 回看 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", centra+"/"+id+"/review"); role.setAttribute("text", "回看"+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/revert/search" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(centra+"/"+id+"/search") ); // 恢复 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", centra+"/"+id+"/revert"); role.setAttribute("text", "恢复"+name); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centra+"/"+id+"/revert/update" + Cnst.ACT_EXT) ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(centra+"/"+id+"/update") ); depn = docm.createElement("depend"); role.appendChild ( depn ); depn.appendChild ( docm.createTextNode(centra+"/"+id+"/review") ); saveDocument(Core.CONF_PATH+"/"+centra+"/"+id+Cnst.NAVI_EXT+".xml", docm); //** 对外开放 **/ /** * 仅供内部管理用时, * 应确保无开放配置. */ File fo = new File(Core.CONF_PATH+"/"+centre+"/"+id+Cnst.NAVI_EXT+".xml"); if (!"2".equals(stat)) { if (fo.exists()) { fo.delete(); } return; } docm = makeDocument(); root = docm.createElement("root"); docm.appendChild ( root ); menu = docm.createElement("menu"); root.appendChild ( menu ); menu.setAttribute("text", name ); menu.setAttribute("href", centre+"/"+id+"/"); // 会话 role = docm.createElement("rsname"); root.appendChild ( role ); role.appendChild ( docm.createTextNode("@centre")); // 公共读取权限 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", "public"); // 增删改须登录 role = docm.createElement("role"); menu.appendChild ( role ); role.setAttribute("name", "centre"); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centre+"/"+id+"/create" + Cnst.ACT_EXT) ); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centre+"/"+id+"/update" + Cnst.ACT_EXT) ); actn = docm.createElement("action"); role.appendChild ( actn ); actn.appendChild ( docm.createTextNode(centre+"/"+id+"/delete" + Cnst.ACT_EXT) ); saveDocument(Core.CONF_PATH+"/"+centre+"/"+id+Cnst.NAVI_EXT+".xml", docm); } protected void updateFormConf(String id, String stat, List<Map> conf) throws HongsException { Document docm; Element root, form, item; docm = makeDocument(); root = docm.createElement("root"); docm.appendChild ( root ); form = docm.createElement("form"); root.appendChild ( form ); form.setAttribute("name" , id ); Map types = FormSet.getInstance().getEnum("__types__"); for (Map fiel: conf) { item = docm.createElement("field"); form.appendChild ( item ); String s, n, t; s = (String) fiel.get("__text__"); if (s != null) item.setAttribute("text", s); n = (String) fiel.get("__name__"); if (n != null) item.setAttribute("name", n); t = (String) fiel.get("__type__"); if (t != null) item.setAttribute("type", t); s = (String) fiel.get("__rule__"); if (s != null && s.length() != 0) item.setAttribute("rule", s); s = (String) fiel.get("__required__"); if (s != null && s.length() != 0) item.setAttribute("required", s); s = (String) fiel.get("__repeated__"); if (s != null && s.length() != 0) item.setAttribute("repeated", s); // 默认不要存放要空字符串 if (!fiel.containsKey("defiant")) { fiel.put("defiant", ""); } // 日期类型要指定存储格式 if ("date".equals(types.get(t) )) { if(!fiel.containsKey("type")) { fiel.put("type", "timestamp"); } } else // 文件类型要指定上传路径 if ("file".equals(types.get(t) )) { if(!fiel.containsKey("href")) { fiel.put("href", upload +"/"+ id); } if(!fiel.containsKey("path")) { fiel.put("path", upload +"/"+ id); } } else // 选项表单要指定配置路径 if ("enum".equals(types.get(t) ) || "form".equals(types.get(t) )) { if(!fiel.containsKey("conf")) { fiel.put("conf", centra +"/"+ id); } } else // 可搜索指定存为搜索类型 if ("search".equals(t) || Synt.declare(fiel.get("srchable"), false)) { if(!fiel.containsKey("lucnene-type")) { fiel.put("lucene-type", "search"); } } else // 文本禁搜索则为存储类型 if ("stored".equals(t) ||"textarea".equals(t) ||"textview".equals(t)) { if(!fiel.containsKey("lucnene-type")) { fiel.put("lucene-type", "stored"); } } Map<String,Map<String,String>> preset = null; List<List<String>> select = null; //** 构建字段参数 **/ for(Object ot : fiel.entrySet( )) { Map.Entry et = (Map.Entry) ot; String k = (String) et.getKey( ); String v = (String) et.getValue(); if (k==null || v==null) { continue; } if (k.startsWith("__")) { continue; } if (k.startsWith( "." ) // 外部预置数据 || k.startsWith( ":")) { // 内部预置数据 if (preset == null) { preset = new LinkedHashMap(); } String l; if (n.equals( "@")) { // 表单预置数据 int p = k.indexOf('.', 1); if (p == -1) continue; l = k.substring(1+ p); k = k.substring(0, p); k = id + k ; } else { // 一般枚举选项 l = k.substring(1 ); k = n; } Dict.put(preset, v, k, l); continue; } if (k.equals("datalist")) { select = Synt.asList(Data.toObject(v) ); continue; } Element para = docm.createElement("param"); item.appendChild ( para ); para.setAttribute("name" , k); para.appendChild ( docm.createTextNode(v) ); } //** 构建枚举列表 **/ if (select != null) { Element anum = docm.createElement("enum" ); root.appendChild ( anum ); anum.setAttribute("name" , n); for(List a : select) { String c = Synt.declare( a.get(0), "" ); String l = Synt.declare( a.get(1), "" ); Element valu = docm.createElement("value"); anum.appendChild ( valu ); valu.setAttribute("code" , c); valu.appendChild ( docm.createTextNode(l) ); } } //** 构建预置数据 **/ if (preset != null) { for(Map.Entry<String,Map<String,String>> et0 : preset.entrySet()) { n = et0.getKey(); Element anum = docm.createElement("enum" ); root.appendChild ( anum ); anum.setAttribute("name" , n); for(Map.Entry<String,String> et1 : et0.getValue().entrySet()) { String c = et1.getKey( ); String l = et1.getValue(); Element valu = docm.createElement("value"); anum.appendChild ( valu ); valu.setAttribute("code" , c); valu.appendChild ( docm.createTextNode(l) ); } } } } saveDocument(Core.CONF_PATH+"/"+centra+"/"+id+Cnst.FORM_EXT+".xml", docm); //** 对外开放 **/ /** * 仅供内部管理用时, * 应确保无公开配置. * 开放存在则不处理, * 固定内容无需更新. */ File fo = new File(Core.CONF_PATH+"/"+centre+"/"+id+Cnst.FORM_EXT+".xml"); if (!"2".equals(stat)) { if (fo.exists()) { fo.delete(); } return; } else { if (fo.exists()) { return; } } docm = makeDocument(); root = docm.createElement("root"); docm.appendChild ( root ); form = docm.createElement("form"); root.appendChild ( form ); form.setAttribute("name" , id ); Element defs, defi; // 全局性保护 defs = docm.createElement("enum"); root.appendChild ( defs ); defs.setAttribute("name", id+":defense"); defi = docm.createElement("value"); defs.appendChild ( defi ); defi.setAttribute("code", Cnst.AR_KEY); defi.appendChild ( docm.createTextNode("(null)")); defi = docm.createElement("value"); defs.appendChild ( defi ); defi.setAttribute("code", Cnst.OR_KEY); defi.appendChild ( docm.createTextNode("(null)")); // 保护写接口 defs = docm.createElement("enum"); root.appendChild ( defs ); defs.setAttribute("name", id+":defence"); defi = docm.createElement("value"); defs.appendChild ( defi ); defi.setAttribute("code", Cnst.AR_KEY+".x.cuser"); defi.appendChild ( docm.createTextNode("($session.uid)")); // 我所创建的 defs = docm.createElement("enum"); root.appendChild ( defs ); defs.setAttribute("name", id+".created"); defi = docm.createElement("value"); defs.appendChild ( defi ); defi.setAttribute("code", Cnst.AR_KEY+".x.cuser"); defi.appendChild ( docm.createTextNode("($session.uid)")); saveDocument(Core.CONF_PATH+"/"+centre+"/"+id+Cnst.FORM_EXT+".xml", docm); } private Document makeDocument() throws HongsException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.newDocument(); } catch (ParserConfigurationException e) { throw new HongsException.Common ( e); } } private void saveDocument(String path, Document docm) throws HongsException { File file = new File(path); File fold = file.getParentFile(); if (!fold.exists()) { fold.mkdirs(); } TransformerFactory tf = TransformerFactory.newInstance(); try { Transformer tr = tf.newTransformer(); DOMSource ds = new DOMSource(docm); StreamResult sr = new StreamResult ( new OutputStreamWriter( new FileOutputStream(file), "utf-8")); tr.setOutputProperty(OutputKeys.ENCODING, "utf-8"); tr.setOutputProperty(OutputKeys.METHOD , "xml" ); tr.setOutputProperty(OutputKeys.INDENT , "yes" ); tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); tr.transform(ds, sr); } catch (TransformerConfigurationException e) { throw new HongsException.Common(e); } catch (IllegalArgumentException e) { throw new HongsException.Common(e); } catch (TransformerException e) { throw new HongsException.Common(e); } catch (FileNotFoundException e) { throw new HongsException.Common(e); } catch (UnsupportedEncodingException e) { throw new HongsException.Common(e); } } }
为 word 增加高级解析功能
hongs-serv-matrix/src/main/java/io/github/ihongs/serv/matrix/Form.java
为 word 增加高级解析功能
<ide><path>ongs-serv-matrix/src/main/java/io/github/ihongs/serv/matrix/Form.java <ide> flds.add(Synt.mapOf( <ide> "__name__", "name", <ide> "__type__", "hidden", <del> "lucene-type", "stored", <del> "readonly", "true" <add> "readonly", "true", <add> "lucene-type", "stored" <ide> )); <ide> } <ide> <ide> flds.add(Synt.mapOf( <ide> "__name__", "word", <ide> "__type__", "hidden", <add> "readonly", "true", <add> "unstored", "true", <ide> "lucene-type", "search", <del> "readonly", "true", <del> "unstored", "true" <add> "lucene-smart-parse", "true" <ide> )); <ide> } <ide>
Java
apache-2.0
d3ff62ba257b5964fd8e4acfd40de7e68d707bef
0
xxxllluuu/uavstack,xxxllluuu/uavstack,xxxllluuu/uavstack,xxxllluuu/uavstack,xxxllluuu/uavstack
/*- * << * UAVStack * == * Copyright (C) 2016 - 2017 UAVStack * == * 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. * >> */ package com.creditease.agent.log; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.logging.MemoryHandler; import com.creditease.agent.helpers.JVMToolHelper; import com.creditease.agent.log.api.IPLogger; public class PLogger implements IPLogger { public static class DefaultLogFormatter extends Formatter { private SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:S"); @Override public String format(LogRecord record) { return "[" + dateFormatter.format(new Date()) + "] " + record.getThreadID() + " " + getLogLevelStr(record.getLevel()) + " " + record.getMessage() + JVMToolHelper.getLineSeperator(); } } public static class SimpleLogFormatter extends Formatter { @Override public String format(LogRecord record) { return record.getMessage() + JVMToolHelper.getLineSeperator(); } } private static String getLogLevelStr(Level level) { if (level == Level.INFO) { return "I "; } else if (level == Level.SEVERE) { return "E "; } else if (level == Level.WARNING) { return "W "; } else if (level == Level.FINEST) { return "D "; } else if (level == Level.FINE) { return "F "; } else if (level == Level.FINER) { return "FR"; } else { return "I "; } } private static Level getLevel(LogLevel level) { Level l = Level.INFO; switch (level) { case ALL: l = Level.ALL; break; case DEBUG: l = Level.FINEST; break; case ERR: l = Level.SEVERE; break; case FINE: l = Level.FINE; break; case FINER: l = Level.FINER; break; case INFO: l = Level.INFO; break; case WARNING: l = Level.WARNING; break; default: l = Level.INFO; break; } return l; } private Logger log = null; private ConsoleHandler consoleHandler = null; private FileHandler fileHandler = null; private MemoryHandler memHandler = null; private Level level = Level.INFO; private boolean isEnableFileOutSus = false; private boolean isEnableConsoleOutSus = false; public PLogger(String name) { log = Logger.getLogger(name); log.setUseParentHandlers(false); } @Override public void setLogLevel(LogLevel level) { Level l = getLevel(level); log.setLevel(l); this.level = l; if (this.consoleHandler != null) { this.consoleHandler.setLevel(l); } if (this.memHandler != null) { this.memHandler.setLevel(l); } if (this.fileHandler != null) { this.fileHandler.setLevel(l); } } @Override public void log(LogLevel level, String info, Object... objects) { /** * NOTE: only when enable is OK to record the log */ if (isEnableFileOutSus == false && isEnableConsoleOutSus == false) { return; } Level l = getLevel(level); log.log(l, info, objects); } @Override public void info(String info, Object... objects) { log(LogLevel.INFO, info, objects); } @Override public void warn(String info, Object... objects) { log(LogLevel.WARNING, info, objects); } @Override public void err(String info, Object... objects) { log(LogLevel.ERR, info, objects); } @Override public void debug(String info, Object... objects) { log(LogLevel.DEBUG, info, objects); } @Override public void fine(String info, Object... objects) { log(LogLevel.FINE, info, objects); } @Override public void finer(String info, Object... objects) { log(LogLevel.FINER, info, objects); } @Override public boolean enableConsoleOut(boolean check) { if (check == true) { if (this.consoleHandler == null) { this.consoleHandler = new ConsoleHandler(); this.consoleHandler.setLevel(this.level); this.consoleHandler.setFormatter(new DefaultLogFormatter()); } log.addHandler(this.consoleHandler); isEnableConsoleOutSus = true; } else { if (this.consoleHandler != null) { log.removeHandler(this.consoleHandler); } isEnableConsoleOutSus = false; } return isEnableConsoleOutSus; } @Override public boolean enableFileOut(String filepattern, boolean check, int bufferSize, int fileSize, int fileCount, boolean isAppend, Formatter format) { if (check == true) { if (this.fileHandler == null) { initFileHandler(filepattern, fileSize, fileCount, isAppend); } if (this.fileHandler != null) { this.fileHandler.setLevel(this.level); this.fileHandler.setFormatter(format); } /** * NOTE: we use async log buffer */ if (this.memHandler == null&& this.fileHandler != null) { this.memHandler = new MemoryHandler(this.fileHandler, bufferSize, this.level); this.log.addHandler(this.memHandler); isEnableFileOutSus = true; } } else { if (this.memHandler != null) { log.removeHandler(this.memHandler); isEnableFileOutSus = false; } } return isEnableFileOutSus; } /** * @param filepattern * @param fileSize * @param fileCount * @param isAppend */ private void initFileHandler(String filepattern, int fileSize, int fileCount, boolean isAppend) { try { if (fileSize > 0 && fileCount > 0) { if (isAppend == false) { this.fileHandler = new FileHandler(filepattern, fileSize, fileCount); } else { this.fileHandler = new FileHandler(filepattern, fileSize, fileCount, isAppend); } } else { this.fileHandler = new FileHandler(filepattern); } } catch (SecurityException e) { // ignore } catch (IOException e) { // ignore } } @Override public void destroy() { if (this.consoleHandler != null) { this.consoleHandler.flush(); this.consoleHandler.close(); } if (this.memHandler != null) { this.memHandler.flush(); this.memHandler.close(); } if (this.fileHandler != null) { this.fileHandler.flush(); this.fileHandler.close(); } } }
com.creditease.uav.logging/src/main/java/com/creditease/agent/log/PLogger.java
/*- * << * UAVStack * == * Copyright (C) 2016 - 2017 UAVStack * == * 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. * >> */ package com.creditease.agent.log; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.logging.MemoryHandler; import com.creditease.agent.helpers.JVMToolHelper; import com.creditease.agent.log.api.IPLogger; public class PLogger implements IPLogger { public static class DefaultLogFormatter extends Formatter { private SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:S"); @Override public String format(LogRecord record) { return "[" + dateFormatter.format(new Date()) + "] " + record.getThreadID() + " " + getLogLevelStr(record.getLevel()) + " " + record.getMessage() + JVMToolHelper.getLineSeperator(); } } public static class SimpleLogFormatter extends Formatter { @Override public String format(LogRecord record) { return record.getMessage() + JVMToolHelper.getLineSeperator(); } } private static String getLogLevelStr(Level level) { if (level == Level.INFO) { return "I "; } else if (level == Level.SEVERE) { return "E "; } else if (level == Level.WARNING) { return "W "; } else if (level == Level.FINEST) { return "D "; } else if (level == Level.FINE) { return "F "; } else if (level == Level.FINER) { return "FR"; } else { return "I "; } } private static Level getLevel(LogLevel level) { Level l = Level.INFO; switch (level) { case ALL: l = Level.ALL; break; case DEBUG: l = Level.FINEST; break; case ERR: l = Level.SEVERE; break; case FINE: l = Level.FINE; break; case FINER: l = Level.FINER; break; case INFO: l = Level.INFO; break; case WARNING: l = Level.WARNING; break; default: l = Level.INFO; break; } return l; } private Logger log = null; private ConsoleHandler consoleHandler = null; private FileHandler fileHandler = null; private MemoryHandler memHandler = null; private Level level = Level.INFO; private boolean isEnableFileOutSus = false; private boolean isEnableConsoleOutSus = false; public PLogger(String name) { log = Logger.getLogger(name); log.setUseParentHandlers(false); } @Override public void setLogLevel(LogLevel level) { Level l = getLevel(level); log.setLevel(l); this.level = l; if (this.consoleHandler != null) { this.consoleHandler.setLevel(l); } if (this.memHandler != null) { this.memHandler.setLevel(l); } if (this.fileHandler != null) { this.fileHandler.setLevel(l); } } @Override public void log(LogLevel level, String info, Object... objects) { /** * NOTE: only when enable is OK to record the log */ if (isEnableFileOutSus == false && isEnableConsoleOutSus == false) { return; } Level l = getLevel(level); log.log(l, info, objects); } @Override public void info(String info, Object... objects) { log(LogLevel.INFO, info, objects); } @Override public void warn(String info, Object... objects) { log(LogLevel.WARNING, info, objects); } @Override public void err(String info, Object... objects) { log(LogLevel.ERR, info, objects); } @Override public void debug(String info, Object... objects) { log(LogLevel.DEBUG, info, objects); } @Override public void fine(String info, Object... objects) { log(LogLevel.FINE, info, objects); } @Override public void finer(String info, Object... objects) { log(LogLevel.FINER, info, objects); } @Override public boolean enableConsoleOut(boolean check) { if (check == true) { if (this.consoleHandler == null) { this.consoleHandler = new ConsoleHandler(); this.consoleHandler.setLevel(this.level); this.consoleHandler.setFormatter(new DefaultLogFormatter()); } log.addHandler(this.consoleHandler); isEnableConsoleOutSus = true; } else { if (this.consoleHandler != null) { log.removeHandler(this.consoleHandler); } isEnableConsoleOutSus = false; } return isEnableConsoleOutSus; } @Override public boolean enableFileOut(String filepattern, boolean check, int bufferSize, int fileSize, int fileCount, boolean isAppend, Formatter format) { if (check == true) { if (this.fileHandler == null) { initFileHandler(filepattern, fileSize, fileCount, isAppend); } if (this.fileHandler != null) { this.fileHandler.setLevel(this.level); this.fileHandler.setFormatter(format); } /** * NOTE: we use async log buffer */ if (this.memHandler == null&& this.fileHandler != null) { this.memHandler = new MemoryHandler(this.fileHandler, bufferSize, this.level); this.log.addHandler(this.memHandler); isEnableFileOutSus = true; } } else { if (this.memHandler != null) { log.removeHandler(this.memHandler); isEnableFileOutSus = false; } } return isEnableFileOutSus; } /** * @param filepattern * @param fileSize * @param fileCount * @param isAppend */ private void initFileHandler(String filepattern, int fileSize, int fileCount, boolean isAppend) { try { if (fileSize > 0 && fileCount > 0) { if (isAppend == false) { this.fileHandler = new FileHandler(filepattern, fileSize, fileCount); } else { this.fileHandler = new FileHandler(filepattern, fileSize, fileCount, isAppend); } } else { this.fileHandler = new FileHandler(filepattern); } } catch (SecurityException e) { // ignore } catch (IOException e) { // ignore } } @Override public void destroy() { if (this.consoleHandler != null) { this.consoleHandler.flush(); this.consoleHandler.close(); } if (this.memHandler != null) { this.memHandler.flush(); this.memHandler.close(); } if (this.fileHandler != null) { this.fileHandler.flush(); this.fileHandler.close(); } } }
code format
com.creditease.uav.logging/src/main/java/com/creditease/agent/log/PLogger.java
code format
<ide><path>om.creditease.uav.logging/src/main/java/com/creditease/agent/log/PLogger.java <ide> this.consoleHandler.setFormatter(new DefaultLogFormatter()); <ide> } <ide> log.addHandler(this.consoleHandler); <del> isEnableConsoleOutSus = true; <add> isEnableConsoleOutSus = true; <ide> } <ide> else { <ide> if (this.consoleHandler != null) { <ide> log.removeHandler(this.consoleHandler); <ide> } <del> isEnableConsoleOutSus = false; <del> } <del> <del> return isEnableConsoleOutSus; <add> isEnableConsoleOutSus = false; <add> } <add> <add> return isEnableConsoleOutSus; <ide> } <ide> <ide> @Override <ide> if (this.memHandler == null&& this.fileHandler != null) { <ide> this.memHandler = new MemoryHandler(this.fileHandler, bufferSize, this.level); <ide> this.log.addHandler(this.memHandler); <del> isEnableFileOutSus = true; <add> isEnableFileOutSus = true; <ide> } <ide> } <ide> else { <ide> if (this.memHandler != null) { <ide> log.removeHandler(this.memHandler); <del> isEnableFileOutSus = false; <del> } <del> } <del> <del> return isEnableFileOutSus; <add> isEnableFileOutSus = false; <add> } <add> } <add> <add> return isEnableFileOutSus; <ide> } <ide> <ide> /**
Java
apache-2.0
f6932f19b0f4579e0a485e8b7bf5075137c4af79
0
TiVo/intellij-haxe,HaxeFoundation/intellij-haxe,winmain/intellij-haxe,TiVo/intellij-haxe,winmain/intellij-haxe,EricBishton/intellij-haxe,HaxeFoundation/intellij-haxe,HaxeFoundation/intellij-haxe,eliasku/intellij-haxe,eliasku/intellij-haxe,eliasku/intellij-haxe,EricBishton/intellij-haxe,winmain/intellij-haxe,TiVo/intellij-haxe,EricBishton/intellij-haxe
/* * Copyright 2000-2013 JetBrains s.r.o. * Copyright 2014-2014 AS3Boyan * Copyright 2014-2014 Elias Ku * Copyright 2018 Ilya Malanin * Copyright 2018 Eric Bishton * * 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. */ package com.intellij.plugins.haxe.ide.folding; import com.intellij.lang.ASTNode; import com.intellij.lang.folding.FoldingBuilder; import com.intellij.lang.folding.FoldingDescriptor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.util.TextRange; import com.intellij.plugins.haxe.ide.HaxeCommenter; import com.intellij.plugins.haxe.util.HaxeStringUtil; import com.intellij.plugins.haxe.util.UsefulPsiTreeUtil; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypeSets.*; import static com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypes.*; import static com.intellij.psi.TokenType.WHITE_SPACE; public class HaxeFoldingBuilder implements FoldingBuilder { private static final String PLACEHOLDER_TEXT = "..."; private static final String WS = "[ \\t]"; // Better unicode space detection: "[\\s\\p{Z}]"; private static final RegionDefinition FD_STYLE = new RegionDefinition("^\\{"+WS+"*region"+WS+"+(.*)$", "^}"+WS+"?end"+WS+"*region("+WS+"*(.*))?$", (matcher)->matcher.group(1)); private static final RegionDefinition PLUGIN_STYLE = new RegionDefinition("^region"+WS+"*(.*)?$", "^end"+WS+"*region"+WS+"*(.*)?$", (matcher)->matcher.group(1)); private static final RegionDefinition C_SHARP_STYLE = new RegionDefinition("^#"+WS+"*region"+WS+"+(.*)$", "^#"+WS+"?end"+WS+"*region("+WS+"*(.*))?$", (matcher)->matcher.group(1)); private static final RegionDefinition COMMENT_REGIONS[] = { FD_STYLE, PLUGIN_STYLE, C_SHARP_STYLE }; private static final RegionDefinition CC_REGION = new RegionDefinition("#", "#", null); private static class RegionDefinition { final Pattern begin; final Pattern end; final Function<Matcher,String> substitutor; public RegionDefinition(String begin, String end, Function<Matcher, String> titleExtractor) { this.begin = Pattern.compile(begin); this.end = Pattern.compile(end); this.substitutor = titleExtractor; } public RegionDefinition(String begin, Function<Matcher, String> titleExtractor) { this.begin = Pattern.compile(begin); this.end = this.begin; this.substitutor = titleExtractor; } public Matcher startMatcher(String s) { return begin.matcher(s); } public Matcher endMatcher(String s) { return end.matcher(s); } public String getPlaceholder(Matcher m) { if (null != substitutor) { return substitutor.apply(m); } return PLACEHOLDER_TEXT; } } private static class RegionMarker { public enum Type { START, END, CC, EMPTY } public static final RegionMarker EMPTY = new RegionMarker(null, null, null, Type.EMPTY); public final RegionDefinition region; public final ASTNode node; public final Type type; public final Matcher matcher; public RegionMarker(RegionDefinition region, ASTNode node, Matcher matcher, Type type) { this.region = region; this.node = node; this.type = type; this.matcher = matcher; } } @NotNull @Override public FoldingDescriptor[] buildFoldRegions(@NotNull ASTNode node, @NotNull Document document) { List<FoldingDescriptor> descriptorList = new ArrayList<>(); List<RegionMarker> regionMarkers = new ArrayList<>(); List<RegionMarker> ccMarkers = new ArrayList<>(); buildFolding(node, descriptorList, regionMarkers, ccMarkers); buildMarkerRegions(descriptorList, regionMarkers); buildCCMarkerRegions(descriptorList, ccMarkers, document); FoldingDescriptor[] descriptors = new FoldingDescriptor[descriptorList.size()]; return descriptorList.toArray(descriptors); } private static void buildFolding(@NotNull ASTNode node, List<FoldingDescriptor> descriptors, List<RegionMarker> regionMarkers, List<RegionMarker> ccMarkers) { final IElementType elementType = node.getElementType(); FoldingDescriptor descriptor = null; if (isImportOrUsingStatement(elementType) && isFirstImportStatement(node)) { descriptor = buildImportsFolding(node); } else if (isCodeBlock(elementType)) { descriptor = buildCodeBlockFolding(node); } else if (isBodyBlock(elementType)) { descriptor = buildBodyBlockFolding(node); } else if (isComment(elementType, node)) { RegionMarker matched = matchRegion(node); if (null != matched) { regionMarkers.add(matched); } } else if (isCompilerConditional(elementType)) { RegionMarker matched = matchCCRegion(node); if (null != matched) { ccMarkers.add(matched); } } if (descriptor != null) { descriptors.add(descriptor); } for (ASTNode child : node.getChildren(null)) { buildFolding(child, descriptors, regionMarkers, ccMarkers); } } private static RegionMarker peekUpStack(List<RegionMarker> list, int n) { return n >= 0 && n < list.size() ? list.get(n) : null; } private static void buildMarkerRegions(List<FoldingDescriptor> descriptors, List<RegionMarker> regionMarkers) { // The list should be a set of balanced nested markers. If they are unbalanced, we simply don't // create the descriptor. LinkedList<RegionMarker> startStack = new LinkedList<>(); for (RegionMarker current : regionMarkers) { if (current.type == RegionMarker.Type.START) { startStack.push(current); } else { // TODO: Use a 'diff' algorithm to determine the best sequence?? See Google's DiffUtils package. // current matches with whatever is on top of the stack. if (startStack.isEmpty()) { // Unbalanced END. // TODO: Mark it as an error in the code?? Can we do that here? continue; } // TODO: Maybe check if the end has a title, and if it does, use that to match to the start as well ?? RegionMarker start = startStack.peek(); if (start.region != current.region) { // Unbalanced start/end types. // Until we can get a better algorithm, we'll use a simple heuristic to see if maybe it's an unbalanced start. RegionMarker nextStart = peekUpStack(startStack, 1); if (null != nextStart && nextStart.region == current.region) { startStack.pop(); // Unbalanced start, so pop one of those start = startStack.peek(); } else { continue; } } startStack.pop(); descriptors.add(buildRegionFolding(start, current)); } } } private static int lineNumber(ASTNode node, Document document) { return document.getLineNumber(node.getStartOffset()); } private static void buildCCRegion(List<FoldingDescriptor> descriptors, RegionMarker start, RegionMarker end, Document document) { if (lineNumber(start.node, document) < lineNumber(end.node, document)) { descriptors.add(buildCCFolding(start, end)); } } private static void buildCCMarkerRegions(List<FoldingDescriptor> descriptors, List<RegionMarker> regionMarkers, Document document) { LinkedList<RegionMarker> interruptedStack = new LinkedList<>(); RegionMarker inProcess = null; for (RegionMarker marker : regionMarkers) { IElementType type = marker.node.getElementType(); if (PPEND == type) { if (null != inProcess) { buildCCRegion(descriptors, inProcess, marker, document); } if (!interruptedStack.isEmpty()) { inProcess = interruptedStack.pop(); } } else { // No matter where we start (e.g. #else instead of #if), we just go to the next marker... if (null == inProcess) { inProcess = marker; } else { // #if introduces a new level. Other kinds do not. if (PPIF == type) { interruptedStack.push(inProcess); inProcess = marker; } else { buildCCRegion(descriptors, inProcess, marker, document); inProcess = marker; } } } } } private static boolean isCodeBlock(IElementType elementType) { return elementType == BLOCK_STATEMENT; } private static boolean isBodyBlock(IElementType elementType) { return BODY_TYPES.contains(elementType); } private static boolean isComment(IElementType elementType, ASTNode node) { return ONLY_COMMENTS.contains(elementType); } private static boolean isCompilerConditional(IElementType elementType) { return ONLY_CC_DIRECTIVES.contains(elementType); } private static String stripComment(IElementType elementType, String text) { if (elementType == MSL_COMMENT) { return strip(text, HaxeCommenter.SINGLE_LINE_PREFIX, null); } if (elementType == MML_COMMENT) { text = HaxeStringUtil.terminateAt(text, '\n'); return strip(text.trim(), HaxeCommenter.BLOCK_COMMENT_PREFIX, HaxeCommenter.BLOCK_COMMENT_SUFFIX); } if (elementType == DOC_COMMENT) { text = HaxeStringUtil.terminateAt(text, '\n'); return strip(text, HaxeCommenter.DOC_COMMENT_PREFIX, HaxeCommenter.DOC_COMMENT_SUFFIX); } return text.trim(); } private static String strip(@NotNull String text, @Nullable String prefix, @Nullable String suffix) { String stripped = text.trim(); if (null != prefix) stripped = HaxeStringUtil.stripPrefix(stripped, prefix); if (null != suffix) stripped = HaxeStringUtil.stripSuffix(stripped, suffix); return stripped.trim(); } private static RegionMarker matchRegion(ASTNode node) { if (null == node) { return null; } String text = stripComment(node.getElementType(), node.getText()); if (null == text || text.isEmpty()) { return null; } // Figure out if it matches any of the region patterns. for (RegionDefinition region : COMMENT_REGIONS) { Matcher start = region.startMatcher(text); if (start.matches()) { return new RegionMarker(region, node, start, RegionMarker.Type.START); } Matcher end = region.endMatcher(text); if (end.matches()) { return new RegionMarker(region, node, end, RegionMarker.Type.END); } } return null; } /** * Gather the CC and its expression (if any) as the placeholder. * * @param node The Compiler Conditional node. * @return a placeholder string for code folding. */ @NotNull private static String getCCPlaceholder(ASTNode node) { StringBuilder s = new StringBuilder(); s.append(node.getText()); ASTNode next = node.getTreeNext(); while (null != next && next.getElementType() == PPEXPRESSION) { s.append(next.getText()); next = next.getTreeNext(); } if (0 != s.length()) { s.append(' '); } String placeholder = s.toString(); return placeholder.isEmpty() ? "compiler conditional" : placeholder; } private static RegionMarker matchCCRegion(ASTNode node) { return new RegionMarker(CC_REGION, node, null, RegionMarker.Type.CC); } private static FoldingDescriptor buildCodeBlockFolding(@NotNull ASTNode node) { final ASTNode openBrace = node.getFirstChildNode(); final ASTNode closeBrace = node.getLastChildNode(); return buildBlockFolding(node, openBrace, closeBrace); } private static FoldingDescriptor buildBodyBlockFolding(@NotNull ASTNode node) { final ASTNode openBrace = UsefulPsiTreeUtil.getPrevSiblingSkipWhiteSpacesAndComments(node); final ASTNode closeBrace = UsefulPsiTreeUtil.getNextSiblingSkipWhiteSpacesAndComments(node); return buildBlockFolding(node, openBrace, closeBrace); } private static FoldingDescriptor buildBlockFolding(@NotNull ASTNode node, ASTNode openBrace, ASTNode closeBrace) { TextRange textRange; if (openBrace != null && closeBrace != null && openBrace.getElementType() == PLCURLY && closeBrace.getElementType() == PRCURLY) { textRange = new TextRange(openBrace.getTextRange().getEndOffset(), closeBrace.getStartOffset()); } else { textRange = node.getTextRange(); } if (textRange.getLength() > PLACEHOLDER_TEXT.length()) { return new FoldingDescriptor(node, textRange); } return null; } private static FoldingDescriptor buildRegionFolding(final RegionMarker start, final RegionMarker end) { TextRange range = new TextRange(start.node.getStartOffset(), end.node.getTextRange().getEndOffset()); return new FoldingDescriptor(start.node, range) { @Nullable @Override public String getPlaceholderText() { String s = start.region.getPlaceholder(start.matcher); return null == s ? PLACEHOLDER_TEXT : s; } }; } private static FoldingDescriptor buildCCFolding(final RegionMarker start, final RegionMarker end) { TextRange range = new TextRange(start.node.getStartOffset(), end.node.getTextRange().getStartOffset()); final String placeholder = getCCPlaceholder(start.node); return new FoldingDescriptor(start.node, range) { @Nullable @Override public String getPlaceholderText() { return placeholder; } }; } private static FoldingDescriptor buildImportsFolding(@NotNull ASTNode node) { final ASTNode lastImportNode = findLastImportNode(node); if (!node.equals(lastImportNode)) { return new FoldingDescriptor(node, buildImportsFoldingTextRange(node, lastImportNode)); } return null; } private static TextRange buildImportsFoldingTextRange(ASTNode firstNode, ASTNode lastNode) { ASTNode nodeStartFrom = UsefulPsiTreeUtil.getNextSiblingSkipWhiteSpacesAndComments(firstNode.getFirstChildNode()); if (nodeStartFrom == null) { nodeStartFrom = firstNode; } return new TextRange(nodeStartFrom.getStartOffset(), lastNode.getTextRange().getEndOffset()); } private static boolean isFirstImportStatement(@NotNull ASTNode node) { ASTNode prevNode = UsefulPsiTreeUtil.getPrevSiblingSkipWhiteSpacesAndComments(node); return prevNode == null || !isImportOrUsingStatement(prevNode.getElementType()); } private static ASTNode findLastImportNode(@NotNull ASTNode node) { ASTNode lastImportNode = node; ASTNode nextNode = UsefulPsiTreeUtil.getNextSiblingSkipWhiteSpacesAndComments(node); while (nextNode != null && isImportOrUsingStatement(nextNode.getElementType())) { lastImportNode = nextNode; nextNode = UsefulPsiTreeUtil.getNextSiblingSkipWhiteSpacesAndComments(nextNode); } if (lastImportNode.getElementType() == WHITE_SPACE) { lastImportNode = lastImportNode.getTreePrev(); } return lastImportNode; } private static boolean isImportOrUsingStatement(IElementType type) { return type == IMPORT_STATEMENT || type == USING_STATEMENT; } @Nullable @Override public String getPlaceholderText(@NotNull ASTNode node) { return PLACEHOLDER_TEXT; } @Override public boolean isCollapsedByDefault(@NotNull ASTNode node) { return false; } }
src/common/com/intellij/plugins/haxe/ide/folding/HaxeFoldingBuilder.java
/* * Copyright 2000-2013 JetBrains s.r.o. * Copyright 2014-2014 AS3Boyan * Copyright 2014-2014 Elias Ku * Copyright 2018 Ilya Malanin * Copyright 2018 Eric Bishton * * 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. */ package com.intellij.plugins.haxe.ide.folding; import com.intellij.lang.ASTNode; import com.intellij.lang.folding.FoldingBuilder; import com.intellij.lang.folding.FoldingDescriptor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.util.TextRange; import com.intellij.plugins.haxe.ide.HaxeCommenter; import com.intellij.plugins.haxe.util.HaxeStringUtil; import com.intellij.plugins.haxe.util.UsefulPsiTreeUtil; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypeSets.*; import static com.intellij.plugins.haxe.lang.lexer.HaxeTokenTypes.*; import static com.intellij.psi.TokenType.WHITE_SPACE; public class HaxeFoldingBuilder implements FoldingBuilder { private static final String PLACEHOLDER_TEXT = "..."; private static final String WS = "[ \\t]"; // Better unicode space detection: "[\\s\\p{Z}]"; private static final RegionDefinition FD_STYLE = new RegionDefinition("^\\{"+WS+"*region"+WS+"+(.*)$", "^}"+WS+"?end"+WS+"*region("+WS+"*(.*))?$", (matcher)->matcher.group(1)); private static final RegionDefinition PLUGIN_STYLE = new RegionDefinition("^region"+WS+"*(.*)?$", "^end"+WS+"*region"+WS+"*(.*)?$", (matcher)->matcher.group(1)); private static final RegionDefinition COMMENT_REGIONS[] = { FD_STYLE, PLUGIN_STYLE }; private static final RegionDefinition CC_REGION = new RegionDefinition("#", "#", null); private static class RegionDefinition { final Pattern begin; final Pattern end; final Function<Matcher,String> substitutor; public RegionDefinition(String begin, String end, Function<Matcher, String> titleExtractor) { this.begin = Pattern.compile(begin); this.end = Pattern.compile(end); this.substitutor = titleExtractor; } public RegionDefinition(String begin, Function<Matcher, String> titleExtractor) { this.begin = Pattern.compile(begin); this.end = this.begin; this.substitutor = titleExtractor; } public Matcher startMatcher(String s) { return begin.matcher(s); } public Matcher endMatcher(String s) { return end.matcher(s); } public String getPlaceholder(Matcher m) { if (null != substitutor) { return substitutor.apply(m); } return PLACEHOLDER_TEXT; } } private static class RegionMarker { public enum Type { START, END, CC, EMPTY } public static final RegionMarker EMPTY = new RegionMarker(null, null, null, Type.EMPTY); public final RegionDefinition region; public final ASTNode node; public final Type type; public final Matcher matcher; public RegionMarker(RegionDefinition region, ASTNode node, Matcher matcher, Type type) { this.region = region; this.node = node; this.type = type; this.matcher = matcher; } } @NotNull @Override public FoldingDescriptor[] buildFoldRegions(@NotNull ASTNode node, @NotNull Document document) { List<FoldingDescriptor> descriptorList = new ArrayList<>(); List<RegionMarker> regionMarkers = new ArrayList<>(); List<RegionMarker> ccMarkers = new ArrayList<>(); buildFolding(node, descriptorList, regionMarkers, ccMarkers); buildMarkerRegions(descriptorList, regionMarkers); buildCCMarkerRegions(descriptorList, ccMarkers, document); FoldingDescriptor[] descriptors = new FoldingDescriptor[descriptorList.size()]; return descriptorList.toArray(descriptors); } private static void buildFolding(@NotNull ASTNode node, List<FoldingDescriptor> descriptors, List<RegionMarker> regionMarkers, List<RegionMarker> ccMarkers) { final IElementType elementType = node.getElementType(); FoldingDescriptor descriptor = null; if (isImportOrUsingStatement(elementType) && isFirstImportStatement(node)) { descriptor = buildImportsFolding(node); } else if (isCodeBlock(elementType)) { descriptor = buildCodeBlockFolding(node); } else if (isBodyBlock(elementType)) { descriptor = buildBodyBlockFolding(node); } else if (isComment(elementType, node)) { RegionMarker matched = matchRegion(node); if (null != matched) { regionMarkers.add(matched); } } else if (isCompilerConditional(elementType)) { RegionMarker matched = matchCCRegion(node); if (null != matched) { ccMarkers.add(matched); } } if (descriptor != null) { descriptors.add(descriptor); } for (ASTNode child : node.getChildren(null)) { buildFolding(child, descriptors, regionMarkers, ccMarkers); } } private static RegionMarker peekUpStack(List<RegionMarker> list, int n) { int current = 0; for (RegionMarker marker : list) { if (current == n) { return marker; } current++; } return null; } private static void buildMarkerRegions(List<FoldingDescriptor> descriptors, List<RegionMarker> regionMarkers) { // The list should be a set of balanced nested markers. If they are unbalanced, we simply don't // create the descriptor. LinkedList<RegionMarker> startStack = new LinkedList<>(); for (RegionMarker current : regionMarkers) { if (current.type == RegionMarker.Type.START) { startStack.push(current); } else { // TODO: Use a 'diff' algorithm to determine the best sequence?? See Google's DiffUtils package. // current matches with whatever is on top of the stack. if (startStack.isEmpty()) { // Unbalanced END. // TODO: Mark it as an error in the code?? Can we do that here? continue; } // TODO: Maybe check if the end has a title, and if it does, use that to match to the start as well ?? RegionMarker start = startStack.peek(); if (start.region != current.region) { // Unbalanced start/end types. // Until we can get a better algorithm, we'll use a simple heuristic to see if maybe it's an unbalanced start. RegionMarker nextStart = peekUpStack(startStack, 1); if (null != nextStart && nextStart.region == current.region) { startStack.pop(); // Unbalanced start, so pop one of those start = startStack.peek(); } else { continue; } } startStack.pop(); descriptors.add(buildRegionFolding(start, current)); } } } private static int lineNumber(ASTNode node, Document document) { return document.getLineNumber(node.getStartOffset()); } private static void buildCCRegion(List<FoldingDescriptor> descriptors, RegionMarker start, RegionMarker end, Document document) { if (lineNumber(start.node, document) < lineNumber(end.node, document)) { descriptors.add(buildCCFolding(start, end)); } } private static void buildCCMarkerRegions(List<FoldingDescriptor> descriptors, List<RegionMarker> regionMarkers, Document document) { LinkedList<RegionMarker> interruptedStack = new LinkedList<>(); RegionMarker inProcess = null; for (RegionMarker marker : regionMarkers) { IElementType type = marker.node.getElementType(); if (PPEND == type) { if (null != inProcess) { buildCCRegion(descriptors, inProcess, marker, document); } if (!interruptedStack.isEmpty()) { inProcess = interruptedStack.pop(); } } else { // No matter where we start (e.g. #else instead of #if), we just go to the next marker... if (null == inProcess) { inProcess = marker; } else { // #if introduces a new level. Other kinds do not. if (PPIF == type) { interruptedStack.push(inProcess); inProcess = marker; } else { buildCCRegion(descriptors, inProcess, marker, document); inProcess = marker; } } } } } private static boolean isCodeBlock(IElementType elementType) { return elementType == BLOCK_STATEMENT; } private static boolean isBodyBlock(IElementType elementType) { return BODY_TYPES.contains(elementType); } private static boolean isComment(IElementType elementType, ASTNode node) { return ONLY_COMMENTS.contains(elementType); } private static boolean isCompilerConditional(IElementType elementType) { return ONLY_CC_DIRECTIVES.contains(elementType); } private static String stripComment(IElementType elementType, String text) { if (elementType == MSL_COMMENT) { return strip(text, HaxeCommenter.SINGLE_LINE_PREFIX, null); } if (elementType == MML_COMMENT) { text = HaxeStringUtil.terminateAt(text, '\n'); return strip(text.trim(), HaxeCommenter.BLOCK_COMMENT_PREFIX, HaxeCommenter.BLOCK_COMMENT_SUFFIX); } if (elementType == DOC_COMMENT) { text = HaxeStringUtil.terminateAt(text, '\n'); return strip(text, HaxeCommenter.DOC_COMMENT_PREFIX, HaxeCommenter.DOC_COMMENT_SUFFIX); } return text.trim(); } private static String strip(@NotNull String text, @Nullable String prefix, @Nullable String suffix) { String stripped = text.trim(); if (null != prefix) stripped = HaxeStringUtil.stripPrefix(stripped, prefix); if (null != suffix) stripped = HaxeStringUtil.stripSuffix(stripped, suffix); return stripped.trim(); } private static RegionMarker matchRegion(ASTNode node) { if (null == node) { return null; } String text = stripComment(node.getElementType(), node.getText()); if (null == text || text.isEmpty()) { return null; } // Figure out if it matches any of the region patterns. for (RegionDefinition region : COMMENT_REGIONS) { Matcher start = region.startMatcher(text); if (start.matches()) { return new RegionMarker(region, node, start, RegionMarker.Type.START); } Matcher end = region.endMatcher(text); if (end.matches()) { return new RegionMarker(region, node, end, RegionMarker.Type.END); } } return null; } /** * Gather the CC and its expression (if any) as the placeholder. * * @param node The Compiler Conditional node. * @return a placeholder string for code folding. */ @NotNull private static String getCCPlaceholder(ASTNode node) { StringBuilder s = new StringBuilder(); s.append(node.getText()); ASTNode next = node.getTreeNext(); while (null != next && next.getElementType() == PPEXPRESSION) { s.append(next.getText()); next = next.getTreeNext(); } if (0 != s.length()) { s.append(' '); } String placeholder = s.toString(); return placeholder.isEmpty() ? "compiler conditional" : placeholder; } private static RegionMarker matchCCRegion(ASTNode node) { return new RegionMarker(CC_REGION, node, null, RegionMarker.Type.CC); } private static FoldingDescriptor buildCodeBlockFolding(@NotNull ASTNode node) { final ASTNode openBrace = node.getFirstChildNode(); final ASTNode closeBrace = node.getLastChildNode(); return buildBlockFolding(node, openBrace, closeBrace); } private static FoldingDescriptor buildBodyBlockFolding(@NotNull ASTNode node) { final ASTNode openBrace = UsefulPsiTreeUtil.getPrevSiblingSkipWhiteSpacesAndComments(node); final ASTNode closeBrace = UsefulPsiTreeUtil.getNextSiblingSkipWhiteSpacesAndComments(node); return buildBlockFolding(node, openBrace, closeBrace); } private static FoldingDescriptor buildBlockFolding(@NotNull ASTNode node, ASTNode openBrace, ASTNode closeBrace) { TextRange textRange; if (openBrace != null && closeBrace != null && openBrace.getElementType() == PLCURLY && closeBrace.getElementType() == PRCURLY) { textRange = new TextRange(openBrace.getTextRange().getEndOffset(), closeBrace.getStartOffset()); } else { textRange = node.getTextRange(); } if (textRange.getLength() > PLACEHOLDER_TEXT.length()) { return new FoldingDescriptor(node, textRange); } return null; } private static FoldingDescriptor buildRegionFolding(final RegionMarker start, final RegionMarker end) { TextRange range = new TextRange(start.node.getStartOffset(), end.node.getTextRange().getEndOffset()); return new FoldingDescriptor(start.node, range) { @Nullable @Override public String getPlaceholderText() { String s = start.region.getPlaceholder(start.matcher); return null == s ? PLACEHOLDER_TEXT : s; } }; } private static FoldingDescriptor buildCCFolding(final RegionMarker start, final RegionMarker end) { TextRange range = new TextRange(start.node.getStartOffset(), end.node.getTextRange().getStartOffset()); final String placeholder = getCCPlaceholder(start.node); return new FoldingDescriptor(start.node, range) { @Nullable @Override public String getPlaceholderText() { return placeholder; } }; } private static FoldingDescriptor buildImportsFolding(@NotNull ASTNode node) { final ASTNode lastImportNode = findLastImportNode(node); if (!node.equals(lastImportNode)) { return new FoldingDescriptor(node, buildImportsFoldingTextRange(node, lastImportNode)); } return null; } private static TextRange buildImportsFoldingTextRange(ASTNode firstNode, ASTNode lastNode) { ASTNode nodeStartFrom = UsefulPsiTreeUtil.getNextSiblingSkipWhiteSpacesAndComments(firstNode.getFirstChildNode()); if (nodeStartFrom == null) { nodeStartFrom = firstNode; } return new TextRange(nodeStartFrom.getStartOffset(), lastNode.getTextRange().getEndOffset()); } private static boolean isFirstImportStatement(@NotNull ASTNode node) { ASTNode prevNode = UsefulPsiTreeUtil.getPrevSiblingSkipWhiteSpacesAndComments(node); return prevNode == null || !isImportOrUsingStatement(prevNode.getElementType()); } private static ASTNode findLastImportNode(@NotNull ASTNode node) { ASTNode lastImportNode = node; ASTNode nextNode = UsefulPsiTreeUtil.getNextSiblingSkipWhiteSpacesAndComments(node); while (nextNode != null && isImportOrUsingStatement(nextNode.getElementType())) { lastImportNode = nextNode; nextNode = UsefulPsiTreeUtil.getNextSiblingSkipWhiteSpacesAndComments(nextNode); } if (lastImportNode.getElementType() == WHITE_SPACE) { lastImportNode = lastImportNode.getTreePrev(); } return lastImportNode; } private static boolean isImportOrUsingStatement(IElementType type) { return type == IMPORT_STATEMENT || type == USING_STATEMENT; } @Nullable @Override public String getPlaceholderText(@NotNull ASTNode node) { return PLACEHOLDER_TEXT; } @Override public boolean isCollapsedByDefault(@NotNull ASTNode node) { return false; } }
Add C#-style region markers as well.
src/common/com/intellij/plugins/haxe/ide/folding/HaxeFoldingBuilder.java
Add C#-style region markers as well.
<ide><path>rc/common/com/intellij/plugins/haxe/ide/folding/HaxeFoldingBuilder.java <ide> "^}"+WS+"?end"+WS+"*region("+WS+"*(.*))?$", <ide> (matcher)->matcher.group(1)); <ide> private static final RegionDefinition PLUGIN_STYLE = new RegionDefinition("^region"+WS+"*(.*)?$", <del> "^end"+WS+"*region"+WS+"*(.*)?$", (matcher)->matcher.group(1)); <del> private static final RegionDefinition COMMENT_REGIONS[] = { FD_STYLE, PLUGIN_STYLE }; <add> "^end"+WS+"*region"+WS+"*(.*)?$", <add> (matcher)->matcher.group(1)); <add> private static final RegionDefinition C_SHARP_STYLE = new RegionDefinition("^#"+WS+"*region"+WS+"+(.*)$", <add> "^#"+WS+"?end"+WS+"*region("+WS+"*(.*))?$", <add> (matcher)->matcher.group(1)); <add> private static final RegionDefinition COMMENT_REGIONS[] = { FD_STYLE, PLUGIN_STYLE, C_SHARP_STYLE }; <ide> <ide> private static final RegionDefinition CC_REGION = new RegionDefinition("#", "#", null); <ide> <ide> } <ide> <ide> private static RegionMarker peekUpStack(List<RegionMarker> list, int n) { <del> int current = 0; <del> for (RegionMarker marker : list) { <del> if (current == n) { <del> return marker; <del> } <del> current++; <del> } <del> return null; <add> return n >= 0 && n < list.size() ? list.get(n) : null; <ide> } <ide> <ide> private static void buildMarkerRegions(List<FoldingDescriptor> descriptors, List<RegionMarker> regionMarkers) {
Java
lgpl-2.1
6acb94efcf821aec68041056ccee14e2d376f00f
0
xtremexp/UT4Converter
package org.xtx.ut4converter.t3d; import org.xtx.ut4converter.MapConverter; import org.xtx.ut4converter.tools.Geometry; public class T3DTrigger extends T3DBrush { private Boolean bInitiallyActive; private Boolean bTriggerOnceOnly; private String classProximityType; private Float damageThreshold; private Float repeatTriggerTime; private Float reRriggerDelay = 1f; private TriggerType triggerType = TriggerType.TT_AnyProximity; private String message; /** * UE1/UE2 * * @author XtremeXp * */ enum TriggerType { TT_AnyProximity, TT_Shoot, TT_ClassProximity, TT_PawnProximity, TT_PlayerProximity, TT_HumanPlayerProximity, TT_LivePlayerProximity, /** * Unreal 2 - Trigger activated by using it */ TT_USE } public T3DTrigger(MapConverter mc, String t3dClass) { super(mc, T3DBrush.BrushClass.TriggerVolume.toString()); collisionHeight = 40d; collisionRadius = 40d; } @Override public void convert() { polyList = Geometry.createCylinder(collisionRadius, collisionHeight, 8); super.convert(); } @Override public boolean analyseT3DData(String line) { if (line.startsWith("TriggerType=")) { triggerType = TriggerType.valueOf(T3DUtils.getString(line)); } else if (line.startsWith("bInitiallyActive=")) { bInitiallyActive = Boolean.getBoolean((T3DUtils.getString(line))); } else if (line.startsWith("ClassProximityType=")) { classProximityType = T3DUtils.getString(line); } else if (line.startsWith("ReTriggerDelay=")) { reRriggerDelay = T3DUtils.getFloat(line); } else if (line.startsWith("RepeatTriggerTime=")) { repeatTriggerTime = T3DUtils.getFloat(line); } else if (line.startsWith("Message=")) { message = T3DUtils.getString(line); } else if (line.startsWith("DamageThreshold=")) { damageThreshold = T3DUtils.getFloat(line); } return super.analyseT3DData(line); } }
src/main/java/org/xtx/ut4converter/t3d/T3DTrigger.java
package org.xtx.ut4converter.t3d; import org.xtx.ut4converter.MapConverter; import org.xtx.ut4converter.tools.Geometry; public class T3DTrigger extends T3DBrush { Boolean bInitiallyActive; Boolean bTriggerOnceOnly; String classProximityType; Float damageThreshold; Float repeatTriggerTime; Float reRriggerDelay = 1f; TriggerType triggerType = TriggerType.TT_AnyProximity; String message; /** * UE1/UE2 * * @author XtremeXp * */ enum TriggerType { TT_AnyProximity, TT_Shoot, TT_ClassProximity, TT_PawnProximity, TT_PlayerProximity, TT_HumanPlayerProximity, TT_LivePlayerProximity } public T3DTrigger(MapConverter mc, String t3dClass) { super(mc, T3DBrush.BrushClass.TriggerVolume.toString()); collisionHeight = 40d; collisionRadius = 40d; } @Override public void convert() { polyList = Geometry.createCylinder(collisionRadius, collisionHeight, 8); super.convert(); } @Override public boolean analyseT3DData(String line) { if (line.startsWith("TriggerType=")) { triggerType = TriggerType.valueOf(T3DUtils.getString(line)); } else if (line.startsWith("bInitiallyActive=")) { bInitiallyActive = Boolean.getBoolean((T3DUtils.getString(line))); } else if (line.startsWith("ClassProximityType=")) { classProximityType = T3DUtils.getString(line); } else if (line.startsWith("ReTriggerDelay=")) { reRriggerDelay = T3DUtils.getFloat(line); } else if (line.startsWith("RepeatTriggerTime=")) { repeatTriggerTime = T3DUtils.getFloat(line); } else if (line.startsWith("Message=")) { message = T3DUtils.getString(line); } else if (line.startsWith("DamageThreshold=")) { damageThreshold = T3DUtils.getFloat(line); } return super.analyseT3DData(line); } }
[u2] - fix TT_USE not supported
src/main/java/org/xtx/ut4converter/t3d/T3DTrigger.java
[u2] - fix TT_USE not supported
<ide><path>rc/main/java/org/xtx/ut4converter/t3d/T3DTrigger.java <ide> <ide> public class T3DTrigger extends T3DBrush { <ide> <del> Boolean bInitiallyActive; <del> Boolean bTriggerOnceOnly; <del> String classProximityType; <del> Float damageThreshold; <del> Float repeatTriggerTime; <del> Float reRriggerDelay = 1f; <del> TriggerType triggerType = TriggerType.TT_AnyProximity; <del> String message; <add> private Boolean bInitiallyActive; <add> private Boolean bTriggerOnceOnly; <add> private String classProximityType; <add> private Float damageThreshold; <add> private Float repeatTriggerTime; <add> private Float reRriggerDelay = 1f; <add> private TriggerType triggerType = TriggerType.TT_AnyProximity; <add> private String message; <ide> <ide> /** <ide> * UE1/UE2 <ide> */ <ide> enum TriggerType { <ide> TT_AnyProximity, TT_Shoot, TT_ClassProximity, TT_PawnProximity, TT_PlayerProximity, <del> TT_HumanPlayerProximity, TT_LivePlayerProximity <add> TT_HumanPlayerProximity, TT_LivePlayerProximity, <add> /** <add> * Unreal 2 - Trigger activated by using it <add> */ <add> TT_USE <ide> } <ide> <ide> public T3DTrigger(MapConverter mc, String t3dClass) {
Java
apache-2.0
8b505135732895c100a6259f4771ac550ea002ea
0
tl-its-umich-edu/sakai,tl-its-umich-edu/sakai,duke-compsci290-spring2016/sakai,Fudan-University/sakai,whumph/sakai,joserabal/sakai,introp-software/sakai,lorenamgUMU/sakai,buckett/sakai-gitflow,rodriguezdevera/sakai,clhedrick/sakai,conder/sakai,puramshetty/sakai,ouit0408/sakai,lorenamgUMU/sakai,introp-software/sakai,introp-software/sakai,bzhouduke123/sakai,hackbuteer59/sakai,liubo404/sakai,Fudan-University/sakai,udayg/sakai,ktakacs/sakai,rodriguezdevera/sakai,pushyamig/sakai,ktakacs/sakai,willkara/sakai,joserabal/sakai,bkirschn/sakai,hackbuteer59/sakai,whumph/sakai,clhedrick/sakai,clhedrick/sakai,wfuedu/sakai,surya-janani/sakai,clhedrick/sakai,buckett/sakai-gitflow,buckett/sakai-gitflow,clhedrick/sakai,frasese/sakai,willkara/sakai,colczr/sakai,wfuedu/sakai,OpenCollabZA/sakai,pushyamig/sakai,bkirschn/sakai,duke-compsci290-spring2016/sakai,ktakacs/sakai,bzhouduke123/sakai,OpenCollabZA/sakai,Fudan-University/sakai,colczr/sakai,liubo404/sakai,liubo404/sakai,kwedoff1/sakai,pushyamig/sakai,surya-janani/sakai,puramshetty/sakai,udayg/sakai,wfuedu/sakai,rodriguezdevera/sakai,udayg/sakai,puramshetty/sakai,kingmook/sakai,frasese/sakai,tl-its-umich-edu/sakai,introp-software/sakai,ouit0408/sakai,willkara/sakai,tl-its-umich-edu/sakai,zqian/sakai,OpenCollabZA/sakai,joserabal/sakai,ktakacs/sakai,wfuedu/sakai,whumph/sakai,lorenamgUMU/sakai,ouit0408/sakai,bzhouduke123/sakai,kingmook/sakai,rodriguezdevera/sakai,buckett/sakai-gitflow,noondaysun/sakai,bkirschn/sakai,tl-its-umich-edu/sakai,introp-software/sakai,joserabal/sakai,lorenamgUMU/sakai,willkara/sakai,surya-janani/sakai,hackbuteer59/sakai,kingmook/sakai,colczr/sakai,duke-compsci290-spring2016/sakai,wfuedu/sakai,joserabal/sakai,kingmook/sakai,puramshetty/sakai,Fudan-University/sakai,liubo404/sakai,surya-janani/sakai,puramshetty/sakai,rodriguezdevera/sakai,kingmook/sakai,frasese/sakai,udayg/sakai,noondaysun/sakai,wfuedu/sakai,kwedoff1/sakai,hackbuteer59/sakai,ouit0408/sakai,OpenCollabZA/sakai,zqian/sakai,colczr/sakai,bzhouduke123/sakai,colczr/sakai,conder/sakai,rodriguezdevera/sakai,whumph/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,whumph/sakai,OpenCollabZA/sakai,liubo404/sakai,rodriguezdevera/sakai,kwedoff1/sakai,duke-compsci290-spring2016/sakai,ouit0408/sakai,bkirschn/sakai,bkirschn/sakai,ktakacs/sakai,OpenCollabZA/sakai,zqian/sakai,wfuedu/sakai,pushyamig/sakai,conder/sakai,joserabal/sakai,willkara/sakai,noondaysun/sakai,frasese/sakai,bzhouduke123/sakai,tl-its-umich-edu/sakai,pushyamig/sakai,udayg/sakai,conder/sakai,whumph/sakai,kingmook/sakai,zqian/sakai,conder/sakai,bzhouduke123/sakai,lorenamgUMU/sakai,Fudan-University/sakai,noondaysun/sakai,conder/sakai,ouit0408/sakai,frasese/sakai,duke-compsci290-spring2016/sakai,bzhouduke123/sakai,zqian/sakai,puramshetty/sakai,clhedrick/sakai,Fudan-University/sakai,ktakacs/sakai,udayg/sakai,ktakacs/sakai,colczr/sakai,Fudan-University/sakai,OpenCollabZA/sakai,surya-janani/sakai,liubo404/sakai,wfuedu/sakai,pushyamig/sakai,buckett/sakai-gitflow,ktakacs/sakai,rodriguezdevera/sakai,OpenCollabZA/sakai,kingmook/sakai,puramshetty/sakai,lorenamgUMU/sakai,frasese/sakai,pushyamig/sakai,joserabal/sakai,hackbuteer59/sakai,noondaysun/sakai,frasese/sakai,willkara/sakai,introp-software/sakai,bzhouduke123/sakai,noondaysun/sakai,introp-software/sakai,liubo404/sakai,surya-janani/sakai,buckett/sakai-gitflow,whumph/sakai,duke-compsci290-spring2016/sakai,udayg/sakai,zqian/sakai,hackbuteer59/sakai,zqian/sakai,lorenamgUMU/sakai,frasese/sakai,introp-software/sakai,pushyamig/sakai,duke-compsci290-spring2016/sakai,willkara/sakai,kwedoff1/sakai,noondaysun/sakai,tl-its-umich-edu/sakai,noondaysun/sakai,zqian/sakai,conder/sakai,puramshetty/sakai,kwedoff1/sakai,Fudan-University/sakai,liubo404/sakai,hackbuteer59/sakai,buckett/sakai-gitflow,conder/sakai,ouit0408/sakai,kwedoff1/sakai,surya-janani/sakai,bkirschn/sakai,whumph/sakai,colczr/sakai,kingmook/sakai,udayg/sakai,hackbuteer59/sakai,colczr/sakai,surya-janani/sakai,kwedoff1/sakai,bkirschn/sakai,kwedoff1/sakai,joserabal/sakai,lorenamgUMU/sakai,clhedrick/sakai,bkirschn/sakai,clhedrick/sakai,buckett/sakai-gitflow,willkara/sakai,duke-compsci290-spring2016/sakai
/* * Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University, * Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation * * Licensed under the Educational Community License Version 1.0 (the "License"); * By obtaining, using and/or copying this Original Work, you agree that you have read, * understand, and will comply with the terms and conditions of the Educational Community License. * You may obtain a copy of the License at: * * http://cvs.sakaiproject.org/licenses/license_1_0.html * * 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. */ package org.sakaiproject.tool.assessment.ui.bean.delivery; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.context.ExternalContext; import javax.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.tool.assessment.data.dao.assessment.AssessmentAccessControl; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedSectionData; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedItemData; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedItemText; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedSecuredIPAddress; import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingData; import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData; import org.sakaiproject.tool.assessment.data.dao.grading.MediaData; import org.sakaiproject.tool.assessment.facade.AgentFacade; import org.sakaiproject.tool.assessment.facade.PublishedAssessmentFacade; import org.sakaiproject.tool.assessment.services.GradingService; import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService; import org.sakaiproject.tool.assessment.ui.bean.util.Validator; import org.sakaiproject.tool.assessment.ui.listener.delivery.DeliveryActionListener; import org.sakaiproject.tool.assessment.ui.listener.delivery.SubmitToGradingActionListener; import org.sakaiproject.tool.assessment.ui.listener.delivery.UpdateTimerListener; import org.sakaiproject.tool.assessment.ui.listener.select.SelectActionListener; import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil; import org.sakaiproject.tool.assessment.util.MimeTypesLocator; import org.sakaiproject.spring.SpringBeanLocator; import org.sakaiproject.tool.assessment.ui.web.session.SessionUtil; import org.sakaiproject.tool.assessment.ui.bean.shared.PersonBean; //cwen import org.sakaiproject.api.kernel.tool.cover.ToolManager; import org.sakaiproject.api.kernel.tool.Placement; // note: we should wrap above dependency in a backend service--esmiley /** * * @author casong * @author [email protected] added agentState * $Id$ * * Used to be org.navigoproject.ui.web.asi.delivery.XmlDeliveryForm.java */ public class DeliveryBean implements Serializable { private static Log log = LogFactory.getLog(DeliveryBean.class); private String assessmentId; private String assessmentTitle; private ArrayList markedForReview; private ArrayList blankItems; private ArrayList markedForReviewIdents; private ArrayList blankItemIdents; private boolean reviewMarked; private boolean reviewAll; private boolean reviewBlank; private int itemIndex; private int size; private String action; private Date beginTime; private String endTime; private String currentTime; private String multipleAttempts; private String timeOutSubmission; private String submissionTicket; private String timeElapse; private String username; private int sectionIndex; private boolean previous; private String duration; private String url; private String confirmation; private String outcome; //Settings private String questionLayout; private String navigation; private String numbering; private String feedback; private String noFeedback; private String statistics; private String creatorName; private FeedbackComponent feedbackComponent; private boolean feedbackOnDate; private String errorMessage; private SettingsDeliveryBean settings; private java.util.Date dueDate; private boolean statsAvailable; private boolean submitted; private boolean graded; private String graderComment; private String rawScore; private String grade; private java.util.Date submissionDate; private java.util.Date submissionTime; private String image; private boolean hasImage; private String instructorMessage; private String courseName; private String timeLimit; private int timeLimit_hour; private int timeLimit_minute; private ContentsDeliveryBean tableOfContents; private String previewMode; private String previewAssessment; private String notPublished; private String submissionId; private String submissionMessage; private String instructorName; private ContentsDeliveryBean pageContents; private int submissionsRemaining; private boolean forGrade; private String password; // For paging private int partIndex; private int questionIndex; private boolean next_page; private boolean reload = true; // daisy added these for SelectActionListener private boolean notTakeable = true; private boolean pastDue; private long subTime; private long raw; private String takenHours; private String takenMinutes; private AssessmentGradingData adata; private PublishedAssessmentFacade publishedAssessment; private java.util.Date feedbackDate; private String feedbackDelivery; private String showScore; private boolean hasTimeLimit; // daisyf added for servlet Login.java, to support anonymous login with // publishedUrl private boolean anonymousLogin = false; private String contextPath; private boolean initAgentAccessString = false; /** Use serialVersionUID for interoperability. */ private final static long serialVersionUID = -1090852048737428722L; private boolean showStudentScore; // lydial added for allowing studentScore view for random draw parts private boolean forGrading; // to reuse deliveryActionListener for grading pages // SAM-387 // esmiley added to track if timer has been started in timed assessments private boolean timeRunning; // SAM-535 // esmiley added to track JavaScript private String javaScriptEnabledCheck; //cwen private String siteId; // daisy added this for SAK-1764 private boolean reviewAssessment=false; // daisy added back for SAK-2738 private boolean accessViaUrl=false; // this instance tracks if the Agent is taking a test via URL, as well as // current agent string (if assigned). SAK-1927: esmiley private AgentFacade deliveryAgent; /** * Creates a new DeliveryBean object. */ public DeliveryBean() { deliveryAgent = new AgentFacade(); } /** * * * @return */ public int getItemIndex() { return this.itemIndex; } /** * * * @param itemIndex */ public void setItemIndex(int itemIndex) { this.itemIndex = itemIndex; } /** * * * @return */ public int getSize() { return this.size; } /** * * * @param size */ public void setSize(int size) { this.size = size; } /** * * * @return */ public String getAssessmentId() { return assessmentId; } /** * * * @param assessmentId */ public void setAssessmentId(String assessmentId) { this.assessmentId = assessmentId; } /** * * * @return */ public ArrayList getMarkedForReview() { return markedForReview; } /** * * * @param markedForReview */ public void setMarkedForReview(ArrayList markedForReview) { this.markedForReview = markedForReview; } /** * * * @return */ public boolean getReviewMarked() { return this.reviewMarked; } /** * * * @param reviewMarked */ public void setReviewMarked(boolean reviewMarked) { this.reviewMarked = reviewMarked; } /** * * * @return */ public boolean getReviewAll() { return this.reviewAll; } /** * * * @param reviewAll */ public void setReviewAll(boolean reviewAll) { this.reviewAll = reviewAll; } /** * * * @return */ public String getAction() { return this.action; } /** * * * @param action */ public void setAction(String action) { this.action = action; } /** * * * @return */ public Date getBeginTime() { return beginTime; } /** * * * @param beginTime */ public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } /** * * * @return */ public String getEndTime() { return endTime; } /** * * * @param endTime */ public void setEndTime(String endTime) { this.endTime = endTime; } /** * * * @return */ public String getCurrentTime() { return this.currentTime; } /** * * * @param currentTime */ public void setCurrentTime(String currentTime) { this.currentTime = currentTime; } /** * * * @return */ public String getMultipleAttempts() { return this.multipleAttempts; } /** * * * @param multipleAttempts */ public void setMultipleAttempts(String multipleAttempts) { this.multipleAttempts = multipleAttempts; } /** * * * @return */ public String getTimeOutSubmission() { return this.timeOutSubmission; } /** * * * @param timeOutSubmission */ public void setTimeOutSubmission(String timeOutSubmission) { this.timeOutSubmission = timeOutSubmission; } /** * * * @return */ public java.util.Date getSubmissionTime() { return submissionTime; } /** * * * @param submissionTime */ public void setSubmissionTime(java.util.Date submissionTime) { this.submissionTime = submissionTime; } /** * * * @return */ public String getTimeElapse() { return timeElapse; } /** * * * @param timeElapse */ public void setTimeElapse(String timeElapse) { this.timeElapse = timeElapse; } /** * * * @return */ public String getSubmissionTicket() { return submissionTicket; } /** * * * @param submissionTicket */ public void setSubmissionTicket(String submissionTicket) { this.submissionTicket = submissionTicket; } /** * * * @return */ public int getDisplayIndex() { return this.itemIndex + 1; } /** * * * @return */ public String getUsername() { return username; } /** * * * @param username */ public void setUsername(String username) { this.username = username; } /** * * * @return */ public String getAssessmentTitle() { return assessmentTitle; } /** * * * @param assessmentTitle */ public void setAssessmentTitle(String assessmentTitle) { this.assessmentTitle = assessmentTitle; } /** * * * @return */ public ArrayList getBlankItems() { return this.blankItems; } /** * * * @param blankItems */ public void setBlankItems(ArrayList blankItems) { this.blankItems = blankItems; } /** * * * @return */ public boolean getReviewBlank() { return reviewBlank; } /** * * * @param reviewBlank */ public void setReviewBlank(boolean reviewBlank) { this.reviewBlank = reviewBlank; } /** * * * @return */ public ArrayList getMarkedForReviewIdents() { return markedForReviewIdents; } /** * * * @param markedForReviewIdents */ public void setMarkedForReviewIdents(ArrayList markedForReviewIdents) { this.markedForReviewIdents = markedForReviewIdents; } /** * * * @return */ public ArrayList getBlankItemIdents() { return blankItemIdents; } /** * * * @param blankItemIdents */ public void setBlankItemIdents(ArrayList blankItemIdents) { this.blankItemIdents = blankItemIdents; } /** * * * @return */ public int getSectionIndex() { return this.sectionIndex; } /** * * * @param sectionIndex */ public void setSectionIndex(int sectionIndex) { this.sectionIndex = sectionIndex; } /** * * * @return */ public boolean getPrevious() { return previous; } /** * * * @param previous */ public void setPrevious(boolean previous) { this.previous = previous; } //Settings public String getQuestionLayout() { return questionLayout; } /** * * * @param questionLayout */ public void setQuestionLayout(String questionLayout) { this.questionLayout = questionLayout; } /** * * * @return */ public String getNavigation() { return navigation; } /** * * * @param navigation */ public void setNavigation(String navigation) { this.navigation = navigation; } /** * * * @return */ public String getNumbering() { return numbering; } /** * * * @param numbering */ public void setNumbering(String numbering) { this.numbering = numbering; } /** * * * @return */ public String getFeedback() { return feedback; } /** * * * @param feedback */ public void setFeedback(String feedback) { this.feedback = feedback; } /** * * * @return */ public String getNoFeedback() { return noFeedback; } /** * * * @param noFeedback */ public void setNoFeedback(String noFeedback) { this.noFeedback = noFeedback; } /** * * * @return */ public String getStatistics() { return statistics; } /** * * * @param statistics */ public void setStatistics(String statistics) { this.statistics = statistics; } /** * * * @return */ public FeedbackComponent getFeedbackComponent() { return feedbackComponent; } /** * * * @param feedbackComponent */ public void setFeedbackComponent(FeedbackComponent feedbackComponent) { this.feedbackComponent = feedbackComponent; } /** * Types of feedback in FeedbackComponent: * * SHOW CORRECT SCORE * SHOW STUDENT SCORE * SHOW ITEM LEVEL * SHOW SECTION LEVEL * SHOW GRADER COMMENT * SHOW STATS * SHOW QUESTION * SHOW RESPONSE **/ /** * @return */ public SettingsDeliveryBean getSettings() { return settings; } /** * @param bean */ public void setSettings(SettingsDeliveryBean settings) { this.settings = settings; } /** * @return */ public String getErrorMessage() { return errorMessage; } /** * @param string */ public void setErrorMessage(String string) { errorMessage = string; } /** * @return */ public String getDuration() { return duration; } /** * @param string */ public void setDuration(String string) { duration = string; } /** * @return */ public String getCreatorName() { return creatorName; } /** * @param string */ public void setCreatorName(String string) { creatorName = string; } public java.util.Date getDueDate() { return dueDate; } public void setDueDate(java.util.Date dueDate) { this.dueDate = dueDate; } public boolean isStatsAvailable() { return statsAvailable; } public void setStatsAvailable(boolean statsAvailable) { this.statsAvailable = statsAvailable; } public boolean isSubmitted() { return submitted; } public void setSubmitted(boolean submitted) { this.submitted = submitted; } public boolean isGraded() { return graded; } public void setGraded(boolean graded) { this.graded = graded; } public boolean getFeedbackOnDate() { return feedbackOnDate; } public void setFeedbackOnDate(boolean feedbackOnDate) { this.feedbackOnDate = feedbackOnDate; } public String getGraderComment() { if (graderComment == null) { return ""; } return graderComment; } public void setGraderComment(String newComment) { graderComment = newComment; } public String getRawScore() { return rawScore; } public void setRawScore(String rawScore) { this.rawScore = rawScore; } public long getRaw() { return raw; } public void setRaw(long raw) { this.raw = raw; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public java.util.Date getSubmissionDate() { return submissionDate; } public void setSubmissionDate(java.util.Date submissionDate) { this.submissionDate = submissionDate; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public boolean isHasImage() { return hasImage; } public void setHasImage(boolean hasImage) { this.hasImage = hasImage; } public String getInstructorMessage() { return instructorMessage; } public void setInstructorMessage(String instructorMessage) { this.instructorMessage = instructorMessage; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getTimeLimit() { return timeLimit; } public void setTimeLimit(String timeLimit) { this.timeLimit = timeLimit; } public int getTimeLimit_hour() { return timeLimit_hour; } public void setTimeLimit_hour(int timeLimit_hour) { this.timeLimit_hour = timeLimit_hour; } public int getTimeLimit_minute() { return timeLimit_minute; } public void setTimeLimit_minute(int timeLimit_minute) { this.timeLimit_minute = timeLimit_minute; } /** * Bean with table of contents information and * a list of all the sections in the assessment * which in turn has a list of all the item contents. * @return table of contents */ public ContentsDeliveryBean getTableOfContents() { return tableOfContents; } /** * Bean with table of contents information and * a list of all the sections in the assessment * which in turn has a list of all the item contents. * @param tableOfContents table of contents */ public void setTableOfContents(ContentsDeliveryBean tableOfContents) { this.tableOfContents = tableOfContents; } /** * Bean with a list of all the sections in the current page * which in turn has a list of all the item contents for the page. * * This is like the table of contents, but the selections are restricted to * that on one page. * * Since these properties are on a page delivery basis--if: * 1. there is only one item per page the list of items will * contain one item and the list of parts will return one part, or if-- * * 2. there is one part per page the list of items will be that * for that part only and there will only be one part, however-- * * 3. if it is all parts and items on a single page there * will be a list of all parts and items. * * @return ContentsDeliveryBean */ public ContentsDeliveryBean getPageContents() { return pageContents; } /** * Bean with a list of all the sections in the current page * which in turn has a list of all the item contents for the page. * * Since these properties are on a page delivery basis--if: * 1. there is only one item per page the list of items will * contain one item and the list of parts will return one part, or if-- * * 2. there is one part per page the list of items will be that * for that part only and there will only be one part, however-- * * 3. if it is all parts and items on a single page there * will be a list of all parts and items. * * @param pageContents ContentsDeliveryBean */ public void setPageContents(ContentsDeliveryBean pageContents) { this.pageContents = pageContents; } /** * track whether delivery is "live" with update of database allowed and * whether the Ui components are disabled. * @return true if preview only */ public String getPreviewMode() { return Validator.check(previewMode, "false"); } /** * track whether delivery is "live" with update of database allowed and * whether the UI components are disabled. * @param previewMode true if preview only */ public void setPreviewMode(boolean previewMode) { this.previewMode = new Boolean(previewMode).toString(); } public String getPreviewAssessment() { return previewAssessment; } public void setPreviewAssessment(String previewAssessment) { this.previewAssessment = previewAssessment; } public String getNotPublished() { return notPublished; } public void setNotPublished(String notPublished) { this.notPublished = notPublished; } public String getSubmissionId() { return submissionId; } public void setSubmissionId(String submissionId) { this.submissionId = submissionId; } public String getSubmissionMessage() { return submissionMessage; } public void setSubmissionMessage(String submissionMessage) { this.submissionMessage = submissionMessage; } public int getSubmissionsRemaining() { return submissionsRemaining; } public void setSubmissionsRemaining(int submissionsRemaining) { this.submissionsRemaining = submissionsRemaining; } public String getInstructorName() { return instructorName; } public void setInstructorName(String instructorName) { this.instructorName = instructorName; } public boolean getForGrade() { return forGrade; } public void setForGrade(boolean newfor) { forGrade = newfor; } public String submitForGrade() { SessionUtil.setSessionTimeout(FacesContext.getCurrentInstance(), this, false); forGrade = true; SubmitToGradingActionListener listener = new SubmitToGradingActionListener(); listener.processAction(null); String returnValue="submitAssessment"; if (getAccessViaUrl()) // this is for accessing via published url { returnValue="anonymousThankYou"; } forGrade = false; SelectActionListener l2 = new SelectActionListener(); l2.processAction(null); reload = true; return returnValue; } public String saveAndExit() { FacesContext context = FacesContext.getCurrentInstance(); SessionUtil.setSessionTimeout(context, this, false); log.debug("***DeliverBean.saveAndEXit face context =" + context); // If this was automatically triggered by running out of time, // check for autosubmit, and do it if so. if (timeOutSubmission != null && timeOutSubmission.equals("true")) { if (getSettings().getAutoSubmit()) { submitForGrade(); return "timeout"; } } forGrade = false; SubmitToGradingActionListener listener = new SubmitToGradingActionListener(); listener.processAction(null); String returnValue = "select"; if (timeOutSubmission != null && timeOutSubmission.equals("true")) { returnValue = "timeout"; } if (getAccessViaUrl()) { // if this is access via url, display quit message log.debug("**anonymous login, go to quit"); returnValue = "anonymousQuit"; } SelectActionListener l2 = new SelectActionListener(); l2.processAction(null); reload = true; return returnValue; } public String next_page() { if (getSettings().isFormatByPart()) { partIndex++; } if (getSettings().isFormatByQuestion()) { questionIndex++; } forGrade = false; if (! ("true").equals(previewAssessment)) { SubmitToGradingActionListener listener = new SubmitToGradingActionListener(); listener.processAction(null); } DeliveryActionListener l2 = new DeliveryActionListener(); l2.processAction(null); reload = false; return "takeAssessment"; } public String previous() { if (getSettings().isFormatByPart()) { partIndex--; } if (getSettings().isFormatByQuestion()) { questionIndex--; } forGrade = false; if (! ("true").equals(previewAssessment)) { SubmitToGradingActionListener listener = new SubmitToGradingActionListener(); listener.processAction(null); } DeliveryActionListener l2 = new DeliveryActionListener(); l2.processAction(null); reload = false; return "takeAssessment"; } // this is the PublishedAccessControl.finalPageUrl public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getConfirmation() { return confirmation; } public void setConfirmation(String confirmation) { this.confirmation = confirmation; } /** * if required, assessment password * @return password */ public String getPassword() { return password; } /** * if required, assessment password * @param string assessment password */ public void setPassword(String string) { password = string; } public String validatePassword() { log.debug("**** username=" + username); log.debug("**** password=" + password); log.debug("**** setting username=" + getSettings().getUsername()); log.debug("**** setting password=" + getSettings().getPassword()); if (password == null || username == null) { return "passwordAccessError"; } if (password.equals(getSettings().getPassword()) && username.equals(getSettings().getUsername())) { // in post 2.1, clicking at Begin Assessment takes users to the // 1st question. return "takeAssessment"; } else { return "passwordAccessError"; } } public String validateIP() { String thisIp = ( (javax.servlet.http.HttpServletRequest) FacesContext. getCurrentInstance().getExternalContext().getRequest()). getRemoteAddr(); Iterator addresses = getSettings().getIpAddresses().iterator(); while (addresses.hasNext()) { String next = ( (PublishedSecuredIPAddress) addresses.next()). getIpAddress(); if (next != null && next.indexOf("*") > -1) { next = next.substring(0, next.indexOf("*")); } if (next == null || next.trim().equals("") || thisIp.trim().startsWith(next.trim())) { // in post 2.1, clicking at Begin Assessment takes users to the // 1st question. return "takeAssessment"; } } return "ipAccessError"; } public String validate() { try { String results = ""; if (!getSettings().getUsername().equals("")) { results = validatePassword(); } if (!results.equals("passwordAccessError") && getSettings().getIpAddresses() != null && !getSettings().getIpAddresses().isEmpty()) { results = validateIP(); } if (results.equals("")) { // in post 2.1, clicking at Begin Assessment takes users to the // 1st question. return "takeAssessment"; } return results; } catch (Exception e) { e.printStackTrace(); return "accessError"; } } public String pvalidate() { // in post 2.1, clicking at Begin Assessment takes users to the // 1st question. return "takeAssessment"; } // Skipped paging methods public int getPartIndex() { return partIndex; } public void setPartIndex(int newindex) { partIndex = newindex; } public int getQuestionIndex() { return questionIndex; } public void setQuestionIndex(int newindex) { questionIndex = newindex; } public boolean getContinue() { return next_page; } public void setContinue(boolean docontinue) { next_page = docontinue; } public boolean getReload() { return reload; } public void setReload(boolean doreload) { reload = doreload; } // Store for paging public AssessmentGradingData getAssessmentGrading() { return adata; } public void setAssessmentGrading(AssessmentGradingData newdata) { adata = newdata; } private byte[] getMediaStream(String mediaLocation) { FileInputStream mediaStream = null; FileInputStream mediaStream2 = null; byte[] mediaByte = new byte[0]; try { int i = 0; int size = 0; mediaStream = new FileInputStream(mediaLocation); if (mediaStream != null) { while ( (i = mediaStream.read()) != -1) { size++; } } mediaStream2 = new FileInputStream(mediaLocation); mediaByte = new byte[size]; mediaStream2.read(mediaByte, 0, size); FileOutputStream out = new FileOutputStream("/tmp/test.txt"); out.write(mediaByte); } catch (FileNotFoundException ex) { log.debug("file not found=" + ex.getMessage()); } catch (IOException ex) { log.debug("io exception=" + ex.getMessage()); } finally { try { mediaStream.close(); } catch (IOException ex1) { } } return mediaByte; } /** * This method is used by jsf/delivery/deliveryFileUpload.jsp * <corejsf:upload * target="/jsf/upload_tmp/assessment#{delivery.assessmentId}/ * question#{question.itemData.itemId}/admin" * valueChangeListener="#{delivery.addMediaToItemGrading}" /> */ public String addMediaToItemGrading(javax.faces.event.ValueChangeEvent e) { GradingService gradingService = new GradingService(); PublishedAssessmentService publishedService = new PublishedAssessmentService(); PublishedAssessmentFacade publishedAssessment = publishedService. getPublishedAssessment(assessmentId); PersonBean person = (PersonBean) ContextUtil.lookupBean("person"); String agent = person.getId(); // 1. create assessmentGrading if it is null if (this.adata == null) { adata = new AssessmentGradingData(); adata.setAgentId(agent); adata.setPublishedAssessment(publishedAssessment.getData()); log.debug("***1a. addMediaToItemGrading, getForGrade()=" + getForGrade()); adata.setForGrade(new Boolean(getForGrade())); adata.setAttemptDate(getBeginTime()); gradingService.saveOrUpdateAssessmentGrading(adata); } log.info("***1b. addMediaToItemGrading, adata=" + adata); // 2. format of the media location is: assessmentXXX/questionXXX/agentId/myfile String mediaLocation = (String) e.getNewValue(); log.debug("***2a. addMediaToItemGrading, new value =" + mediaLocation); // 3. get the questionId (which is the PublishedItemData.itemId) int assessmentIndex = mediaLocation.indexOf("assessment"); int questionIndex = mediaLocation.indexOf("question"); int agentIndex = mediaLocation.indexOf("/", questionIndex + 8); //cwen if(agentIndex < 0 ) { agentIndex = mediaLocation.indexOf("\\", questionIndex + 8); } String pubAssessmentId = mediaLocation.substring(assessmentIndex + 10, questionIndex - 1); String questionId = mediaLocation.substring(questionIndex + 8, agentIndex); log.debug("***3a. addMediaToItemGrading, questionId =" + questionId); log.debug("***3b. addMediaToItemGrading, assessmentId =" + assessmentId); // 4. prepare itemGradingData and attach it to assessmentGarding PublishedItemData item = publishedService.loadPublishedItem(questionId); log.debug("***4a. addMediaToItemGrading, item =" + item); log.debug("***4b. addMediaToItemGrading, itemTextArray =" + item.getItemTextArray()); log.debug("***4c. addMediaToItemGrading, itemText(0) =" + item.getItemTextArray().get(0)); // there is only one text in audio question PublishedItemText itemText = (PublishedItemText) item. getItemTextArraySorted().get(0); ItemGradingData itemGradingData = getItemGradingData(questionId); boolean newItemGradingData = false; if (itemGradingData == null) { newItemGradingData = true; itemGradingData = new ItemGradingData(); itemGradingData.setAssessmentGrading(adata); itemGradingData.setPublishedItem(item); itemGradingData.setPublishedItemText(itemText); itemGradingData.setSubmittedDate(new Date()); itemGradingData.setAgentId(agent); itemGradingData.setOverrideScore(new Float(0)); } setAssessmentGrading(adata); // 5. save AssessmentGardingData with ItemGardingData Set itemDataSet = adata.getItemGradingSet(); log.debug("***5a. addMediaToItemGrading, itemDataSet=" + itemDataSet); if (itemDataSet == null) { itemDataSet = new HashSet(); } itemDataSet.add(itemGradingData); adata.setItemGradingSet(itemDataSet); gradingService.saveOrUpdateAssessmentGrading(adata); log.debug("***5b. addMediaToItemGrading, saved=" + adata); //if media is uploaded, create media record and attach to itemGradingData if (mediaIsValid()) saveMedia(agent, mediaLocation, itemGradingData, gradingService); // 8. do whatever need doing DeliveryActionListener dlistener = new DeliveryActionListener(); // false => do not reset the entire current delivery.pageContents. // we will do it ourselves and only update the question that this media // is attached to dlistener.processAction(null, false); if (newItemGradingData) attachToItemContentBean(itemGradingData, questionId); // 9. do the timer thing Integer timeLimit = null; if (adata != null && adata.getPublishedAssessment() != null && adata.getPublishedAssessment().getAssessmentAccessControl() != null) { timeLimit = adata.getPublishedAssessment().getAssessmentAccessControl(). getTimeLimit(); } if (timeLimit != null && timeLimit.intValue() > 0) { UpdateTimerListener l3 = new UpdateTimerListener(); l3.processAction(null); } reload = true; return "takeAssessment"; } public void saveMedia(String agent, String mediaLocation, ItemGradingData itemGradingData, GradingService gradingService){ // 1. create a media record File media = new File(mediaLocation); byte[] mediaByte = getMediaStream(mediaLocation); String mimeType = MimeTypesLocator.getInstance().getContentType(media); //boolean SAVETODB = MediaData.saveToDB(); boolean SAVETODB = getSaveToDb(); log.debug("**** SAVETODB=" + SAVETODB); MediaData mediaData = null; log.debug("***6a. addMediaToItemGrading, itemGradinDataId=" + itemGradingData.getItemGradingId()); log.debug("***6b. addMediaToItemGrading, publishedItemId=" + ( (PublishedItemData) itemGradingData.getPublishedItem()). getItemId()); if (SAVETODB) { // put the byte[] in mediaData = new MediaData(itemGradingData, mediaByte, new Long(mediaByte.length + ""), mimeType, "description", null, media.getName(), false, false, new Integer(1), agent, new Date(), agent, new Date()); } else { // put the location in mediaData = new MediaData(itemGradingData, null, new Long(mediaByte.length + ""), mimeType, "description", mediaLocation, media.getName(), false, false, new Integer(1), agent, new Date(), agent, new Date()); } Long mediaId = gradingService.saveMedia(mediaData); log.debug("mediaId=" + mediaId); log.debug("***6c. addMediaToItemGrading, media.itemGradinDataId=" + ( (ItemGradingData) mediaData.getItemGradingData()). getItemGradingId()); log.debug("***6d. addMediaToItemGrading, mediaId=" + mediaData.getMediaId()); // 2. store mediaId in itemGradingRecord.answerText log.debug("***7. addMediaToItemGrading, adata=" + adata); itemGradingData.setAnswerText(mediaId + ""); gradingService.saveItemGrading(itemGradingData); } public boolean mediaIsValid() { boolean returnValue =true; // check if file is too big FacesContext context = FacesContext.getCurrentInstance(); ExternalContext external = context.getExternalContext(); Long fileSize = (Long)((ServletContext)external.getContext()).getAttribute("TEMP_FILEUPLOAD_SIZE"); Long maxSize = (Long)((ServletContext)external.getContext()).getAttribute("FILEUPLOAD_SIZE_MAX"); log.info("**** filesize is ="+fileSize); log.info("**** maxsize is ="+maxSize); ((ServletContext)external.getContext()).removeAttribute("TEMP_FILEUPLOAD_SIZE"); if (fileSize!=null){ float fileSize_float = fileSize.floatValue()/1024; int tmp = Math.round(fileSize_float * 10.0f); fileSize_float = (float)tmp / 10.0f; float maxSize_float = maxSize.floatValue()/1024; int tmp0 = Math.round(maxSize_float * 10.0f); maxSize_float = (float)tmp0 / 10.0f; String err1=(String)ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "file_upload_error"); String err2=(String)ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "file_uploaded"); String err3=(String)ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "max_size_allowed"); String err4=(String)ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "upload_again"); String err = err2 + fileSize_float + err3 + maxSize_float + err4; context.addMessage("file_upload_error",new FacesMessage(err1)); context.addMessage("file_upload_error",new FacesMessage(err)); returnValue = false; } return returnValue; } public boolean getNotTakeable() { return notTakeable; } public void setNotTakeable(boolean notTakeable) { this.notTakeable = notTakeable; } public boolean getPastDue() { return pastDue; } public void setPastDue(boolean pastDue) { this.pastDue = pastDue; } public long getSubTime() { return subTime; } public void setSubTime(long newSubTime) { subTime = newSubTime; } public String getSubmissionHours() { return takenHours; } public void setSubmissionHours(String newHours) { takenHours = newHours; } public String getSubmissionMinutes() { return takenMinutes; } public void setSubmissionMinutes(String newMinutes) { takenMinutes = newMinutes; } public PublishedAssessmentFacade getPublishedAssessment() { return publishedAssessment; } public void setPublishedAssessment(PublishedAssessmentFacade publishedAssessment) { this.publishedAssessment = publishedAssessment; } public java.util.Date getFeedbackDate() { return feedbackDate; } public void setFeedbackDate(java.util.Date feedbackDate) { this.feedbackDate = feedbackDate; } public String getFeedbackDelivery() { return feedbackDelivery; } public void setFeedbackDelivery(String feedbackDelivery) { this.feedbackDelivery = feedbackDelivery; } public String getShowScore() { return showScore; } public void setShowScore(String showScore) { this.showScore = showScore; } public boolean getHasTimeLimit() { return hasTimeLimit; } public void setHasTimeLimit(boolean hasTimeLimit) { this.hasTimeLimit = hasTimeLimit; } public String getOutcome() { return outcome; } public void setOutcome(String outcome) { this.outcome = outcome; } public String doit() { return outcome; } /* public ItemGradingData getItemGradingData(String publishedItemId){ ItemGradingData itemGradingData = new ItemGradingData(); if (adata != null){ GradingService service = new GradingService(); itemGradingData = service.getItemGradingData(adata.getAssessmentGradingId().toString(), publishedItemId); if (itemGradingData == null) itemGradingData = new ItemGradingData(); } return itemGradingData; } */ public boolean getAnonymousLogin() { return anonymousLogin; } public void setAnonymousLogin(boolean anonymousLogin) { this.anonymousLogin = anonymousLogin; } public boolean getAccessViaUrl() { return accessViaUrl; } public void setAccessViaUrl(boolean accessViaUrl) { this.accessViaUrl=accessViaUrl; } public ItemGradingData getItemGradingData(String publishedItemId) { ItemGradingData selected = null; if (adata != null) { Set items = adata.getItemGradingSet(); if (items != null) { Iterator iter = items.iterator(); while (iter.hasNext()) { ItemGradingData itemGradingData = (ItemGradingData) iter.next(); String itemPublishedId = itemGradingData.getPublishedItem().getItemId(). toString(); if ( (publishedItemId).equals(itemPublishedId)) { log.debug("*** addMediaToItemGrading, same : found it"); selected = itemGradingData; } else { log.debug("*** addMediaToItemGrading, not the same"); } } log.debug("*** addMediaToItemGrading, publishedItemId =" + publishedItemId); if (selected != null) { log.debug( "*** addMediaToItemGrading, itemGradingData.publishedItemId =" + selected.getPublishedItem().getItemId().toString()); } } } return selected; } public String getContextPath() { return contextPath; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } public boolean isShowStudentScore() { return showStudentScore; } public void setShowStudentScore(boolean showStudentScore) { this.showStudentScore = showStudentScore; } public boolean getForGrading() { return forGrading; } public void setForGrading(boolean param) { this.forGrading = param; } public boolean isTimeRunning() { return timeRunning; } public void setTimeRunning(boolean timeRunning) { this.timeRunning = timeRunning; } /** * Used for a JavaScript enable check. */ public String getJavaScriptEnabledCheck() { return this.javaScriptEnabledCheck; } /** * Used for a JavaScript enable check. */ public void setJavaScriptEnabledCheck(String javaScriptEnabledCheck) { this.javaScriptEnabledCheck = javaScriptEnabledCheck; } //cwen public void setSiteId(String siteId) { this.siteId = siteId; } public String getSiteId() { siteId = null; Placement currentPlacement = ToolManager.getCurrentPlacement(); if(currentPlacement != null) siteId = currentPlacement.getContext(); return siteId; } public String getAgentAccessString() { return deliveryAgent.getAgentInstanceString(); } public void setAgentAccessString(String agentString) { deliveryAgent.setAgentInstanceString(agentString); } public boolean getSaveToDb(){ String saveToDb=(String)ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.ui.bean.delivery.resource.MediaConstants", "SAVETODB"); if (saveToDb.equals("true")) return true; else return false; } public boolean getReviewAssessment() { return reviewAssessment; } public void setReviewAssessment(boolean reviewAssessment) { this.reviewAssessment = reviewAssessment; } public void attachToItemContentBean(ItemGradingData itemGradingData, String questionId){ ArrayList list = new ArrayList(); list.add(itemGradingData); //find out sectionId from questionId PublishedAssessmentService publishedService = new PublishedAssessmentService(); PublishedItemData publishedItem = publishedService. loadPublishedItem(questionId); PublishedSectionData publishedSection = (PublishedSectionData) publishedItem.getSection(); String sectionId = publishedSection.getSectionId().toString(); SectionContentsBean partSelected = null; //get all partContents ArrayList parts = getPageContents().getPartsContents(); for (int i=0; i<parts.size(); i++){ SectionContentsBean part = (SectionContentsBean)parts.get(i); log.debug("**** question's sectionId"+sectionId); log.debug("**** partId"+part.getSectionId()); if (sectionId.equals(part.getSectionId())){ partSelected = part; break; } } //locate the itemContentBean - the hard way, sigh... ArrayList items = new ArrayList(); if (partSelected!=null) items = partSelected.getItemContents(); for (int j=0; j<items.size(); j++){ ItemContentsBean item = (ItemContentsBean)items.get(j); if ((publishedItem.getItemId()).equals(item.getItemData().getItemId())){ // comparing itemId not object item.setItemGradingDataArray(list); break; } } } }
samigo/tool/src/java/org/sakaiproject/tool/assessment/ui/bean/delivery/DeliveryBean.java
/* * Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University, * Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation * * Licensed under the Educational Community License Version 1.0 (the "License"); * By obtaining, using and/or copying this Original Work, you agree that you have read, * understand, and will comply with the terms and conditions of the Educational Community License. * You may obtain a copy of the License at: * * http://cvs.sakaiproject.org/licenses/license_1_0.html * * 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. */ package org.sakaiproject.tool.assessment.ui.bean.delivery; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.context.ExternalContext; import javax.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.tool.assessment.data.dao.assessment.AssessmentAccessControl; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedSectionData; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedItemData; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedItemText; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedSecuredIPAddress; import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingData; import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData; import org.sakaiproject.tool.assessment.data.dao.grading.MediaData; import org.sakaiproject.tool.assessment.facade.AgentFacade; import org.sakaiproject.tool.assessment.facade.PublishedAssessmentFacade; import org.sakaiproject.tool.assessment.services.GradingService; import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService; import org.sakaiproject.tool.assessment.ui.bean.util.Validator; import org.sakaiproject.tool.assessment.ui.listener.delivery.DeliveryActionListener; import org.sakaiproject.tool.assessment.ui.listener.delivery.SubmitToGradingActionListener; import org.sakaiproject.tool.assessment.ui.listener.delivery.UpdateTimerListener; import org.sakaiproject.tool.assessment.ui.listener.select.SelectActionListener; import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil; import org.sakaiproject.tool.assessment.util.MimeTypesLocator; import org.sakaiproject.spring.SpringBeanLocator; import org.sakaiproject.tool.assessment.ui.web.session.SessionUtil; import org.sakaiproject.tool.assessment.ui.bean.shared.PersonBean; //cwen import org.sakaiproject.api.kernel.tool.cover.ToolManager; import org.sakaiproject.api.kernel.tool.Placement; // note: we should wrap above dependency in a backend service--esmiley /** * * @author casong * @author [email protected] added agentState * $Id$ * * Used to be org.navigoproject.ui.web.asi.delivery.XmlDeliveryForm.java */ public class DeliveryBean implements Serializable { private static Log log = LogFactory.getLog(DeliveryBean.class); private String assessmentId; private String assessmentTitle; private ArrayList markedForReview; private ArrayList blankItems; private ArrayList markedForReviewIdents; private ArrayList blankItemIdents; private boolean reviewMarked; private boolean reviewAll; private boolean reviewBlank; private int itemIndex; private int size; private String action; private Date beginTime; private String endTime; private String currentTime; private String multipleAttempts; private String timeOutSubmission; private String submissionTicket; private String timeElapse; private String username; private int sectionIndex; private boolean previous; private String duration; private String url; private String confirmation; private String outcome; //Settings private String questionLayout; private String navigation; private String numbering; private String feedback; private String noFeedback; private String statistics; private String creatorName; private FeedbackComponent feedbackComponent; private boolean feedbackOnDate; private String errorMessage; private SettingsDeliveryBean settings; private java.util.Date dueDate; private boolean statsAvailable; private boolean submitted; private boolean graded; private String graderComment; private String rawScore; private String grade; private java.util.Date submissionDate; private java.util.Date submissionTime; private String image; private boolean hasImage; private String instructorMessage; private String courseName; private String timeLimit; private int timeLimit_hour; private int timeLimit_minute; private ContentsDeliveryBean tableOfContents; private String previewMode; private String previewAssessment; private String notPublished; private String submissionId; private String submissionMessage; private String instructorName; private ContentsDeliveryBean pageContents; private int submissionsRemaining; private boolean forGrade; private String password; // For paging private int partIndex; private int questionIndex; private boolean next_page; private boolean reload = true; // daisy added these for SelectActionListener private boolean notTakeable = true; private boolean pastDue; private long subTime; private long raw; private String takenHours; private String takenMinutes; private AssessmentGradingData adata; private PublishedAssessmentFacade publishedAssessment; private java.util.Date feedbackDate; private String feedbackDelivery; private String showScore; private boolean hasTimeLimit; // daisyf added for servlet Login.java, to support anonymous login with // publishedUrl private boolean anonymousLogin = false; private String contextPath; private boolean initAgentAccessString = false; /** Use serialVersionUID for interoperability. */ private final static long serialVersionUID = -1090852048737428722L; private boolean showStudentScore; // lydial added for allowing studentScore view for random draw parts private boolean forGrading; // to reuse deliveryActionListener for grading pages // SAM-387 // esmiley added to track if timer has been started in timed assessments private boolean timeRunning; // SAM-535 // esmiley added to track JavaScript private String javaScriptEnabledCheck; //cwen private String siteId; // daisy added this for SAK-1764 private boolean reviewAssessment=false; // daisy added back for SAK-2738 private boolean accessViaUrl=false; // this instance tracks if the Agent is taking a test via URL, as well as // current agent string (if assigned). SAK-1927: esmiley private AgentFacade deliveryAgent; /** * Creates a new DeliveryBean object. */ public DeliveryBean() { deliveryAgent = new AgentFacade(); } /** * * * @return */ public int getItemIndex() { return this.itemIndex; } /** * * * @param itemIndex */ public void setItemIndex(int itemIndex) { this.itemIndex = itemIndex; } /** * * * @return */ public int getSize() { return this.size; } /** * * * @param size */ public void setSize(int size) { this.size = size; } /** * * * @return */ public String getAssessmentId() { return assessmentId; } /** * * * @param assessmentId */ public void setAssessmentId(String assessmentId) { this.assessmentId = assessmentId; } /** * * * @return */ public ArrayList getMarkedForReview() { return markedForReview; } /** * * * @param markedForReview */ public void setMarkedForReview(ArrayList markedForReview) { this.markedForReview = markedForReview; } /** * * * @return */ public boolean getReviewMarked() { return this.reviewMarked; } /** * * * @param reviewMarked */ public void setReviewMarked(boolean reviewMarked) { this.reviewMarked = reviewMarked; } /** * * * @return */ public boolean getReviewAll() { return this.reviewAll; } /** * * * @param reviewAll */ public void setReviewAll(boolean reviewAll) { this.reviewAll = reviewAll; } /** * * * @return */ public String getAction() { return this.action; } /** * * * @param action */ public void setAction(String action) { this.action = action; } /** * * * @return */ public Date getBeginTime() { return beginTime; } /** * * * @param beginTime */ public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } /** * * * @return */ public String getEndTime() { return endTime; } /** * * * @param endTime */ public void setEndTime(String endTime) { this.endTime = endTime; } /** * * * @return */ public String getCurrentTime() { return this.currentTime; } /** * * * @param currentTime */ public void setCurrentTime(String currentTime) { this.currentTime = currentTime; } /** * * * @return */ public String getMultipleAttempts() { return this.multipleAttempts; } /** * * * @param multipleAttempts */ public void setMultipleAttempts(String multipleAttempts) { this.multipleAttempts = multipleAttempts; } /** * * * @return */ public String getTimeOutSubmission() { return this.timeOutSubmission; } /** * * * @param timeOutSubmission */ public void setTimeOutSubmission(String timeOutSubmission) { this.timeOutSubmission = timeOutSubmission; } /** * * * @return */ public java.util.Date getSubmissionTime() { return submissionTime; } /** * * * @param submissionTime */ public void setSubmissionTime(java.util.Date submissionTime) { this.submissionTime = submissionTime; } /** * * * @return */ public String getTimeElapse() { return timeElapse; } /** * * * @param timeElapse */ public void setTimeElapse(String timeElapse) { this.timeElapse = timeElapse; } /** * * * @return */ public String getSubmissionTicket() { return submissionTicket; } /** * * * @param submissionTicket */ public void setSubmissionTicket(String submissionTicket) { this.submissionTicket = submissionTicket; } /** * * * @return */ public int getDisplayIndex() { return this.itemIndex + 1; } /** * * * @return */ public String getUsername() { return username; } /** * * * @param username */ public void setUsername(String username) { this.username = username; } /** * * * @return */ public String getAssessmentTitle() { return assessmentTitle; } /** * * * @param assessmentTitle */ public void setAssessmentTitle(String assessmentTitle) { this.assessmentTitle = assessmentTitle; } /** * * * @return */ public ArrayList getBlankItems() { return this.blankItems; } /** * * * @param blankItems */ public void setBlankItems(ArrayList blankItems) { this.blankItems = blankItems; } /** * * * @return */ public boolean getReviewBlank() { return reviewBlank; } /** * * * @param reviewBlank */ public void setReviewBlank(boolean reviewBlank) { this.reviewBlank = reviewBlank; } /** * * * @return */ public ArrayList getMarkedForReviewIdents() { return markedForReviewIdents; } /** * * * @param markedForReviewIdents */ public void setMarkedForReviewIdents(ArrayList markedForReviewIdents) { this.markedForReviewIdents = markedForReviewIdents; } /** * * * @return */ public ArrayList getBlankItemIdents() { return blankItemIdents; } /** * * * @param blankItemIdents */ public void setBlankItemIdents(ArrayList blankItemIdents) { this.blankItemIdents = blankItemIdents; } /** * * * @return */ public int getSectionIndex() { return this.sectionIndex; } /** * * * @param sectionIndex */ public void setSectionIndex(int sectionIndex) { this.sectionIndex = sectionIndex; } /** * * * @return */ public boolean getPrevious() { return previous; } /** * * * @param previous */ public void setPrevious(boolean previous) { this.previous = previous; } //Settings public String getQuestionLayout() { return questionLayout; } /** * * * @param questionLayout */ public void setQuestionLayout(String questionLayout) { this.questionLayout = questionLayout; } /** * * * @return */ public String getNavigation() { return navigation; } /** * * * @param navigation */ public void setNavigation(String navigation) { this.navigation = navigation; } /** * * * @return */ public String getNumbering() { return numbering; } /** * * * @param numbering */ public void setNumbering(String numbering) { this.numbering = numbering; } /** * * * @return */ public String getFeedback() { return feedback; } /** * * * @param feedback */ public void setFeedback(String feedback) { this.feedback = feedback; } /** * * * @return */ public String getNoFeedback() { return noFeedback; } /** * * * @param noFeedback */ public void setNoFeedback(String noFeedback) { this.noFeedback = noFeedback; } /** * * * @return */ public String getStatistics() { return statistics; } /** * * * @param statistics */ public void setStatistics(String statistics) { this.statistics = statistics; } /** * * * @return */ public FeedbackComponent getFeedbackComponent() { return feedbackComponent; } /** * * * @param feedbackComponent */ public void setFeedbackComponent(FeedbackComponent feedbackComponent) { this.feedbackComponent = feedbackComponent; } /** * Types of feedback in FeedbackComponent: * * SHOW CORRECT SCORE * SHOW STUDENT SCORE * SHOW ITEM LEVEL * SHOW SECTION LEVEL * SHOW GRADER COMMENT * SHOW STATS * SHOW QUESTION * SHOW RESPONSE **/ /** * @return */ public SettingsDeliveryBean getSettings() { return settings; } /** * @param bean */ public void setSettings(SettingsDeliveryBean settings) { this.settings = settings; } /** * @return */ public String getErrorMessage() { return errorMessage; } /** * @param string */ public void setErrorMessage(String string) { errorMessage = string; } /** * @return */ public String getDuration() { return duration; } /** * @param string */ public void setDuration(String string) { duration = string; } /** * @return */ public String getCreatorName() { return creatorName; } /** * @param string */ public void setCreatorName(String string) { creatorName = string; } public java.util.Date getDueDate() { return dueDate; } public void setDueDate(java.util.Date dueDate) { this.dueDate = dueDate; } public boolean isStatsAvailable() { return statsAvailable; } public void setStatsAvailable(boolean statsAvailable) { this.statsAvailable = statsAvailable; } public boolean isSubmitted() { return submitted; } public void setSubmitted(boolean submitted) { this.submitted = submitted; } public boolean isGraded() { return graded; } public void setGraded(boolean graded) { this.graded = graded; } public boolean getFeedbackOnDate() { return feedbackOnDate; } public void setFeedbackOnDate(boolean feedbackOnDate) { this.feedbackOnDate = feedbackOnDate; } public String getGraderComment() { if (graderComment == null) { return ""; } return graderComment; } public void setGraderComment(String newComment) { graderComment = newComment; } public String getRawScore() { return rawScore; } public void setRawScore(String rawScore) { this.rawScore = rawScore; } public long getRaw() { return raw; } public void setRaw(long raw) { this.raw = raw; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public java.util.Date getSubmissionDate() { return submissionDate; } public void setSubmissionDate(java.util.Date submissionDate) { this.submissionDate = submissionDate; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public boolean isHasImage() { return hasImage; } public void setHasImage(boolean hasImage) { this.hasImage = hasImage; } public String getInstructorMessage() { return instructorMessage; } public void setInstructorMessage(String instructorMessage) { this.instructorMessage = instructorMessage; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getTimeLimit() { return timeLimit; } public void setTimeLimit(String timeLimit) { this.timeLimit = timeLimit; } public int getTimeLimit_hour() { return timeLimit_hour; } public void setTimeLimit_hour(int timeLimit_hour) { this.timeLimit_hour = timeLimit_hour; } public int getTimeLimit_minute() { return timeLimit_minute; } public void setTimeLimit_minute(int timeLimit_minute) { this.timeLimit_minute = timeLimit_minute; } /** * Bean with table of contents information and * a list of all the sections in the assessment * which in turn has a list of all the item contents. * @return table of contents */ public ContentsDeliveryBean getTableOfContents() { return tableOfContents; } /** * Bean with table of contents information and * a list of all the sections in the assessment * which in turn has a list of all the item contents. * @param tableOfContents table of contents */ public void setTableOfContents(ContentsDeliveryBean tableOfContents) { this.tableOfContents = tableOfContents; } /** * Bean with a list of all the sections in the current page * which in turn has a list of all the item contents for the page. * * This is like the table of contents, but the selections are restricted to * that on one page. * * Since these properties are on a page delivery basis--if: * 1. there is only one item per page the list of items will * contain one item and the list of parts will return one part, or if-- * * 2. there is one part per page the list of items will be that * for that part only and there will only be one part, however-- * * 3. if it is all parts and items on a single page there * will be a list of all parts and items. * * @return ContentsDeliveryBean */ public ContentsDeliveryBean getPageContents() { return pageContents; } /** * Bean with a list of all the sections in the current page * which in turn has a list of all the item contents for the page. * * Since these properties are on a page delivery basis--if: * 1. there is only one item per page the list of items will * contain one item and the list of parts will return one part, or if-- * * 2. there is one part per page the list of items will be that * for that part only and there will only be one part, however-- * * 3. if it is all parts and items on a single page there * will be a list of all parts and items. * * @param pageContents ContentsDeliveryBean */ public void setPageContents(ContentsDeliveryBean pageContents) { this.pageContents = pageContents; } /** * track whether delivery is "live" with update of database allowed and * whether the Ui components are disabled. * @return true if preview only */ public String getPreviewMode() { return Validator.check(previewMode, "false"); } /** * track whether delivery is "live" with update of database allowed and * whether the UI components are disabled. * @param previewMode true if preview only */ public void setPreviewMode(boolean previewMode) { this.previewMode = new Boolean(previewMode).toString(); } public String getPreviewAssessment() { return previewAssessment; } public void setPreviewAssessment(String previewAssessment) { this.previewAssessment = previewAssessment; } public String getNotPublished() { return notPublished; } public void setNotPublished(String notPublished) { this.notPublished = notPublished; } public String getSubmissionId() { return submissionId; } public void setSubmissionId(String submissionId) { this.submissionId = submissionId; } public String getSubmissionMessage() { return submissionMessage; } public void setSubmissionMessage(String submissionMessage) { this.submissionMessage = submissionMessage; } public int getSubmissionsRemaining() { return submissionsRemaining; } public void setSubmissionsRemaining(int submissionsRemaining) { this.submissionsRemaining = submissionsRemaining; } public String getInstructorName() { return instructorName; } public void setInstructorName(String instructorName) { this.instructorName = instructorName; } public boolean getForGrade() { return forGrade; } public void setForGrade(boolean newfor) { forGrade = newfor; } public String submitForGrade() { SessionUtil.setSessionTimeout(FacesContext.getCurrentInstance(), this, false); forGrade = true; SubmitToGradingActionListener listener = new SubmitToGradingActionListener(); listener.processAction(null); String returnValue="submitAssessment"; if (getAccessViaUrl()) // this is for accessing via published url { returnValue="anonymousThankYou"; } forGrade = false; SelectActionListener l2 = new SelectActionListener(); l2.processAction(null); reload = true; return returnValue; } public String saveAndExit() { FacesContext context = FacesContext.getCurrentInstance(); SessionUtil.setSessionTimeout(context, this, false); log.debug("***DeliverBean.saveAndEXit face context =" + context); // If this was automatically triggered by running out of time, // check for autosubmit, and do it if so. if (timeOutSubmission != null && timeOutSubmission.equals("true")) { if (getSettings().getAutoSubmit()) { submitForGrade(); return "timeout"; } } forGrade = false; SubmitToGradingActionListener listener = new SubmitToGradingActionListener(); listener.processAction(null); String returnValue = "select"; if (timeOutSubmission != null && timeOutSubmission.equals("true")) { returnValue = "timeout"; } if (getAccessViaUrl()) { // if this is access via url, display quit message log.debug("**anonymous login, go to quit"); returnValue = "anonymousQuit"; } SelectActionListener l2 = new SelectActionListener(); l2.processAction(null); reload = true; return returnValue; } public String next_page() { if (getSettings().isFormatByPart()) { partIndex++; } if (getSettings().isFormatByQuestion()) { questionIndex++; } forGrade = false; if (! ("true").equals(previewAssessment)) { SubmitToGradingActionListener listener = new SubmitToGradingActionListener(); listener.processAction(null); } DeliveryActionListener l2 = new DeliveryActionListener(); l2.processAction(null); reload = false; return "takeAssessment"; } public String previous() { if (getSettings().isFormatByPart()) { partIndex--; } if (getSettings().isFormatByQuestion()) { questionIndex--; } forGrade = false; if (! ("true").equals(previewAssessment)) { SubmitToGradingActionListener listener = new SubmitToGradingActionListener(); listener.processAction(null); } DeliveryActionListener l2 = new DeliveryActionListener(); l2.processAction(null); reload = false; return "takeAssessment"; } // this is the PublishedAccessControl.finalPageUrl public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getConfirmation() { return confirmation; } public void setConfirmation(String confirmation) { this.confirmation = confirmation; } /** * if required, assessment password * @return password */ public String getPassword() { return password; } /** * if required, assessment password * @param string assessment password */ public void setPassword(String string) { password = string; } public String validatePassword() { log.debug("**** username=" + username); log.debug("**** password=" + password); log.debug("**** setting username=" + getSettings().getUsername()); log.debug("**** setting password=" + getSettings().getPassword()); if (password == null || username == null) { return "passwordAccessError"; } if (password.equals(getSettings().getPassword()) && username.equals(getSettings().getUsername())) { if (getNavigation().equals (AssessmentAccessControl.RANDOM_ACCESS.toString())) { return "tableOfContents"; } else { return "takeAssessment"; } } else { return "passwordAccessError"; } } public String validateIP() { String thisIp = ( (javax.servlet.http.HttpServletRequest) FacesContext. getCurrentInstance().getExternalContext().getRequest()). getRemoteAddr(); Iterator addresses = getSettings().getIpAddresses().iterator(); while (addresses.hasNext()) { String next = ( (PublishedSecuredIPAddress) addresses.next()). getIpAddress(); if (next != null && next.indexOf("*") > -1) { next = next.substring(0, next.indexOf("*")); } if (next == null || next.trim().equals("") || thisIp.trim().startsWith(next.trim())) { if (getNavigation().equals (AssessmentAccessControl.RANDOM_ACCESS.toString())) { return "tableOfContents"; } else { return "takeAssessment"; } } } return "ipAccessError"; } public String validate() { try { String results = ""; if (!getSettings().getUsername().equals("")) { results = validatePassword(); } if (!results.equals("passwordAccessError") && getSettings().getIpAddresses() != null && !getSettings().getIpAddresses().isEmpty()) { results = validateIP(); } if (results.equals("")) { if (getNavigation().equals (AssessmentAccessControl.RANDOM_ACCESS.toString())) { return "tableOfContents"; } else { return "takeAssessment"; } } return results; } catch (Exception e) { e.printStackTrace(); return "accessError"; } } public String pvalidate() { try { if (getNavigation().equals (AssessmentAccessControl.RANDOM_ACCESS.toString())) { return "tableOfContents"; } else { return "takeAssessment"; } } catch (Exception e) { e.printStackTrace(); return "accessError"; } } // Skipped paging methods public int getPartIndex() { return partIndex; } public void setPartIndex(int newindex) { partIndex = newindex; } public int getQuestionIndex() { return questionIndex; } public void setQuestionIndex(int newindex) { questionIndex = newindex; } public boolean getContinue() { return next_page; } public void setContinue(boolean docontinue) { next_page = docontinue; } public boolean getReload() { return reload; } public void setReload(boolean doreload) { reload = doreload; } // Store for paging public AssessmentGradingData getAssessmentGrading() { return adata; } public void setAssessmentGrading(AssessmentGradingData newdata) { adata = newdata; } private byte[] getMediaStream(String mediaLocation) { FileInputStream mediaStream = null; FileInputStream mediaStream2 = null; byte[] mediaByte = new byte[0]; try { int i = 0; int size = 0; mediaStream = new FileInputStream(mediaLocation); if (mediaStream != null) { while ( (i = mediaStream.read()) != -1) { size++; } } mediaStream2 = new FileInputStream(mediaLocation); mediaByte = new byte[size]; mediaStream2.read(mediaByte, 0, size); FileOutputStream out = new FileOutputStream("/tmp/test.txt"); out.write(mediaByte); } catch (FileNotFoundException ex) { log.debug("file not found=" + ex.getMessage()); } catch (IOException ex) { log.debug("io exception=" + ex.getMessage()); } finally { try { mediaStream.close(); } catch (IOException ex1) { } } return mediaByte; } /** * This method is used by jsf/delivery/deliveryFileUpload.jsp * <corejsf:upload * target="/jsf/upload_tmp/assessment#{delivery.assessmentId}/ * question#{question.itemData.itemId}/admin" * valueChangeListener="#{delivery.addMediaToItemGrading}" /> */ public String addMediaToItemGrading(javax.faces.event.ValueChangeEvent e) { GradingService gradingService = new GradingService(); PublishedAssessmentService publishedService = new PublishedAssessmentService(); PublishedAssessmentFacade publishedAssessment = publishedService. getPublishedAssessment(assessmentId); PersonBean person = (PersonBean) ContextUtil.lookupBean("person"); String agent = person.getId(); // 1. create assessmentGrading if it is null if (this.adata == null) { adata = new AssessmentGradingData(); adata.setAgentId(agent); adata.setPublishedAssessment(publishedAssessment.getData()); log.debug("***1a. addMediaToItemGrading, getForGrade()=" + getForGrade()); adata.setForGrade(new Boolean(getForGrade())); adata.setAttemptDate(getBeginTime()); gradingService.saveOrUpdateAssessmentGrading(adata); } log.info("***1b. addMediaToItemGrading, adata=" + adata); // 2. format of the media location is: assessmentXXX/questionXXX/agentId/myfile String mediaLocation = (String) e.getNewValue(); log.debug("***2a. addMediaToItemGrading, new value =" + mediaLocation); // 3. get the questionId (which is the PublishedItemData.itemId) int assessmentIndex = mediaLocation.indexOf("assessment"); int questionIndex = mediaLocation.indexOf("question"); int agentIndex = mediaLocation.indexOf("/", questionIndex + 8); //cwen if(agentIndex < 0 ) { agentIndex = mediaLocation.indexOf("\\", questionIndex + 8); } String pubAssessmentId = mediaLocation.substring(assessmentIndex + 10, questionIndex - 1); String questionId = mediaLocation.substring(questionIndex + 8, agentIndex); log.debug("***3a. addMediaToItemGrading, questionId =" + questionId); log.debug("***3b. addMediaToItemGrading, assessmentId =" + assessmentId); // 4. prepare itemGradingData and attach it to assessmentGarding PublishedItemData item = publishedService.loadPublishedItem(questionId); log.debug("***4a. addMediaToItemGrading, item =" + item); log.debug("***4b. addMediaToItemGrading, itemTextArray =" + item.getItemTextArray()); log.debug("***4c. addMediaToItemGrading, itemText(0) =" + item.getItemTextArray().get(0)); // there is only one text in audio question PublishedItemText itemText = (PublishedItemText) item. getItemTextArraySorted().get(0); ItemGradingData itemGradingData = getItemGradingData(questionId); boolean newItemGradingData = false; if (itemGradingData == null) { newItemGradingData = true; itemGradingData = new ItemGradingData(); itemGradingData.setAssessmentGrading(adata); itemGradingData.setPublishedItem(item); itemGradingData.setPublishedItemText(itemText); itemGradingData.setSubmittedDate(new Date()); itemGradingData.setAgentId(agent); itemGradingData.setOverrideScore(new Float(0)); } setAssessmentGrading(adata); // 5. save AssessmentGardingData with ItemGardingData Set itemDataSet = adata.getItemGradingSet(); log.debug("***5a. addMediaToItemGrading, itemDataSet=" + itemDataSet); if (itemDataSet == null) { itemDataSet = new HashSet(); } itemDataSet.add(itemGradingData); adata.setItemGradingSet(itemDataSet); gradingService.saveOrUpdateAssessmentGrading(adata); log.debug("***5b. addMediaToItemGrading, saved=" + adata); //if media is uploaded, create media record and attach to itemGradingData if (mediaIsValid()) saveMedia(agent, mediaLocation, itemGradingData, gradingService); // 8. do whatever need doing DeliveryActionListener dlistener = new DeliveryActionListener(); // false => do not reset the entire current delivery.pageContents. // we will do it ourselves and only update the question that this media // is attached to dlistener.processAction(null, false); if (newItemGradingData) attachToItemContentBean(itemGradingData, questionId); // 9. do the timer thing Integer timeLimit = null; if (adata != null && adata.getPublishedAssessment() != null && adata.getPublishedAssessment().getAssessmentAccessControl() != null) { timeLimit = adata.getPublishedAssessment().getAssessmentAccessControl(). getTimeLimit(); } if (timeLimit != null && timeLimit.intValue() > 0) { UpdateTimerListener l3 = new UpdateTimerListener(); l3.processAction(null); } reload = true; return "takeAssessment"; } public void saveMedia(String agent, String mediaLocation, ItemGradingData itemGradingData, GradingService gradingService){ // 1. create a media record File media = new File(mediaLocation); byte[] mediaByte = getMediaStream(mediaLocation); String mimeType = MimeTypesLocator.getInstance().getContentType(media); //boolean SAVETODB = MediaData.saveToDB(); boolean SAVETODB = getSaveToDb(); log.debug("**** SAVETODB=" + SAVETODB); MediaData mediaData = null; log.debug("***6a. addMediaToItemGrading, itemGradinDataId=" + itemGradingData.getItemGradingId()); log.debug("***6b. addMediaToItemGrading, publishedItemId=" + ( (PublishedItemData) itemGradingData.getPublishedItem()). getItemId()); if (SAVETODB) { // put the byte[] in mediaData = new MediaData(itemGradingData, mediaByte, new Long(mediaByte.length + ""), mimeType, "description", null, media.getName(), false, false, new Integer(1), agent, new Date(), agent, new Date()); } else { // put the location in mediaData = new MediaData(itemGradingData, null, new Long(mediaByte.length + ""), mimeType, "description", mediaLocation, media.getName(), false, false, new Integer(1), agent, new Date(), agent, new Date()); } Long mediaId = gradingService.saveMedia(mediaData); log.debug("mediaId=" + mediaId); log.debug("***6c. addMediaToItemGrading, media.itemGradinDataId=" + ( (ItemGradingData) mediaData.getItemGradingData()). getItemGradingId()); log.debug("***6d. addMediaToItemGrading, mediaId=" + mediaData.getMediaId()); // 2. store mediaId in itemGradingRecord.answerText log.debug("***7. addMediaToItemGrading, adata=" + adata); itemGradingData.setAnswerText(mediaId + ""); gradingService.saveItemGrading(itemGradingData); } public boolean mediaIsValid() { boolean returnValue =true; // check if file is too big FacesContext context = FacesContext.getCurrentInstance(); ExternalContext external = context.getExternalContext(); Long fileSize = (Long)((ServletContext)external.getContext()).getAttribute("TEMP_FILEUPLOAD_SIZE"); Long maxSize = (Long)((ServletContext)external.getContext()).getAttribute("FILEUPLOAD_SIZE_MAX"); log.info("**** filesize is ="+fileSize); log.info("**** maxsize is ="+maxSize); ((ServletContext)external.getContext()).removeAttribute("TEMP_FILEUPLOAD_SIZE"); if (fileSize!=null){ float fileSize_float = fileSize.floatValue()/1024; int tmp = Math.round(fileSize_float * 10.0f); fileSize_float = (float)tmp / 10.0f; float maxSize_float = maxSize.floatValue()/1024; int tmp0 = Math.round(maxSize_float * 10.0f); maxSize_float = (float)tmp0 / 10.0f; String err1=(String)ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "file_upload_error"); String err2=(String)ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "file_uploaded"); String err3=(String)ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "max_size_allowed"); String err4=(String)ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.DeliveryMessages", "upload_again"); String err = err2 + fileSize_float + err3 + maxSize_float + err4; context.addMessage("file_upload_error",new FacesMessage(err1)); context.addMessage("file_upload_error",new FacesMessage(err)); returnValue = false; } return returnValue; } public boolean getNotTakeable() { return notTakeable; } public void setNotTakeable(boolean notTakeable) { this.notTakeable = notTakeable; } public boolean getPastDue() { return pastDue; } public void setPastDue(boolean pastDue) { this.pastDue = pastDue; } public long getSubTime() { return subTime; } public void setSubTime(long newSubTime) { subTime = newSubTime; } public String getSubmissionHours() { return takenHours; } public void setSubmissionHours(String newHours) { takenHours = newHours; } public String getSubmissionMinutes() { return takenMinutes; } public void setSubmissionMinutes(String newMinutes) { takenMinutes = newMinutes; } public PublishedAssessmentFacade getPublishedAssessment() { return publishedAssessment; } public void setPublishedAssessment(PublishedAssessmentFacade publishedAssessment) { this.publishedAssessment = publishedAssessment; } public java.util.Date getFeedbackDate() { return feedbackDate; } public void setFeedbackDate(java.util.Date feedbackDate) { this.feedbackDate = feedbackDate; } public String getFeedbackDelivery() { return feedbackDelivery; } public void setFeedbackDelivery(String feedbackDelivery) { this.feedbackDelivery = feedbackDelivery; } public String getShowScore() { return showScore; } public void setShowScore(String showScore) { this.showScore = showScore; } public boolean getHasTimeLimit() { return hasTimeLimit; } public void setHasTimeLimit(boolean hasTimeLimit) { this.hasTimeLimit = hasTimeLimit; } public String getOutcome() { return outcome; } public void setOutcome(String outcome) { this.outcome = outcome; } public String doit() { return outcome; } /* public ItemGradingData getItemGradingData(String publishedItemId){ ItemGradingData itemGradingData = new ItemGradingData(); if (adata != null){ GradingService service = new GradingService(); itemGradingData = service.getItemGradingData(adata.getAssessmentGradingId().toString(), publishedItemId); if (itemGradingData == null) itemGradingData = new ItemGradingData(); } return itemGradingData; } */ public boolean getAnonymousLogin() { return anonymousLogin; } public void setAnonymousLogin(boolean anonymousLogin) { this.anonymousLogin = anonymousLogin; } public boolean getAccessViaUrl() { return accessViaUrl; } public void setAccessViaUrl(boolean accessViaUrl) { this.accessViaUrl=accessViaUrl; } public ItemGradingData getItemGradingData(String publishedItemId) { ItemGradingData selected = null; if (adata != null) { Set items = adata.getItemGradingSet(); if (items != null) { Iterator iter = items.iterator(); while (iter.hasNext()) { ItemGradingData itemGradingData = (ItemGradingData) iter.next(); String itemPublishedId = itemGradingData.getPublishedItem().getItemId(). toString(); if ( (publishedItemId).equals(itemPublishedId)) { log.debug("*** addMediaToItemGrading, same : found it"); selected = itemGradingData; } else { log.debug("*** addMediaToItemGrading, not the same"); } } log.debug("*** addMediaToItemGrading, publishedItemId =" + publishedItemId); if (selected != null) { log.debug( "*** addMediaToItemGrading, itemGradingData.publishedItemId =" + selected.getPublishedItem().getItemId().toString()); } } } return selected; } public String getContextPath() { return contextPath; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } public boolean isShowStudentScore() { return showStudentScore; } public void setShowStudentScore(boolean showStudentScore) { this.showStudentScore = showStudentScore; } public boolean getForGrading() { return forGrading; } public void setForGrading(boolean param) { this.forGrading = param; } public boolean isTimeRunning() { return timeRunning; } public void setTimeRunning(boolean timeRunning) { this.timeRunning = timeRunning; } /** * Used for a JavaScript enable check. */ public String getJavaScriptEnabledCheck() { return this.javaScriptEnabledCheck; } /** * Used for a JavaScript enable check. */ public void setJavaScriptEnabledCheck(String javaScriptEnabledCheck) { this.javaScriptEnabledCheck = javaScriptEnabledCheck; } //cwen public void setSiteId(String siteId) { this.siteId = siteId; } public String getSiteId() { siteId = null; Placement currentPlacement = ToolManager.getCurrentPlacement(); if(currentPlacement != null) siteId = currentPlacement.getContext(); return siteId; } public String getAgentAccessString() { return deliveryAgent.getAgentInstanceString(); } public void setAgentAccessString(String agentString) { deliveryAgent.setAgentInstanceString(agentString); } public boolean getSaveToDb(){ String saveToDb=(String)ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.ui.bean.delivery.resource.MediaConstants", "SAVETODB"); if (saveToDb.equals("true")) return true; else return false; } public boolean getReviewAssessment() { return reviewAssessment; } public void setReviewAssessment(boolean reviewAssessment) { this.reviewAssessment = reviewAssessment; } public void attachToItemContentBean(ItemGradingData itemGradingData, String questionId){ ArrayList list = new ArrayList(); list.add(itemGradingData); //find out sectionId from questionId PublishedAssessmentService publishedService = new PublishedAssessmentService(); PublishedItemData publishedItem = publishedService. loadPublishedItem(questionId); PublishedSectionData publishedSection = (PublishedSectionData) publishedItem.getSection(); String sectionId = publishedSection.getSectionId().toString(); SectionContentsBean partSelected = null; //get all partContents ArrayList parts = getPageContents().getPartsContents(); for (int i=0; i<parts.size(); i++){ SectionContentsBean part = (SectionContentsBean)parts.get(i); log.debug("**** question's sectionId"+sectionId); log.debug("**** partId"+part.getSectionId()); if (sectionId.equals(part.getSectionId())){ partSelected = part; break; } } //locate the itemContentBean - the hard way, sigh... ArrayList items = new ArrayList(); if (partSelected!=null) items = partSelected.getItemContents(); for (int j=0; j<items.size(); j++){ ItemContentsBean item = (ItemContentsBean)items.get(j); if ((publishedItem.getItemId()).equals(item.getItemData().getItemId())){ // comparing itemId not object item.setItemGradingDataArray(list); break; } } } }
SAK-1781 - goto the 1st question when after users hit Begin Assessment This is a change of spec git-svn-id: 840349cbf2a7f44860f6cfd02374235b623e9bf9@4329 66ffb92e-73f9-0310-93c1-f5514f145a0a
samigo/tool/src/java/org/sakaiproject/tool/assessment/ui/bean/delivery/DeliveryBean.java
SAK-1781 - goto the 1st question when after users hit Begin Assessment This is a change of spec
<ide><path>amigo/tool/src/java/org/sakaiproject/tool/assessment/ui/bean/delivery/DeliveryBean.java <ide> if (password.equals(getSettings().getPassword()) && <ide> username.equals(getSettings().getUsername())) <ide> { <del> if (getNavigation().equals <del> (AssessmentAccessControl.RANDOM_ACCESS.toString())) <del> { <del> return "tableOfContents"; <del> } <del> else <del> { <del> return "takeAssessment"; <del> } <add> // in post 2.1, clicking at Begin Assessment takes users to the <add> // 1st question. <add> return "takeAssessment"; <ide> } <ide> else <ide> { <ide> if (next == null || next.trim().equals("") || <ide> thisIp.trim().startsWith(next.trim())) <ide> { <del> if (getNavigation().equals <del> (AssessmentAccessControl.RANDOM_ACCESS.toString())) <del> { <del> return "tableOfContents"; <del> } <del> else <del> { <del> return "takeAssessment"; <del> } <add> // in post 2.1, clicking at Begin Assessment takes users to the <add> // 1st question. <add> return "takeAssessment"; <ide> } <ide> } <ide> return "ipAccessError"; <ide> } <ide> if (results.equals("")) <ide> { <del> if (getNavigation().equals <del> (AssessmentAccessControl.RANDOM_ACCESS.toString())) <del> { <del> return "tableOfContents"; <del> } <del> else <del> { <del> return "takeAssessment"; <del> } <add> // in post 2.1, clicking at Begin Assessment takes users to the <add> // 1st question. <add> return "takeAssessment"; <ide> } <ide> return results; <ide> } <ide> <ide> public String pvalidate() <ide> { <del> try <del> { <del> if (getNavigation().equals <del> (AssessmentAccessControl.RANDOM_ACCESS.toString())) <del> { <del> return "tableOfContents"; <del> } <del> else <del> { <del> return "takeAssessment"; <del> } <del> <del> } <del> catch (Exception e) <del> { <del> e.printStackTrace(); <del> return "accessError"; <del> } <add> // in post 2.1, clicking at Begin Assessment takes users to the <add> // 1st question. <add> return "takeAssessment"; <ide> } <ide> <ide> // Skipped paging methods
Java
apache-2.0
c653316fee3d911bfb0332bd69b7300a1a80dd0d
0
yangfuhai/jboot,yangfuhai/jboot
/** * Copyright (c) 2015-2019, Michael Yang 杨福海 ([email protected]). * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. */ package io.jboot.support.swagger; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializeConfig; import com.google.common.collect.Maps; import com.jfinal.core.JFinal; import io.jboot.Jboot; import io.jboot.web.controller.JbootController; import io.jboot.web.cors.EnableCORS; import io.swagger.models.Swagger; import io.swagger.models.properties.RefProperty; /** * @author Michael Yang 杨福海 ([email protected]) * @version V1.0 * @Package io.jboot.component.swagger */ public class JbootSwaggerController extends JbootController { JbootSwaggerConfig config = Jboot.config(JbootSwaggerConfig.class); public void index() { String html; try { String viewPath = config.getPath().endsWith("/") ? config.getPath() : config.getPath() + "/"; html = renderToString(viewPath + "index.html", Maps.newHashMap()); } catch (Exception ex) { renderHtml("error,please put <a href=\"https://github.com/swagger-api/swagger-ui\" target=\"_blank\">swagger-ui</a> " + "into your project path : " + config.getPath() + " <br />" + "or click <a href=\"" + config.getPath() + "/json\">here</a> show swagger json."); return; } // String jsonUrl = getRequest().getRequestURL().toString() + "/json"; // String basePath = JFinal.me().getContextPath() + "/" + config.getPath() + "/"; String basePath = getRequest().getRequestURL().toString(); String jsonUrl = basePath + "json"; html = html.replace("http://petstore.swagger.io/v2/swagger.json", jsonUrl); // 可能是 https ,看下载的 swagger 版本 html = html.replace("https://petstore.swagger.io/v2/swagger.json", jsonUrl); html = html.replace("src=\"./", "src=\"" + basePath); html = html.replace("href=\"./", "href=\"" + basePath); renderHtml(html); } /** * 渲染json * 参考:http://petstore.swagger.io/ 及json信息 http://petstore.swagger.io/v2/swagger.json */ @EnableCORS public void json() { Swagger swagger = JbootSwaggerManager.me().getSwagger(); if (swagger == null) { renderText("swagger config error."); return; } // 适配swaggerUI, 解决页面"Unknown Type : ref"问题。 SerializeConfig serializeConfig = new SerializeConfig(); serializeConfig.put(RefProperty.class, new RefPropertySerializer()); renderJson(JSON.toJSONString(swagger, serializeConfig)); } }
src/main/java/io/jboot/support/swagger/JbootSwaggerController.java
/** * Copyright (c) 2015-2019, Michael Yang 杨福海 ([email protected]). * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. */ package io.jboot.support.swagger; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializeConfig; import com.google.common.collect.Maps; import com.jfinal.core.JFinal; import io.jboot.Jboot; import io.jboot.web.controller.JbootController; import io.jboot.web.cors.EnableCORS; import io.swagger.models.Swagger; import io.swagger.models.properties.RefProperty; /** * @author Michael Yang 杨福海 ([email protected]) * @version V1.0 * @Package io.jboot.component.swagger */ public class JbootSwaggerController extends JbootController { JbootSwaggerConfig config = Jboot.config(JbootSwaggerConfig.class); public void index() { String html; try { String viewPath = config.getPath().endsWith("/") ? config.getPath() : config.getPath() + "/"; html = renderToString(viewPath + "index.html", Maps.newHashMap()); } catch (Exception ex) { renderHtml("error,please put <a href=\"https://github.com/swagger-api/swagger-ui\" target=\"_blank\">swagger-ui</a> " + "into your project path : " + config.getPath() + " <br />" + "or click <a href=\"" + config.getPath() + "/json\">here</a> show swagger json."); return; } String jsonUrl = getRequest().getRequestURL().toString() + "/json"; String basePath = JFinal.me().getContextPath() + "/" + config.getPath() + "/"; html = html.replace("http://petstore.swagger.io/v2/swagger.json", jsonUrl); html = html.replace("https://petstore.swagger.io/v2/swagger.json", jsonUrl); // 可能是 https ,看下载的 swagger 版本 html = html.replace("src=\"./", "src=\"" + basePath); html = html.replace("href=\"./", "href=\"" + basePath); renderHtml(html); } /** * 渲染json * 参考:http://petstore.swagger.io/ 及json信息 http://petstore.swagger.io/v2/swagger.json */ @EnableCORS public void json() { Swagger swagger = JbootSwaggerManager.me().getSwagger(); if (swagger == null) { renderText("swagger config error."); return; } // 适配swaggerUI, 解决页面"Unknown Type : ref"问题。 SerializeConfig serializeConfig = new SerializeConfig(); serializeConfig.put(RefProperty.class, new RefPropertySerializer()); renderJson(JSON.toJSONString(swagger, serializeConfig)); } }
fixed: 修复swaggerui中index.html中css,js,json资源路径错误的bug
src/main/java/io/jboot/support/swagger/JbootSwaggerController.java
fixed: 修复swaggerui中index.html中css,js,json资源路径错误的bug
<ide><path>rc/main/java/io/jboot/support/swagger/JbootSwaggerController.java <ide> return; <ide> } <ide> <del> <del> String jsonUrl = getRequest().getRequestURL().toString() + "/json"; <del> String basePath = JFinal.me().getContextPath() + "/" + config.getPath() + "/"; <add> // String jsonUrl = getRequest().getRequestURL().toString() + "/json"; <add> // String basePath = JFinal.me().getContextPath() + "/" + config.getPath() + "/"; <add> String basePath = getRequest().getRequestURL().toString(); <add> String jsonUrl = basePath + "json"; <ide> <ide> html = html.replace("http://petstore.swagger.io/v2/swagger.json", jsonUrl); <del> html = html.replace("https://petstore.swagger.io/v2/swagger.json", jsonUrl); // 可能是 https ,看下载的 swagger 版本 <add> // 可能是 https ,看下载的 swagger 版本 <add> html = html.replace("https://petstore.swagger.io/v2/swagger.json", jsonUrl); <ide> html = html.replace("src=\"./", "src=\"" + basePath); <ide> html = html.replace("href=\"./", "href=\"" + basePath); <ide>
Java
apache-2.0
41e57abd4d970b039ee845931e3c73a00cfbcc00
0
omindu/carbon-identity-framework,omindu/carbon-identity-framework,wso2/carbon-identity-framework,wso2/carbon-identity-framework,omindu/carbon-identity-framework,wso2/carbon-identity-framework,omindu/carbon-identity-framework,wso2/carbon-identity-framework
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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. */ package org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js; import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; import org.wso2.carbon.identity.application.authentication.framework.context.TransientObjectWrapper; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants; /** * Javascript wrapper for Java level AuthenticationContext. * This provides controlled access to AuthenticationContext object via provided javascript native syntax. * e.g * var requestedAcr = context.requestedAcr * <p> * instead of * var requestedAcr = context.getRequestedAcr() * <p> * Also it prevents writing an arbitrary values to the respective fields, keeping consistency on runtime * AuthenticationContext. * * @see AuthenticationContext */ public class JsAuthenticationContext extends AbstractJSObjectWrapper<AuthenticationContext> { public JsAuthenticationContext(AuthenticationContext wrapped) { super(wrapped); } @Override public Object getMember(String name) { switch (name) { case FrameworkConstants.JSAttributes.JS_REQUESTED_ACR: return getWrapped().getRequestedAcr(); case FrameworkConstants.JSAttributes.JS_AUTHENTICATED_SUBJECT: return new JsAuthenticatedUser(getWrapped().getSubject()); case FrameworkConstants.JSAttributes.JS_LAST_AUTHENTICATED_USER: return new JsAuthenticatedUser(getWrapped().getLastAuthenticatedUser()); case FrameworkConstants.JSAttributes.JS_TENANT_DOMAIN: return getWrapped().getTenantDomain(); case FrameworkConstants.JSAttributes.JS_SERVICE_PROVIDER_NAME: return getWrapped().getServiceProviderName(); case FrameworkConstants.JSAttributes.JS_REQUEST: return new JsServletRequest((TransientObjectWrapper) getWrapped() .getParameter(FrameworkConstants.RequestAttribute.HTTP_REQUEST)); case FrameworkConstants.JSAttributes.JS_RESPONSE: return new JsServletResponse((TransientObjectWrapper) getWrapped() .getParameter(FrameworkConstants.RequestAttribute.HTTP_RESPONSE)); default: return super.getMember(name); } } @Override public boolean hasMember(String name) { switch (name) { case FrameworkConstants.JSAttributes.JS_REQUESTED_ACR: return getWrapped().getRequestedAcr() != null; case FrameworkConstants.JSAttributes.JS_AUTHENTICATED_SUBJECT: return getWrapped().getSubject() != null; case FrameworkConstants.JSAttributes.JS_LAST_AUTHENTICATED_USER: return getWrapped().getLastAuthenticatedUser() != null; case FrameworkConstants.JSAttributes.JS_TENANT_DOMAIN: return getWrapped().getTenantDomain() != null; case FrameworkConstants.JSAttributes.JS_SERVICE_PROVIDER_NAME: return getWrapped().getServiceProviderName() != null; case FrameworkConstants.JSAttributes.JS_REQUEST: return hasTransientValueInParameters(FrameworkConstants.RequestAttribute.HTTP_REQUEST); case FrameworkConstants.JSAttributes.JS_RESPONSE: return hasTransientValueInParameters(FrameworkConstants.RequestAttribute.HTTP_RESPONSE); default: return super.hasMember(name); } } @Override public void removeMember(String name) { switch (name) { case FrameworkConstants.JSAttributes.JS_SELECTED_ACR: getWrapped().setSelectedAcr(null); break; default: super.removeMember(name); } } @Override public void setMember(String name, Object value) { switch (name) { case FrameworkConstants.JSAttributes.JS_SELECTED_ACR: getWrapped().setSelectedAcr(String.valueOf(value)); break; default: super.setMember(name, value); } } private boolean hasTransientValueInParameters(String key) { TransientObjectWrapper transientObjectWrapper = (TransientObjectWrapper) getWrapped().getParameter(key); return transientObjectWrapper != null && transientObjectWrapper.getWrapped() != null; } }
components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/config/model/graph/js/JsAuthenticationContext.java
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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. */ package org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js; import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; import org.wso2.carbon.identity.application.authentication.framework.context.TransientObjectWrapper; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants; /** * Javascript wrapper for Java level AuthenticationContext. * This provides controlled access to AuthenticationContext object via provided javascript native syntax. * e.g * var requestedAcr = context.requestedAcr * <p> * instead of * var requestedAcr = context.getRequestedAcr() * <p> * Also it prevents writing an arbitrary values to the respective fields, keeping consistency on runtime * AuthenticationContext. * * @see AuthenticationContext */ public class JsAuthenticationContext extends AbstractJSObjectWrapper<AuthenticationContext> { public JsAuthenticationContext(AuthenticationContext wrapped) { super(wrapped); } @Override public Object getMember(String name) { switch (name) { case FrameworkConstants.JSAttributes.JS_REQUESTED_ACR: return getWrapped().getRequestedAcr(); case FrameworkConstants.JSAttributes.JS_AUTHENTICATED_SUBJECT: return new JsAuthenticatedUser(getWrapped().getSubject()); case FrameworkConstants.JSAttributes.JS_LAST_AUTHENTICATED_USER: return new JsAuthenticatedUser(getWrapped().getLastAuthenticatedUser()); case FrameworkConstants.JSAttributes.JS_TENANT_DOMAIN: return getWrapped().getTenantDomain(); case FrameworkConstants.JSAttributes.JS_SERVICE_PROVIDER_NAME: return getWrapped().getServiceProviderName(); case FrameworkConstants.JSAttributes.JS_REQUEST: return new JsServletRequest((TransientObjectWrapper) getWrapped() .getParameter(FrameworkConstants.RequestAttribute.HTTP_REQUEST)); case FrameworkConstants.JSAttributes.JS_RESPONSE: return new JsServletResponse((TransientObjectWrapper) getWrapped() .getParameter(FrameworkConstants.RequestAttribute.HTTP_REQUEST)); default: return super.getMember(name); } } @Override public boolean hasMember(String name) { switch (name) { case FrameworkConstants.JSAttributes.JS_REQUESTED_ACR: return getWrapped().getRequestedAcr() != null; case FrameworkConstants.JSAttributes.JS_AUTHENTICATED_SUBJECT: return getWrapped().getSubject() != null; case FrameworkConstants.JSAttributes.JS_LAST_AUTHENTICATED_USER: return getWrapped().getLastAuthenticatedUser() != null; case FrameworkConstants.JSAttributes.JS_TENANT_DOMAIN: return getWrapped().getTenantDomain() != null; case FrameworkConstants.JSAttributes.JS_SERVICE_PROVIDER_NAME: return getWrapped().getServiceProviderName() != null; case FrameworkConstants.JSAttributes.JS_REQUEST: return hasTransientValueInParameters(FrameworkConstants.RequestAttribute.HTTP_REQUEST); case FrameworkConstants.JSAttributes.JS_RESPONSE: return hasTransientValueInParameters(FrameworkConstants.RequestAttribute.HTTP_RESPONSE); default: return super.hasMember(name); } } @Override public void removeMember(String name) { switch (name) { case FrameworkConstants.JSAttributes.JS_SELECTED_ACR: getWrapped().setSelectedAcr(null); break; default: super.removeMember(name); } } @Override public void setMember(String name, Object value) { switch (name) { case FrameworkConstants.JSAttributes.JS_SELECTED_ACR: getWrapped().setSelectedAcr(String.valueOf(value)); break; default: super.setMember(name, value); } } private boolean hasTransientValueInParameters(String key) { TransientObjectWrapper transientObjectWrapper = (TransientObjectWrapper) getWrapped().getParameter(key); return transientObjectWrapper != null && transientObjectWrapper.getWrapped() != null; } }
Fix: JS context.response returns the HttpRequest, instead of response.
components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/config/model/graph/js/JsAuthenticationContext.java
Fix: JS context.response returns the HttpRequest, instead of response.
<ide><path>omponents/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/config/model/graph/js/JsAuthenticationContext.java <ide> .getParameter(FrameworkConstants.RequestAttribute.HTTP_REQUEST)); <ide> case FrameworkConstants.JSAttributes.JS_RESPONSE: <ide> return new JsServletResponse((TransientObjectWrapper) getWrapped() <del> .getParameter(FrameworkConstants.RequestAttribute.HTTP_REQUEST)); <add> .getParameter(FrameworkConstants.RequestAttribute.HTTP_RESPONSE)); <ide> default: <ide> return super.getMember(name); <ide> }
Java
bsd-3-clause
24057be617a9587dfe938030e8f02ad11cba2a41
0
JosephCottam/AbstractRendering,ahmadia/AbstractRendering,JosephCottam/AbstractRendering,JosephCottam/AbstractRendering,ahmadia/AbstractRendering,ahmadia/AbstractRendering,ahmadia/AbstractRendering,ahmadia/AbstractRendering,JosephCottam/AbstractRendering,JosephCottam/AbstractRendering
package ar.app.display; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JPanel; import ar.Aggregates; import ar.Aggregator; import ar.Glyphset; import ar.Renderer; import ar.Transfer; import ar.app.components.LabeledItem; /**Host a panel with an optional draw-on overlay**/ public class OverlayHost extends ARComponent.Aggregating { private static final long serialVersionUID = -6449887730981205865L; private ARComponent.Aggregating hosted; private SelectionOverlay overlay; /**Host the given component in the overlay.**/ public OverlayHost(ARComponent.Aggregating hosted) { this.hosted = hosted; this.overlay = new SelectionOverlay(this); this.add(overlay); this.add(hosted); overlay.setVisible(false); } public void layout() { Rectangle b = this.getBounds(); hosted.setBounds(b); overlay.setBounds(b); } /**Is the overlay currently visible?**/ public boolean showOverlay() {return overlay.isVisible();} /**Set the overlay visibility state.**/ public void showOverlay(boolean show) {overlay.setVisible(show);} private static class SelectionOverlay extends JComponent implements Selectable { private static final long serialVersionUID = 9079768489874376280L; public Color MASKED = new Color(100,100,100,50); public Color SELECTED = new Color(200,0,0,50); public Color PROVISIONAL = Color.black; private Rectangle2D selection = null; private boolean provisional = false; private final OverlayHost host; public SelectionOverlay(OverlayHost host) { AdjustRange r = new AdjustRange(this); this.addMouseListener(r); this.addMouseMotionListener(r); this.host = host; } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2= (Graphics2D) g; Area a =new Area(this.getBounds()); Shape s = host.viewTransform().createTransformedShape(selection); if (selection != null) { g.setColor(SELECTED); g2.fill(s); a.subtract(new Area(s)); if (provisional) { g2.setColor(PROVISIONAL); g2.draw(s); } g2.setColor(MASKED); g2.fill(a); } else { g2.setColor(SELECTED); g2.fill(a); } } public void clear() { this.selection = null; provisional = false; } /**Set the current selection to a new value. * To indicate transient state, set the "provisional" flag. * * TODO: Add flag for "extend" vs "replace" ***/ public void setSelection(Rectangle2D bounds, boolean provisional) { try {this.selection = host.viewTransform().createInverse().createTransformedShape(bounds).getBounds2D();} catch (Exception e) {/*Ignore...should be impossible...should be.*/} this.provisional=provisional; this.repaint(); } } private interface Selectable { public void clear(); public void setSelection(Rectangle2D bounds, boolean provisional); } //TODO: Add keyboard support for "clear" and "invert" //TODO: Add multi-region selection private final static class AdjustRange implements MouseListener, MouseMotionListener { Point2D start; final Selectable target; public AdjustRange(Selectable target) {this.target = target;} public void mousePressed(MouseEvent e) {start = e.getPoint();} public void mouseReleased(MouseEvent e) { if (start != null) { Rectangle2D bounds =bounds(e); if (bounds.isEmpty() || bounds.getWidth()*bounds.getHeight()<1) {bounds = null;} target.setSelection(bounds, false); } start = null; } public void mouseClicked(MouseEvent e) {target.clear();} public void mouseDragged(MouseEvent e) { if (start != null) { Rectangle2D bounds =bounds(e); if (bounds.isEmpty() || bounds.getWidth()*bounds.getHeight()<1) {bounds = null;} target.setSelection(bounds, true); } } private Rectangle2D bounds(MouseEvent e) { double w = Math.abs(start.getX()-e.getX()); double h = Math.abs(start.getY()-e.getY()); double x = Math.min(start.getX(), e.getX()); double y = Math.min(start.getY(), e.getY()); return new Rectangle2D.Double(x,y,w,h); } public void mouseMoved(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} } public Transfer<?, ?> transfer() {return hosted.transfer();} public void transfer(Transfer<?, ?> t) {hosted.transfer(t);} public Aggregates<?> aggregates() {return hosted.aggregates();} public void aggregates(Aggregates<?> aggregates) {hosted.aggregates(aggregates);} public Aggregates<?> refAggregates() {return hosted.refAggregates();} public void refAggregates(Aggregates<?> aggregates) {hosted.refAggregates(aggregates);} public Glyphset<?> dataset() {return hosted.dataset();} public void dataset(Glyphset<?> data) { hosted.dataset(data); overlay.clear(); } public Aggregator<?, ?> aggregator() {return hosted.aggregator();} public void aggregator(Aggregator<?, ?> aggregator) {hosted.aggregator(aggregator);} public Renderer renderer() {return hosted.renderer();} public void zoomFit() {hosted.zoomFit();} public AffineTransform viewTransform() {return hosted.viewTransform();} public void viewTransform(AffineTransform vt) throws NoninvertibleTransformException {hosted.viewTransform(vt);} /**Toggle control for the given overlay.**/ public static final class Control extends JPanel { private static final long serialVersionUID = -4922729009197379804L; private final JCheckBox box = new JCheckBox(); private OverlayHost host=null; /**Create a toggle control. Will have no effect until 'host' is set.**/ public Control() { JPanel item = new LabeledItem("Show Overlay:", box); this.add(item); box.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { boolean show = ((JCheckBox)e.getSource()).isSelected(); host().showOverlay(show); host().repaint(); } catch (Exception ex) {/**Ignored**/} } }); } /**Get the target host control.**/ public OverlayHost host() {return host;} /**Set the target host control.**/ public void host(OverlayHost host) {this.host = host;} } }
AbstractRendering/app/ar/app/display/OverlayHost.java
package ar.app.display; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JPanel; import ar.Aggregates; import ar.Aggregator; import ar.Glyphset; import ar.Renderer; import ar.Transfer; import ar.app.components.LabeledItem; import ar.util.Util; /**Host a panel with an optional draw-on overlay**/ public class OverlayHost extends ARComponent.Aggregating { private static final long serialVersionUID = -6449887730981205865L; private ARComponent.Aggregating hosted; private JComponent overlay; /**Host the given component in the overlay.**/ public OverlayHost(ARComponent.Aggregating hosted) { this.hosted = hosted; this.overlay = new SelectionOverlay(this); this.add(overlay); this.add(hosted); overlay.setVisible(false); } public void layout() { Rectangle b = this.getBounds(); hosted.setBounds(b); overlay.setBounds(b); } /**Is the overlay currently visible?**/ public boolean showOverlay() {return overlay.isVisible();} /**Set the overlay visibility state.**/ public void showOverlay(boolean show) {overlay.setVisible(show);} private static class SelectionOverlay extends JComponent implements Selectable { private static final long serialVersionUID = 9079768489874376280L; public Color MASKED = new Color(100,100,100,50); public Color SELECTED = new Color(200,0,0,50); public Color PROVISIONAL = Color.black; private Rectangle2D selection = null; private boolean provisional = false; private final OverlayHost host; public SelectionOverlay(OverlayHost host) { AdjustRange r = new AdjustRange(this); this.addMouseListener(r); this.addMouseMotionListener(r); this.host = host; } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2= (Graphics2D) g; //g2.setTransform(host.viewTransform()); Area a =new Area(this.getBounds()); if (selection != null) { g2.setColor(MASKED); g2.fill(a); g.setColor(SELECTED); g2.fill(selection); a.subtract(new Area(selection)); } else { g2.setColor(SELECTED); g2.fill(a); } if (provisional && selection != null) { g2.setColor(PROVISIONAL); g2.draw(selection); } } public void setSelection(Rectangle2D bounds) { this.selection = bounds; this.provisional=false; this.repaint(); } public void setProvisional(Rectangle2D bounds) { this.selection = bounds; this.provisional=true; this.repaint(); } } private interface Selectable { public void setSelection(Rectangle2D bounds); public void setProvisional(Rectangle2D bounds); } private final static class AdjustRange implements MouseListener, MouseMotionListener { Point2D start; final Selectable target; public AdjustRange(Selectable target) {this.target = target;} public void mousePressed(MouseEvent e) {start = e.getPoint();} public void mouseReleased(MouseEvent e) { if (start != null) { Rectangle2D bounds =bounds(e); if (bounds.isEmpty() || bounds.getWidth()*bounds.getHeight()<1) {bounds = null;} target.setSelection(bounds); } start = null; } public void mouseMoved(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseDragged(MouseEvent e) { if (start != null) { Rectangle2D bounds =bounds(e); if (bounds.isEmpty() || bounds.getWidth()*bounds.getHeight()<1) {bounds = null;} target.setProvisional(bounds); } } private Rectangle2D bounds(MouseEvent e) { double w = Math.abs(start.getX()-e.getX()); double h = Math.abs(start.getY()-e.getY()); double x = Math.min(start.getX(), e.getX()); double y = Math.min(start.getY(), e.getY()); return new Rectangle2D.Double(x,y,w,h); } } public Transfer<?, ?> transfer() {return hosted.transfer();} public void transfer(Transfer<?, ?> t) {hosted.transfer(t);} public Aggregates<?> aggregates() {return hosted.aggregates();} public void aggregates(Aggregates<?> aggregates) {hosted.aggregates(aggregates);} public Aggregates<?> refAggregates() {return hosted.refAggregates();} public void refAggregates(Aggregates<?> aggregates) {hosted.refAggregates(aggregates);} public Glyphset<?> dataset() {return hosted.dataset();} public void dataset(Glyphset<?> data) {hosted.dataset(data);} public Aggregator<?, ?> aggregator() {return hosted.aggregator();} public void aggregator(Aggregator<?, ?> aggregator) {hosted.aggregator(aggregator);} public Renderer renderer() {return hosted.renderer();} public void zoomFit() {hosted.zoomFit();} public AffineTransform viewTransform() {return hosted.viewTransform();} public void viewTransform(AffineTransform vt) throws NoninvertibleTransformException {hosted.viewTransform(vt);} /**Toggle control for the given overlay.**/ public static final class Control extends JPanel { private static final long serialVersionUID = -4922729009197379804L; private final JCheckBox box = new JCheckBox(); private OverlayHost host=null; /**Create a toggle control. Will have no effect until 'host' is set.**/ public Control() { JPanel item = new LabeledItem("Show Overlay:", box); this.add(item); box.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { boolean show = ((JCheckBox)e.getSource()).isSelected(); host().showOverlay(show); host().repaint(); } catch (Exception ex) {/**Ignored**/} } }); } /**Get the target host control.**/ public OverlayHost host() {return host;} /**Set the target host control.**/ public void host(OverlayHost host) {this.host = host;} } }
Overlay selection region tracks dataspace.
AbstractRendering/app/ar/app/display/OverlayHost.java
Overlay selection region tracks dataspace.
<ide><path>bstractRendering/app/ar/app/display/OverlayHost.java <ide> import java.awt.Graphics; <ide> import java.awt.Graphics2D; <ide> import java.awt.Rectangle; <add>import java.awt.Shape; <ide> import java.awt.event.ActionEvent; <ide> import java.awt.event.ActionListener; <ide> import java.awt.event.MouseEvent; <ide> import ar.Renderer; <ide> import ar.Transfer; <ide> import ar.app.components.LabeledItem; <del>import ar.util.Util; <ide> <ide> /**Host a panel with an optional draw-on overlay**/ <ide> public class OverlayHost extends ARComponent.Aggregating { <ide> private static final long serialVersionUID = -6449887730981205865L; <ide> <ide> private ARComponent.Aggregating hosted; <del> private JComponent overlay; <add> private SelectionOverlay overlay; <ide> <ide> /**Host the given component in the overlay.**/ <ide> public OverlayHost(ARComponent.Aggregating hosted) { <ide> public void paintComponent(Graphics g) { <ide> super.paintComponent(g); <ide> Graphics2D g2= (Graphics2D) g; <del> //g2.setTransform(host.viewTransform()); <ide> Area a =new Area(this.getBounds()); <ide> <add> Shape s = host.viewTransform().createTransformedShape(selection); <add> <ide> if (selection != null) { <add> g.setColor(SELECTED); <add> g2.fill(s); <add> a.subtract(new Area(s)); <add> <add> if (provisional) { <add> g2.setColor(PROVISIONAL); <add> g2.draw(s); <add> } <add> <ide> g2.setColor(MASKED); <ide> g2.fill(a); <del> <del> g.setColor(SELECTED); <del> g2.fill(selection); <del> a.subtract(new Area(selection)); <ide> } else { <ide> g2.setColor(SELECTED); <ide> g2.fill(a); <ide> } <ide> <del> if (provisional && selection != null) { <del> g2.setColor(PROVISIONAL); <del> g2.draw(selection); <del> } <del> } <del> <del> public void setSelection(Rectangle2D bounds) { <del> this.selection = bounds; <del> this.provisional=false; <add> } <add> <add> public void clear() { <add> this.selection = null; <add> provisional = false; <add> } <add> <add> /**Set the current selection to a new value. <add> * To indicate transient state, set the "provisional" flag. <add> * <add> * TODO: Add flag for "extend" vs "replace" <add> ***/ <add> public void setSelection(Rectangle2D bounds, boolean provisional) { <add> try {this.selection = host.viewTransform().createInverse().createTransformedShape(bounds).getBounds2D();} <add> catch (Exception e) {/*Ignore...should be impossible...should be.*/} <add> this.provisional=provisional; <ide> this.repaint(); <ide> } <del> <del> public void setProvisional(Rectangle2D bounds) { <del> this.selection = bounds; <del> this.provisional=true; <del> this.repaint(); <del> } <ide> } <ide> <ide> private interface Selectable { <del> public void setSelection(Rectangle2D bounds); <del> public void setProvisional(Rectangle2D bounds); <del> } <del> <add> public void clear(); <add> public void setSelection(Rectangle2D bounds, boolean provisional); <add> } <add> <add> //TODO: Add keyboard support for "clear" and "invert" <add> //TODO: Add multi-region selection <ide> private final static class AdjustRange implements MouseListener, MouseMotionListener { <ide> Point2D start; <ide> final Selectable target; <ide> if (start != null) { <ide> Rectangle2D bounds =bounds(e); <ide> if (bounds.isEmpty() || bounds.getWidth()*bounds.getHeight()<1) {bounds = null;} <del> target.setSelection(bounds); <add> target.setSelection(bounds, false); <ide> } <ide> start = null; <ide> } <ide> <del> public void mouseMoved(MouseEvent e) {} <del> <del> public void mouseClicked(MouseEvent e) {} <del> public void mouseEntered(MouseEvent e) {} <del> public void mouseExited(MouseEvent e) {} <add> public void mouseClicked(MouseEvent e) {target.clear();} <ide> public void mouseDragged(MouseEvent e) { <ide> if (start != null) { <ide> Rectangle2D bounds =bounds(e); <ide> if (bounds.isEmpty() || bounds.getWidth()*bounds.getHeight()<1) {bounds = null;} <del> target.setProvisional(bounds); <add> target.setSelection(bounds, true); <ide> } <ide> } <del> <add> <ide> private Rectangle2D bounds(MouseEvent e) { <ide> double w = Math.abs(start.getX()-e.getX()); <ide> double h = Math.abs(start.getY()-e.getY()); <ide> <ide> return new Rectangle2D.Double(x,y,w,h); <ide> } <add> <add> public void mouseMoved(MouseEvent e) {} <add> public void mouseEntered(MouseEvent e) {} <add> public void mouseExited(MouseEvent e) {} <ide> } <ide> <ide> public Transfer<?, ?> transfer() {return hosted.transfer();} <ide> public Aggregates<?> refAggregates() {return hosted.refAggregates();} <ide> public void refAggregates(Aggregates<?> aggregates) {hosted.refAggregates(aggregates);} <ide> public Glyphset<?> dataset() {return hosted.dataset();} <del> public void dataset(Glyphset<?> data) {hosted.dataset(data);} <add> <add> public void dataset(Glyphset<?> data) { <add> hosted.dataset(data); <add> overlay.clear(); <add> } <add> <ide> public Aggregator<?, ?> aggregator() {return hosted.aggregator();} <ide> public void aggregator(Aggregator<?, ?> aggregator) {hosted.aggregator(aggregator);} <ide> public Renderer renderer() {return hosted.renderer();}
Java
apache-2.0
31dbd1508a7157f5c239ff7aee5ade171435c53f
0
robin13/elasticsearch,uschindler/elasticsearch,uschindler/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch,robin13/elasticsearch,gingerwizard/elasticsearch,HonzaKral/elasticsearch,scorpionvicky/elasticsearch,nknize/elasticsearch,coding0011/elasticsearch,HonzaKral/elasticsearch,GlenRSmith/elasticsearch,nknize/elasticsearch,GlenRSmith/elasticsearch,nknize/elasticsearch,GlenRSmith/elasticsearch,GlenRSmith/elasticsearch,gingerwizard/elasticsearch,coding0011/elasticsearch,nknize/elasticsearch,gingerwizard/elasticsearch,gingerwizard/elasticsearch,gingerwizard/elasticsearch,coding0011/elasticsearch,scorpionvicky/elasticsearch,uschindler/elasticsearch,coding0011/elasticsearch,scorpionvicky/elasticsearch,HonzaKral/elasticsearch,coding0011/elasticsearch,uschindler/elasticsearch,GlenRSmith/elasticsearch,HonzaKral/elasticsearch,nknize/elasticsearch,gingerwizard/elasticsearch,scorpionvicky/elasticsearch,scorpionvicky/elasticsearch,robin13/elasticsearch,robin13/elasticsearch,uschindler/elasticsearch
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.dataframe.checkpoint; import org.elasticsearch.action.admin.indices.stats.CommonStats; import org.elasticsearch.action.admin.indices.stats.ShardStats; import org.elasticsearch.cluster.routing.RecoverySource; import org.elasticsearch.cluster.routing.RecoverySource.PeerRecoverySource; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.UnassignedInfo; import org.elasticsearch.common.UUIDs; import org.elasticsearch.index.Index; import org.elasticsearch.index.cache.query.QueryCacheStats; import org.elasticsearch.index.cache.request.RequestCacheStats; import org.elasticsearch.index.engine.SegmentsStats; import org.elasticsearch.index.fielddata.FieldDataStats; import org.elasticsearch.index.flush.FlushStats; import org.elasticsearch.index.get.GetStats; import org.elasticsearch.index.merge.MergeStats; import org.elasticsearch.index.refresh.RefreshStats; import org.elasticsearch.index.search.stats.SearchStats; import org.elasticsearch.index.seqno.SeqNoStats; import org.elasticsearch.index.shard.DocsStats; import org.elasticsearch.index.shard.IndexingStats; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.shard.ShardPath; import org.elasticsearch.index.store.StoreStats; import org.elasticsearch.index.warmer.WarmerStats; import org.elasticsearch.search.suggest.completion.CompletionStats; import org.elasticsearch.test.ESTestCase; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import static org.hamcrest.Matchers.containsString; public class DataFrameTransformsCheckpointServiceTests extends ESTestCase { public void testExtractIndexCheckpoints() { Map<String, long[]> expectedCheckpoints = new HashMap<>(); Set<String> indices = randomUserIndices(); ShardStats[] shardStatsArray = createRandomShardStats(expectedCheckpoints, indices, false, false); Map<String, long[]> checkpoints = DataFrameTransformsCheckpointService.extractIndexCheckPoints(shardStatsArray, indices); assertEquals(expectedCheckpoints.size(), checkpoints.size()); assertEquals(expectedCheckpoints.keySet(), checkpoints.keySet()); // low-level compare for (Entry<String, long[]> entry : expectedCheckpoints.entrySet()) { assertTrue(Arrays.equals(entry.getValue(), checkpoints.get(entry.getKey()))); } } public void testExtractIndexCheckpointsLostPrimaries() { Map<String, long[]> expectedCheckpoints = new HashMap<>(); Set<String> indices = randomUserIndices(); ShardStats[] shardStatsArray = createRandomShardStats(expectedCheckpoints, indices, true, false); Map<String, long[]> checkpoints = DataFrameTransformsCheckpointService.extractIndexCheckPoints(shardStatsArray, indices); assertEquals(expectedCheckpoints.size(), checkpoints.size()); assertEquals(expectedCheckpoints.keySet(), checkpoints.keySet()); // low-level compare for (Entry<String, long[]> entry : expectedCheckpoints.entrySet()) { assertTrue(Arrays.equals(entry.getValue(), checkpoints.get(entry.getKey()))); } } public void testExtractIndexCheckpointsInconsistentGlobalCheckpoints() { Map<String, long[]> expectedCheckpoints = new HashMap<>(); Set<String> indices = randomUserIndices(); ShardStats[] shardStatsArray = createRandomShardStats(expectedCheckpoints, indices, randomBoolean(), true); // fail CheckpointException e = expectThrows(CheckpointException.class, () -> DataFrameTransformsCheckpointService.extractIndexCheckPoints(shardStatsArray, indices)); assertThat(e.getMessage(), containsString("Global checkpoints mismatch")); } /** * Create a random set of 3 index names * @return set of indices a simulated user has access to */ private static Set<String> randomUserIndices() { Set<String> indices = new HashSet<>(); // never create an empty set if (randomBoolean()) { indices.add("index-1"); } else { indices.add("index-2"); } if (randomBoolean()) { indices.add("index-3"); } return indices; } /** * create a ShardStats for testing with random fuzzing * * @param expectedCheckpoints output parameter to return the checkpoints to expect * @param userIndices set of indices that are visible * @param skipPrimaries whether some shards do not have a primary shard at random * @param inconsistentGlobalCheckpoints whether to introduce inconsistent global checkpoints * @return array of ShardStats */ private static ShardStats[] createRandomShardStats(Map<String, long[]> expectedCheckpoints, Set<String> userIndices, boolean skipPrimaries, boolean inconsistentGlobalCheckpoints) { // always create the full list List<Index> indices = new ArrayList<>(); indices.add(new Index("index-1", UUIDs.randomBase64UUID(random()))); indices.add(new Index("index-2", UUIDs.randomBase64UUID(random()))); indices.add(new Index("index-3", UUIDs.randomBase64UUID(random()))); List<ShardStats> shardStats = new ArrayList<>(); for (final Index index : indices) { int numShards = randomIntBetween(1, 5); List<Long> checkpoints = new ArrayList<>(); for (int shardIndex = 0; shardIndex < numShards; shardIndex++) { // we need at least one replica for testing int numShardCopies = randomIntBetween(2, 4); int primaryShard = 0; if (skipPrimaries) { primaryShard = randomInt(numShardCopies - 1); } int inconsistentReplica = -1; if (inconsistentGlobalCheckpoints) { List<Integer> replicas = new ArrayList<>(numShardCopies - 1); for (int i = 0; i < numShardCopies; i++) { if (primaryShard != i) { replicas.add(i); } } inconsistentReplica = randomFrom(replicas); } // SeqNoStats asserts that checkpoints are logical long localCheckpoint = randomLongBetween(0L, 100000000L); long globalCheckpoint = randomBoolean() ? localCheckpoint : randomLongBetween(0L, 100000000L); long maxSeqNo = Math.max(localCheckpoint, globalCheckpoint); final SeqNoStats validSeqNoStats = new SeqNoStats(maxSeqNo, localCheckpoint, globalCheckpoint); checkpoints.add(globalCheckpoint); for (int replica = 0; replica < numShardCopies; replica++) { ShardId shardId = new ShardId(index, shardIndex); boolean primary = (replica == primaryShard); Path path = createTempDir().resolve("indices").resolve(index.getUUID()).resolve(String.valueOf(shardIndex)); ShardRouting shardRouting = ShardRouting.newUnassigned(shardId, primary, primary ? RecoverySource.EmptyStoreRecoverySource.INSTANCE : PeerRecoverySource.INSTANCE, new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, null) ); shardRouting = shardRouting.initialize("node-0", null, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE); shardRouting = shardRouting.moveToStarted(); CommonStats stats = new CommonStats(); stats.fieldData = new FieldDataStats(); stats.queryCache = new QueryCacheStats(); stats.docs = new DocsStats(); stats.store = new StoreStats(); stats.indexing = new IndexingStats(); stats.search = new SearchStats(); stats.segments = new SegmentsStats(); stats.merge = new MergeStats(); stats.refresh = new RefreshStats(); stats.completion = new CompletionStats(); stats.requestCache = new RequestCacheStats(); stats.get = new GetStats(); stats.flush = new FlushStats(); stats.warmer = new WarmerStats(); if (inconsistentReplica == replica) { // overwrite SeqNoStats invalidSeqNoStats = new SeqNoStats(maxSeqNo, localCheckpoint, globalCheckpoint + randomLongBetween(10L, 100L)); shardStats.add( new ShardStats(shardRouting, new ShardPath(false, path, path, shardId), stats, null, invalidSeqNoStats, null)); } else { shardStats.add( new ShardStats(shardRouting, new ShardPath(false, path, path, shardId), stats, null, validSeqNoStats, null)); } } } if (userIndices.contains(index.getName())) { expectedCheckpoints.put(index.getName(), checkpoints.stream().mapToLong(l -> l).toArray()); } } // shuffle the shard stats Collections.shuffle(shardStats, random()); ShardStats[] shardStatsArray = shardStats.toArray(new ShardStats[0]); return shardStatsArray; } }
x-pack/plugin/data-frame/src/test/java/org/elasticsearch/xpack/dataframe/checkpoint/DataFrameTransformsCheckpointServiceTests.java
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.dataframe.checkpoint; import org.elasticsearch.action.admin.indices.stats.CommonStats; import org.elasticsearch.action.admin.indices.stats.ShardStats; import org.elasticsearch.cluster.routing.RecoverySource; import org.elasticsearch.cluster.routing.RecoverySource.PeerRecoverySource; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.UnassignedInfo; import org.elasticsearch.common.UUIDs; import org.elasticsearch.index.Index; import org.elasticsearch.index.cache.query.QueryCacheStats; import org.elasticsearch.index.cache.request.RequestCacheStats; import org.elasticsearch.index.engine.SegmentsStats; import org.elasticsearch.index.fielddata.FieldDataStats; import org.elasticsearch.index.flush.FlushStats; import org.elasticsearch.index.get.GetStats; import org.elasticsearch.index.merge.MergeStats; import org.elasticsearch.index.refresh.RefreshStats; import org.elasticsearch.index.search.stats.SearchStats; import org.elasticsearch.index.seqno.SeqNoStats; import org.elasticsearch.index.shard.DocsStats; import org.elasticsearch.index.shard.IndexingStats; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.shard.ShardPath; import org.elasticsearch.index.store.StoreStats; import org.elasticsearch.index.warmer.WarmerStats; import org.elasticsearch.search.suggest.completion.CompletionStats; import org.elasticsearch.test.ESTestCase; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import static org.hamcrest.Matchers.containsString; public class DataFrameTransformsCheckpointServiceTests extends ESTestCase { public void testExtractIndexCheckpoints() { Map<String, long[]> expectedCheckpoints = new HashMap<>(); Set<String> indices = randomUserIndices(); ShardStats[] shardStatsArray = createRandomShardStats(expectedCheckpoints, indices, false, false); Map<String, long[]> checkpoints = DataFrameTransformsCheckpointService.extractIndexCheckPoints(shardStatsArray, indices); assertEquals(expectedCheckpoints.size(), checkpoints.size()); assertEquals(expectedCheckpoints.keySet(), checkpoints.keySet()); // low-level compare for (Entry<String, long[]> entry : expectedCheckpoints.entrySet()) { assertTrue(Arrays.equals(entry.getValue(), checkpoints.get(entry.getKey()))); } } public void testExtractIndexCheckpointsLostPrimaries() { Map<String, long[]> expectedCheckpoints = new HashMap<>(); Set<String> indices = randomUserIndices(); ShardStats[] shardStatsArray = createRandomShardStats(expectedCheckpoints, indices, true, false); Map<String, long[]> checkpoints = DataFrameTransformsCheckpointService.extractIndexCheckPoints(shardStatsArray, indices); assertEquals(expectedCheckpoints.size(), checkpoints.size()); assertEquals(expectedCheckpoints.keySet(), checkpoints.keySet()); // low-level compare for (Entry<String, long[]> entry : expectedCheckpoints.entrySet()) { assertTrue(Arrays.equals(entry.getValue(), checkpoints.get(entry.getKey()))); } } @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/40368") public void testExtractIndexCheckpointsInconsistentGlobalCheckpoints() { Map<String, long[]> expectedCheckpoints = new HashMap<>(); Set<String> indices = randomUserIndices(); ShardStats[] shardStatsArray = createRandomShardStats(expectedCheckpoints, indices, randomBoolean(), true); // fail CheckpointException e = expectThrows(CheckpointException.class, () -> DataFrameTransformsCheckpointService.extractIndexCheckPoints(shardStatsArray, indices)); assertThat(e.getMessage(), containsString("Global checkpoints mismatch")); } /** * Create a random set of 3 index names * @return set of indices a simulated user has access to */ private static Set<String> randomUserIndices() { Set<String> indices = new HashSet<>(); // never create an empty set if (randomBoolean()) { indices.add("index-1"); } else { indices.add("index-2"); } if (randomBoolean()) { indices.add("index-3"); } return indices; } /** * create a ShardStats for testing with random fuzzing * * @param expectedCheckpoints output parameter to return the checkpoints to expect * @param userIndices set of indices that are visible * @param skipPrimaries whether some shards do not have a primary shard at random * @param inconsistentGlobalCheckpoints whether to introduce inconsistent global checkpoints * @return array of ShardStats */ private static ShardStats[] createRandomShardStats(Map<String, long[]> expectedCheckpoints, Set<String> userIndices, boolean skipPrimaries, boolean inconsistentGlobalCheckpoints) { // always create the full list List<Index> indices = new ArrayList<>(); indices.add(new Index("index-1", UUIDs.randomBase64UUID(random()))); indices.add(new Index("index-2", UUIDs.randomBase64UUID(random()))); indices.add(new Index("index-3", UUIDs.randomBase64UUID(random()))); List<ShardStats> shardStats = new ArrayList<>(); for (final Index index : indices) { int numShards = randomIntBetween(1, 5); List<Long> checkpoints = new ArrayList<>(); for (int shardIndex = 0; shardIndex < numShards; shardIndex++) { // we need at least one replica for testing int numShardCopies = randomIntBetween(2, 4); int primaryShard = 0; if (skipPrimaries) { primaryShard = randomInt(numShardCopies - 1); } int inconsistentReplica = -1; if (inconsistentGlobalCheckpoints) { List<Integer> replicas = new ArrayList<>(numShardCopies - 1); for (int i = 0; i < numShardCopies; i++) { if (primaryShard != i) { replicas.add(i); } } inconsistentReplica = randomFrom(replicas); } // SeqNoStats asserts that checkpoints are logical long localCheckpoint = randomLongBetween(0L, 100000000L); long globalCheckpoint = randomBoolean() ? localCheckpoint : randomLongBetween(0L, 100000000L); long maxSeqNo = Math.max(localCheckpoint, globalCheckpoint); SeqNoStats seqNoStats = new SeqNoStats(maxSeqNo, localCheckpoint, globalCheckpoint); checkpoints.add(globalCheckpoint); for (int replica = 0; replica < numShardCopies; replica++) { ShardId shardId = new ShardId(index, shardIndex); boolean primary = (replica == primaryShard); Path path = createTempDir().resolve("indices").resolve(index.getUUID()).resolve(String.valueOf(shardIndex)); ShardRouting shardRouting = ShardRouting.newUnassigned(shardId, primary, primary ? RecoverySource.EmptyStoreRecoverySource.INSTANCE : PeerRecoverySource.INSTANCE, new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, null) ); shardRouting = shardRouting.initialize("node-0", null, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE); shardRouting = shardRouting.moveToStarted(); CommonStats stats = new CommonStats(); stats.fieldData = new FieldDataStats(); stats.queryCache = new QueryCacheStats(); stats.docs = new DocsStats(); stats.store = new StoreStats(); stats.indexing = new IndexingStats(); stats.search = new SearchStats(); stats.segments = new SegmentsStats(); stats.merge = new MergeStats(); stats.refresh = new RefreshStats(); stats.completion = new CompletionStats(); stats.requestCache = new RequestCacheStats(); stats.get = new GetStats(); stats.flush = new FlushStats(); stats.warmer = new WarmerStats(); if (inconsistentReplica == replica) { // overwrite seqNoStats = new SeqNoStats(maxSeqNo, localCheckpoint, globalCheckpoint + randomLongBetween(10L, 100L)); } shardStats.add(new ShardStats(shardRouting, new ShardPath(false, path, path, shardId), stats, null, seqNoStats, null)); } } if (userIndices.contains(index.getName())) { expectedCheckpoints.put(index.getName(), checkpoints.stream().mapToLong(l -> l).toArray()); } } // shuffle the shard stats Collections.shuffle(shardStats, random()); ShardStats[] shardStatsArray = shardStats.toArray(new ShardStats[0]); return shardStatsArray; } }
[ML] addressing test failure (#40701) * [ML] Fixing test * adjusting line lengths * marking valid seqno as final
x-pack/plugin/data-frame/src/test/java/org/elasticsearch/xpack/dataframe/checkpoint/DataFrameTransformsCheckpointServiceTests.java
[ML] addressing test failure (#40701)
<ide><path>-pack/plugin/data-frame/src/test/java/org/elasticsearch/xpack/dataframe/checkpoint/DataFrameTransformsCheckpointServiceTests.java <ide> } <ide> } <ide> <del> @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/40368") <ide> public void testExtractIndexCheckpointsInconsistentGlobalCheckpoints() { <ide> Map<String, long[]> expectedCheckpoints = new HashMap<>(); <ide> Set<String> indices = randomUserIndices(); <ide> long globalCheckpoint = randomBoolean() ? localCheckpoint : randomLongBetween(0L, 100000000L); <ide> long maxSeqNo = Math.max(localCheckpoint, globalCheckpoint); <ide> <del> SeqNoStats seqNoStats = new SeqNoStats(maxSeqNo, localCheckpoint, globalCheckpoint); <add> final SeqNoStats validSeqNoStats = new SeqNoStats(maxSeqNo, localCheckpoint, globalCheckpoint); <ide> checkpoints.add(globalCheckpoint); <ide> <ide> for (int replica = 0; replica < numShardCopies; replica++) { <ide> <ide> if (inconsistentReplica == replica) { <ide> // overwrite <del> seqNoStats = new SeqNoStats(maxSeqNo, localCheckpoint, globalCheckpoint + randomLongBetween(10L, 100L)); <add> SeqNoStats invalidSeqNoStats = <add> new SeqNoStats(maxSeqNo, localCheckpoint, globalCheckpoint + randomLongBetween(10L, 100L)); <add> shardStats.add( <add> new ShardStats(shardRouting, <add> new ShardPath(false, path, path, shardId), stats, null, invalidSeqNoStats, null)); <add> } else { <add> shardStats.add( <add> new ShardStats(shardRouting, <add> new ShardPath(false, path, path, shardId), stats, null, validSeqNoStats, null)); <ide> } <del> <del> shardStats.add(new ShardStats(shardRouting, new ShardPath(false, path, path, shardId), stats, null, seqNoStats, null)); <ide> } <ide> } <ide>
JavaScript
mit
2ce8a39d380b447a33b49b71635a786a96654746
0
arunoda/meteor-smart-collections,arunoda/meteor-smart-collections
laika/tests/queue_invalidator.js
var assert = require('assert'); global._ = require('../../node_modules/underscore'); require('./loader')('lib/queue_invalidator'); suite('Queue Invalidator', function() { test('insert', function(done) { var qi = new Meteor.SmartQueueInvalidator({ insert: function(id, doc) { assert.equal(id, 'id1'); assert.deepEqual(doc, {aa: 20}); done(); } }); qi.insert('id1', {aa: 20}); }); test('update with id', function(done) { var result; var qi = new Meteor.SmartQueueInvalidator({ update: function(id, doc, callback) { result = [id, doc]; callback(); } }); qi.update('id1', {$set: {aa: 10}}); assert.deepEqual(result, ['id1', {aa: 1}]); assert.deepEqual(qi._idQueues, {id1: []}); assert.deepEqual(qi._idsProcessing, []); done(); }); test('update with id twice', function(done) { var results = []; var qi = new Meteor.SmartQueueInvalidator({ update: function(id, doc, callback) { results.push([id, doc]); setTimeout(callback, 0); } }); qi.update('id1', {$set: {aa: 10}}); qi.update('id1', {$set: {bb: 10}}); assert.deepEqual(qi._idQueues, {id1: [['u', 'id1', {$set: {bb: 10}}]]}); assert.deepEqual(qi._idsProcessing, ['id1']); setTimeout(function() { assert.deepEqual(results, [['id1', {aa: 1}], ['id1', {bb: 1}]]); assert.deepEqual(qi._idQueues, {id1: []}); assert.deepEqual(qi._idsProcessing, []); done(); }, 10); }); test('update with different id', function(done) { var results = []; var qi = new Meteor.SmartQueueInvalidator({ update: function(id, doc, callback) { results.push([id, doc]); setTimeout(callback, 0); } }); qi.update('id1', {$set: {aa: 10}}); qi.update('id2', {$set: {bb: 10}}); assert.deepEqual(qi._idQueues, {id1: [], id2: []}); assert.deepEqual(qi._idsProcessing, ['id1', 'id2']); setTimeout(function() { assert.deepEqual(results, [['id1', {aa: 1}], ['id2', {bb: 1}]]); assert.deepEqual(qi._idQueues, {id1: [], id2: []}); assert.deepEqual(qi._idsProcessing, []); done(); }, 10); }); test('remove while queued', function(done) { var results = []; var qi = new Meteor.SmartQueueInvalidator({ remove: function(id) { results.push(id); } }); qi._idQueues = {'id1': [['u', 'id1', {$set: {bb: 19}}]]} qi.remove('id1'); assert.deepEqual(qi._idQueues, {}); assert.deepEqual(results, ['id1']); done(); }); test('multi update once', function(done) { var results = []; var qi = new Meteor.SmartQueueInvalidator({ multiUpdate: function(selector, fields, callback) { results.push([selector, fields]); setTimeout(callback, 0); } }); qi.multiUpdate({aa: 10}, {$set: {bb: 20}}); assert.equal(qi._globalProcessing, true); assert.deepEqual(qi._globalQueue, []); assert.equal(qi._globalHook, null); setTimeout(function() { assert.deepEqual(results, [[{aa: 10}, {bb: 1}]]); assert.equal(qi._globalProcessing, false); assert.deepEqual(qi._globalQueue, []); assert.equal(qi._globalHook, null); done(); }, 10); }); test('multi update and multi remove once', function(done) { var results = []; var qi = new Meteor.SmartQueueInvalidator({ multiUpdate: function(selector, fields, callback) { results.push([selector, fields]); setTimeout(callback, 0); }, multiRemove: function(selector, callback) { results.push([selector]); setTimeout(callback, 0); } }); qi.multiUpdate({aa: 10}, {$set: {bb: 20}}); qi.multiRemove({cc: 10}); assert.equal(qi._globalProcessing, true); assert.deepEqual(qi._globalQueue, [['mr', {cc: 10}]]); assert.equal(qi._globalHook, null); setTimeout(function() { assert.deepEqual(results, [[{aa: 10}, {bb: 1}], [{cc: 10}]]); assert.equal(qi._globalProcessing, false); assert.deepEqual(qi._globalQueue, []); assert.equal(qi._globalHook, null); done(); }, 10); }); test('adding id update after while multi remove', function(done) { var results = []; var qi = new Meteor.SmartQueueInvalidator({ multiUpdate: function(selector, fields, callback) { results.push([selector, fields]); setTimeout(callback, 0); }, update: function(id, fields, callback) { results.push([id, fields]); setTimeout(callback, 0); } }); qi.multiUpdate({aa: 10}, {$set: {bb: 20}}); qi.update('id1', {$set: {cc: 20}}); assert.deepEqual(qi._idQueues, {}); assert.equal(qi._globalProcessing, true); assert.deepEqual(qi._globalQueue, [['u', 'id1', {$set: {cc: 20}}]]); assert.equal(qi._globalHook, null); setTimeout(function() { assert.deepEqual(results, [[{aa: 10}, {bb: 1}], ['id1', {cc: 1}]]); assert.equal(qi._globalProcessing, false); assert.deepEqual(qi._globalQueue, []); assert.equal(qi._globalHook, null); assert.deepEqual(qi._idsProcessing, []); assert.deepEqual(qi._idQueues, {id1: []}); done(); }, 10); }); test('add id update, multi update at once', function(done) { var results = []; var qi = new Meteor.SmartQueueInvalidator({ multiUpdate: function(selector, fields, callback) { results.push([selector, fields]); setTimeout(callback, 0); }, update: function(id, fields, callback) { results.push([id, fields]); setTimeout(callback, 0); } }); qi.update('id1', {$set: {cc: 20}}); qi.multiUpdate({aa: 10}, {$set: {bb: 20}}); assert.deepEqual(qi._idQueues, {id1: []}); assert.deepEqual(qi._idsProcessing, ['id1']); assert.equal(qi._globalProcessing, false); assert.deepEqual(qi._globalQueue, [['mu', {aa: 10}, {$set: {bb: 20}}]]); assert.equal(typeof(qi._globalHook), 'function'); setTimeout(function() { assert.deepEqual(results, [['id1', {cc: 1}], [{aa: 10}, {bb: 1}]]); assert.equal(qi._globalProcessing, false); assert.deepEqual(qi._globalQueue, []); assert.equal(qi._globalHook, null); assert.deepEqual(qi._idsProcessing, []); assert.deepEqual(qi._idQueues, {id1: []}); done(); }, 10); }); // test('add multi update, id update, multi remove at once', function(done) { // var results = []; // var qi = new Meteor.SmartQueueInvalidator({ // multiUpdate: function(selector, fields, callback) { // results.push([selector, fields]); // setTimeout(callback, 0); // }, // update: function(id, fields, callback) { // results.push([id, fields]); // callback(); // assert.deepEqual(qi._globalProcessing, true); // assert.deepEqual(qi._globalQueue, []); // }, // multiRemove: function(selector, callback) { // results.push([selector]); // setTimeout(callback, 0); // } // }); // qi.multiUpdate({aa: 10}, {$set: {bb: 20}}); // qi.update('id1', {$set: {aa: 30}}); // qi.multiRemove({cc: 10}); // assert.deepEqual(qi._globalProcessing, true); // assert.deepEqual(qi._globalQueue[ // ['u', 'id1', {$set: {aa: 30}}], // ['mr', {cc: 10}] // ]); // setTimeout(function() { // assert.deepEqual(results, [ // [{aa: 10}, {bb: 1}], // ['id1', {aa: 1}], // [{cc: 10}] // ]); // done(); // }, 10); // }); });
removed queue invalidator tests
laika/tests/queue_invalidator.js
removed queue invalidator tests
<ide><path>aika/tests/queue_invalidator.js <del>var assert = require('assert'); <del>global._ = require('../../node_modules/underscore'); <del>require('./loader')('lib/queue_invalidator'); <del> <del>suite('Queue Invalidator', function() { <del> test('insert', function(done) { <del> var qi = new Meteor.SmartQueueInvalidator({ <del> insert: function(id, doc) { <del> assert.equal(id, 'id1'); <del> assert.deepEqual(doc, {aa: 20}); <del> done(); <del> } <del> }); <del> qi.insert('id1', {aa: 20}); <del> }); <del> <del> test('update with id', function(done) { <del> var result; <del> var qi = new Meteor.SmartQueueInvalidator({ <del> update: function(id, doc, callback) { <del> result = [id, doc]; <del> callback(); <del> } <del> }); <del> qi.update('id1', {$set: {aa: 10}}); <del> assert.deepEqual(result, ['id1', {aa: 1}]); <del> assert.deepEqual(qi._idQueues, {id1: []}); <del> assert.deepEqual(qi._idsProcessing, []); <del> done(); <del> }); <del> <del> test('update with id twice', function(done) { <del> var results = []; <del> var qi = new Meteor.SmartQueueInvalidator({ <del> update: function(id, doc, callback) { <del> results.push([id, doc]); <del> setTimeout(callback, 0); <del> } <del> }); <del> qi.update('id1', {$set: {aa: 10}}); <del> qi.update('id1', {$set: {bb: 10}}); <del> <del> assert.deepEqual(qi._idQueues, {id1: [['u', 'id1', {$set: {bb: 10}}]]}); <del> assert.deepEqual(qi._idsProcessing, ['id1']); <del> <del> setTimeout(function() { <del> assert.deepEqual(results, [['id1', {aa: 1}], ['id1', {bb: 1}]]); <del> assert.deepEqual(qi._idQueues, {id1: []}); <del> assert.deepEqual(qi._idsProcessing, []); <del> done(); <del> }, 10); <del> <del> }); <del> <del> test('update with different id', function(done) { <del> var results = []; <del> var qi = new Meteor.SmartQueueInvalidator({ <del> update: function(id, doc, callback) { <del> results.push([id, doc]); <del> setTimeout(callback, 0); <del> } <del> }); <del> qi.update('id1', {$set: {aa: 10}}); <del> qi.update('id2', {$set: {bb: 10}}); <del> <del> assert.deepEqual(qi._idQueues, {id1: [], id2: []}); <del> assert.deepEqual(qi._idsProcessing, ['id1', 'id2']); <del> <del> setTimeout(function() { <del> assert.deepEqual(results, [['id1', {aa: 1}], ['id2', {bb: 1}]]); <del> assert.deepEqual(qi._idQueues, {id1: [], id2: []}); <del> assert.deepEqual(qi._idsProcessing, []); <del> done(); <del> }, 10); <del> }); <del> <del> test('remove while queued', function(done) { <del> var results = []; <del> var qi = new Meteor.SmartQueueInvalidator({ <del> remove: function(id) { <del> results.push(id); <del> } <del> }); <del> qi._idQueues = {'id1': [['u', 'id1', {$set: {bb: 19}}]]} <del> qi.remove('id1'); <del> <del> assert.deepEqual(qi._idQueues, {}); <del> assert.deepEqual(results, ['id1']); <del> done(); <del> }); <del> <del> test('multi update once', function(done) { <del> var results = []; <del> var qi = new Meteor.SmartQueueInvalidator({ <del> multiUpdate: function(selector, fields, callback) { <del> results.push([selector, fields]); <del> setTimeout(callback, 0); <del> } <del> }); <del> qi.multiUpdate({aa: 10}, {$set: {bb: 20}}); <del> <del> assert.equal(qi._globalProcessing, true); <del> assert.deepEqual(qi._globalQueue, []); <del> assert.equal(qi._globalHook, null); <del> <del> setTimeout(function() { <del> assert.deepEqual(results, [[{aa: 10}, {bb: 1}]]); <del> assert.equal(qi._globalProcessing, false); <del> assert.deepEqual(qi._globalQueue, []); <del> assert.equal(qi._globalHook, null); <del> done(); <del> }, 10); <del> }); <del> <del> test('multi update and multi remove once', function(done) { <del> var results = []; <del> var qi = new Meteor.SmartQueueInvalidator({ <del> multiUpdate: function(selector, fields, callback) { <del> results.push([selector, fields]); <del> setTimeout(callback, 0); <del> }, <del> multiRemove: function(selector, callback) { <del> results.push([selector]); <del> setTimeout(callback, 0); <del> } <del> }); <del> qi.multiUpdate({aa: 10}, {$set: {bb: 20}}); <del> qi.multiRemove({cc: 10}); <del> <del> assert.equal(qi._globalProcessing, true); <del> assert.deepEqual(qi._globalQueue, [['mr', {cc: 10}]]); <del> assert.equal(qi._globalHook, null); <del> <del> setTimeout(function() { <del> assert.deepEqual(results, [[{aa: 10}, {bb: 1}], [{cc: 10}]]); <del> assert.equal(qi._globalProcessing, false); <del> assert.deepEqual(qi._globalQueue, []); <del> assert.equal(qi._globalHook, null); <del> done(); <del> }, 10); <del> }); <del> <del> test('adding id update after while multi remove', function(done) { <del> var results = []; <del> var qi = new Meteor.SmartQueueInvalidator({ <del> multiUpdate: function(selector, fields, callback) { <del> results.push([selector, fields]); <del> setTimeout(callback, 0); <del> }, <del> update: function(id, fields, callback) { <del> results.push([id, fields]); <del> setTimeout(callback, 0); <del> } <del> }); <del> qi.multiUpdate({aa: 10}, {$set: {bb: 20}}); <del> qi.update('id1', {$set: {cc: 20}}); <del> <del> assert.deepEqual(qi._idQueues, {}); <del> assert.equal(qi._globalProcessing, true); <del> assert.deepEqual(qi._globalQueue, [['u', 'id1', {$set: {cc: 20}}]]); <del> assert.equal(qi._globalHook, null); <del> <del> setTimeout(function() { <del> assert.deepEqual(results, [[{aa: 10}, {bb: 1}], ['id1', {cc: 1}]]); <del> assert.equal(qi._globalProcessing, false); <del> assert.deepEqual(qi._globalQueue, []); <del> assert.equal(qi._globalHook, null); <del> assert.deepEqual(qi._idsProcessing, []); <del> assert.deepEqual(qi._idQueues, {id1: []}); <del> <del> done(); <del> }, 10); <del> }); <del> <del> test('add id update, multi update at once', function(done) { <del> var results = []; <del> var qi = new Meteor.SmartQueueInvalidator({ <del> multiUpdate: function(selector, fields, callback) { <del> results.push([selector, fields]); <del> setTimeout(callback, 0); <del> }, <del> update: function(id, fields, callback) { <del> results.push([id, fields]); <del> setTimeout(callback, 0); <del> } <del> }); <del> qi.update('id1', {$set: {cc: 20}}); <del> qi.multiUpdate({aa: 10}, {$set: {bb: 20}}); <del> <del> assert.deepEqual(qi._idQueues, {id1: []}); <del> assert.deepEqual(qi._idsProcessing, ['id1']); <del> assert.equal(qi._globalProcessing, false); <del> assert.deepEqual(qi._globalQueue, [['mu', {aa: 10}, {$set: {bb: 20}}]]); <del> assert.equal(typeof(qi._globalHook), 'function'); <del> <del> setTimeout(function() { <del> assert.deepEqual(results, [['id1', {cc: 1}], [{aa: 10}, {bb: 1}]]); <del> assert.equal(qi._globalProcessing, false); <del> assert.deepEqual(qi._globalQueue, []); <del> assert.equal(qi._globalHook, null); <del> assert.deepEqual(qi._idsProcessing, []); <del> assert.deepEqual(qi._idQueues, {id1: []}); <del> <del> done(); <del> }, 10); <del> }); <del> <del> // test('add multi update, id update, multi remove at once', function(done) { <del> // var results = []; <del> // var qi = new Meteor.SmartQueueInvalidator({ <del> // multiUpdate: function(selector, fields, callback) { <del> // results.push([selector, fields]); <del> // setTimeout(callback, 0); <del> // }, <del> // update: function(id, fields, callback) { <del> // results.push([id, fields]); <del> // callback(); <del> // assert.deepEqual(qi._globalProcessing, true); <del> // assert.deepEqual(qi._globalQueue, []); <del> // }, <del> // multiRemove: function(selector, callback) { <del> // results.push([selector]); <del> // setTimeout(callback, 0); <del> // } <del> // }); <del> <del> // qi.multiUpdate({aa: 10}, {$set: {bb: 20}}); <del> // qi.update('id1', {$set: {aa: 30}}); <del> // qi.multiRemove({cc: 10}); <del> <del> // assert.deepEqual(qi._globalProcessing, true); <del> // assert.deepEqual(qi._globalQueue[ <del> // ['u', 'id1', {$set: {aa: 30}}], <del> // ['mr', {cc: 10}] <del> // ]); <del> <del> // setTimeout(function() { <del> // assert.deepEqual(results, [ <del> // [{aa: 10}, {bb: 1}], <del> // ['id1', {aa: 1}], <del> // [{cc: 10}] <del> // ]); <del> // done(); <del> // }, 10); <del> // }); <del>});
JavaScript
mit
cbecf0c7fb4dcbef1a65b098df5732fef82358f1
0
tilmanjusten/grunt-partial-extract,tilmanjusten/grunt-partial-extract
/* * grunt-partial-extract * https://github.com/tilmanjusten/grunt-partial-extract * * Copyright (c) 2015 Tilman Justen * Licensed under the MIT license. */ 'use strict'; module.exports = function (grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks var util = require('util'); var _ = require('lodash'); var path = require('path'); var options = {}; var InventoryObject = require('./../lib/inventory-object'); grunt.registerMultiTask('partial-extract', 'Extract partials from any text based files and write json inventory file.', function () { // Merge task-specific and/or target-specific options with these defaults. options = this.options({ // Find partials by pattern: // // <!-- extract:individual-file.html optional1:value optional2:value1:value2 --> // partial // <!-- endextract --> patternExtract: new RegExp(/<!--\s*extract:(.|\n)*?endextract\s?-->/g), // Wrap partial in template element and add options as data attributes templateWrap: { before: '<template id="partial" {{wrapData}}>', after: '</template>' }, // Wrap component for viewing purposes: e.g. add production context // // <!-- extract:individual-file.html wrap:<div class="context">:</div> --> // partial // <!-- endextract --> // // results in // // <div class="context"> // partial // </div> viewWrap: { before: '', after: '' }, // Base directory base: './inventory', // Partial directory where individual partial files will be stored (relative to base) partials: './partials', // Store inventory data as JSON file storage: 'partial-extract.json', // Enable storing partials as individual files storePartials: false, // Set indent value of partial code indent: ' ' }); grunt.log.writeln('Destination: ' + options.base); grunt.verbose.writeln('Files: ' + this.files.length); grunt.log.writeln(''); var processedBlocks = { options: options, length: 0, items: [] }; var uniqueBlocks = []; // Iterate over all specified file groups. this.files.forEach(function (file) { var content = grunt.util.normalizelf(grunt.file.read(file.src)); if (!options.patternExtract.test(content)) { grunt.log.errorlns('No partials in file ' + file.src); grunt.verbose.writeln(''); return; } var blocks = getPartials(content); grunt.log.oklns('Found ' + blocks.length + ' partials in file ' + file.src); // Write blocks to separate files blocks.map(function (block) { // init inventory object var opts = _.assign({}, options); var processed = new InventoryObject(); var isDuplicate = false; // process block processed.parseData(block, opts); processed.setProperty('origin', file.dest); processedBlocks.items.push(processed); if (uniqueBlocks.indexOf(processed.id) < 0) { uniqueBlocks.push(processed.id); } else { isDuplicate = true; } // store partial if not already happen if (options.storePartials && !isDuplicate) { grunt.file.write(path.resolve(options.base, options.partials, processed.id), processed.template); } }); grunt.verbose.writeln(''); }); processedBlocks.length = processedBlocks.items.length; grunt.file.write(path.resolve(options.base, options.storage), JSON.stringify(processedBlocks, null, '\t')); grunt.log.writeln(''); grunt.log.oklns('Extracted ' + processedBlocks.length + ' partials, ' + uniqueBlocks.length + ' unique.'); }); /** * extract partials * * @param src * @returns {Array} */ function getPartials(src) { return src.match(options.patternExtract); } };
tasks/partial_extract.js
/* * grunt-partial-extract * https://github.com/tilmanjusten/grunt-partial-extract * * Copyright (c) 2015 Tilman Justen * Licensed under the MIT license. */ 'use strict'; module.exports = function (grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks var util = require('util'); var _ = require('lodash'); var path = require('path'); var options = {}; var InventoryObject = require('./../lib/inventory-object'); grunt.registerMultiTask('partial-extract', 'Extract partials from any text based files and write json inventory file.', function () { // Merge task-specific and/or target-specific options with these defaults. options = this.options({ // Find partials by pattern: // // <!-- extract:individual-file.html optional1:value optional2:value1:value2 --> // partial // <!-- endextract --> patternExtract: new RegExp(/<!--\s*extract:(.|\n)*?endextract\s?-->/g), // Wrap partial in template element and add options as data attributes templateWrap: { before: '<template id="partial" {{wrapData}}>', after: '</template>' }, // Wrap component for viewing purposes: e.g. add production context // // <!-- extract:individual-file.html wrap:<div class="context">:</div> --> // partial // <!-- endextract --> // // results in // // <div class="context"> // partial // </div> viewWrap: { before: '', after: '' }, // Base directory base: './inventory', // Partial directory where individual partial files will be stored (relative to base) partials: './partials', // Store inventory data as JSON file storage: 'partial-extract.json', // Enable storing partials as individual files storePartials: false, // Set indent value of partial code indent: ' ' }); grunt.log.writeln('Destination: ' + options.base); grunt.verbose.writeln('Files: ' + this.files.length); grunt.log.writeln(''); var processedBlocks = { options: options, length: 0, items: [] }; // Iterate over all specified file groups. this.files.forEach(function (file) { var content = grunt.util.normalizelf(grunt.file.read(file.src)); if (!options.patternExtract.test(content)) { grunt.log.errorlns('No partials in file ' + file.src); grunt.verbose.writeln(''); return; } var blocks = getPartials(content); grunt.log.oklns('Found ' + blocks.length + ' partials in file ' + file.src); // Write blocks to separate files blocks.map(function (block) { // init inventory object var opts = _.assign({}, options); var processed = new InventoryObject(); // process block processed.parseData(block, opts); processed.setProperty('origin', file.dest); processedBlocks.items.push(processed); if (options.storePartials) { grunt.file.write(path.resolve(options.base, options.partials, processed.id), processed.template); } }); grunt.verbose.writeln(''); }); processedBlocks.length = processedBlocks.items.length; grunt.file.write(path.resolve(options.base, options.storage), JSON.stringify(processedBlocks, null, '\t')); grunt.log.writeln(''); grunt.log.oklns('Extracted ' + processedBlocks.length + ' partials.'); }); /** * extract partials * * @param src * @returns {Array} */ function getPartials(src) { return src.match(options.patternExtract); } };
Count unique blocks
tasks/partial_extract.js
Count unique blocks
<ide><path>asks/partial_extract.js <ide> length: 0, <ide> items: [] <ide> }; <add> var uniqueBlocks = []; <ide> <ide> // Iterate over all specified file groups. <ide> this.files.forEach(function (file) { <ide> // init inventory object <ide> var opts = _.assign({}, options); <ide> var processed = new InventoryObject(); <add> var isDuplicate = false; <ide> <ide> // process block <ide> processed.parseData(block, opts); <ide> <ide> processedBlocks.items.push(processed); <ide> <del> if (options.storePartials) { <add> if (uniqueBlocks.indexOf(processed.id) < 0) { <add> uniqueBlocks.push(processed.id); <add> } else { <add> isDuplicate = true; <add> } <add> <add> // store partial if not already happen <add> if (options.storePartials && !isDuplicate) { <ide> grunt.file.write(path.resolve(options.base, options.partials, processed.id), processed.template); <ide> } <ide> }); <ide> <ide> grunt.log.writeln(''); <ide> <del> grunt.log.oklns('Extracted ' + processedBlocks.length + ' partials.'); <add> grunt.log.oklns('Extracted ' + processedBlocks.length + ' partials, ' + uniqueBlocks.length + ' unique.'); <ide> }); <ide> <ide> /**
JavaScript
mit
7893dba6becdde1ef9819291f618136a8b9e1c85
0
tgriesser/graphql-js,gabelevi/graphql-js,graphql/graphql-js,baer/graphql-js,enaqx/graphql-js,gabelevi/graphql-js,baer/graphql-js,jjergus/graphql-js,enaqx/graphql-js,graphql/graphql-js,enaqx/graphql-js,jjergus/graphql-js,tgriesser/graphql-js,graphql/graphql-js
/* @flow */ /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import invariant from '../jsutils/invariant'; import isNullish from '../jsutils/isNullish'; import { ENUM } from '../language/kinds'; import { assertValidName } from '../utilities/assertValidName'; import type { OperationDefinitionNode, FieldNode, FragmentDefinitionNode, ValueNode, } from '../language/ast'; import type { GraphQLSchema } from './schema'; // Predicates & Assertions /** * These are all of the possible kinds of types. */ export type GraphQLType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<any> | GraphQLNonNull<any>; export function isType(type: mixed): boolean { return ( type instanceof GraphQLScalarType || type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType || type instanceof GraphQLEnumType || type instanceof GraphQLInputObjectType || type instanceof GraphQLList || type instanceof GraphQLNonNull ); } export function assertType(type: mixed): GraphQLType { invariant( isType(type), `Expected ${String(type)} to be a GraphQL type.` ); return (type: any); } /** * These types may be used as input types for arguments and directives. */ export type GraphQLInputType = GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLInputType> | GraphQLNonNull< GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLInputType> >; export function isInputType(type: ?GraphQLType): boolean { const namedType = getNamedType(type); return ( namedType instanceof GraphQLScalarType || namedType instanceof GraphQLEnumType || namedType instanceof GraphQLInputObjectType ); } export function assertInputType(type: ?GraphQLType): GraphQLInputType { invariant( isInputType(type), `Expected ${String(type)} to be a GraphQL input type.` ); return (type: any); } /** * These types may be used as output types as the result of fields. */ export type GraphQLOutputType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList<GraphQLOutputType> | GraphQLNonNull< GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList<GraphQLOutputType> >; export function isOutputType(type: ?GraphQLType): boolean { const namedType = getNamedType(type); return ( namedType instanceof GraphQLScalarType || namedType instanceof GraphQLObjectType || namedType instanceof GraphQLInterfaceType || namedType instanceof GraphQLUnionType || namedType instanceof GraphQLEnumType ); } export function assertOutputType(type: ?GraphQLType): GraphQLOutputType { invariant( isOutputType(type), `Expected ${String(type)} to be a GraphQL output type.`, ); return (type: any); } /** * These types may describe types which may be leaf values. */ export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType; export function isLeafType(type: ?GraphQLType): boolean { return ( type instanceof GraphQLScalarType || type instanceof GraphQLEnumType ); } export function assertLeafType(type: ?GraphQLType): GraphQLLeafType { invariant( isLeafType(type), `Expected ${String(type)} to be a GraphQL leaf type.`, ); return (type: any); } /** * These types may describe the parent context of a selection set. */ export type GraphQLCompositeType = GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType; export function isCompositeType(type: ?GraphQLType): boolean { return ( type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType ); } export function assertCompositeType(type: ?GraphQLType): GraphQLCompositeType { invariant( isCompositeType(type), `Expected ${String(type)} to be a GraphQL composite type.`, ); return (type: any); } /** * These types may describe the parent context of a selection set. */ export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionType; export function isAbstractType(type: ?GraphQLType): boolean { return ( type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType ); } export function assertAbstractType(type: ?GraphQLType): GraphQLAbstractType { invariant( isAbstractType(type), `Expected ${String(type)} to be a GraphQL abstract type.`, ); return (type: any); } /** * These types can all accept null as a value. */ export type GraphQLNullableType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<*>; export function getNullableType<T: GraphQLType>( type: ?T ): ?(T & GraphQLNullableType) { return type instanceof GraphQLNonNull ? type.ofType : type; } /** * These named types do not include modifiers like List or NonNull. */ export type GraphQLNamedType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType; export function isNamedType(type: ?GraphQLType): boolean { return ( type instanceof GraphQLScalarType || type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType || type instanceof GraphQLEnumType || type instanceof GraphQLInputObjectType ); } export function assertNamedType(type: ?GraphQLType): GraphQLNamedType { invariant( isNamedType(type), `Expected ${String(type)} to be a GraphQL named type.`, ); return (type: any); } export function getNamedType(type: ?GraphQLType): ?GraphQLNamedType { let unmodifiedType = type; while ( unmodifiedType instanceof GraphQLList || unmodifiedType instanceof GraphQLNonNull ) { unmodifiedType = unmodifiedType.ofType; } return unmodifiedType; } /** * Used while defining GraphQL types to allow for circular references in * otherwise immutable type definitions. */ export type Thunk<T> = (() => T) | T; function resolveThunk<T>(thunk: Thunk<T>): T { return typeof thunk === 'function' ? thunk() : thunk; } /** * Scalar Type Definition * * The leaf values of any request and input values to arguments are * Scalars (or Enums) and are defined with a name and a series of functions * used to parse input from ast or variables and to ensure validity. * * Example: * * const OddType = new GraphQLScalarType({ * name: 'Odd', * serialize(value) { * return value % 2 === 1 ? value : null; * } * }); * */ export class GraphQLScalarType { name: string; description: ?string; _scalarConfig: GraphQLScalarTypeConfig<*, *>; constructor(config: GraphQLScalarTypeConfig<*, *>) { assertValidName(config.name); this.name = config.name; this.description = config.description; invariant( typeof config.serialize === 'function', `${this.name} must provide "serialize" function. If this custom Scalar ` + 'is also used as an input type, ensure "parseValue" and "parseLiteral" ' + 'functions are also provided.' ); if (config.parseValue || config.parseLiteral) { invariant( typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function', `${this.name} must provide both "parseValue" and "parseLiteral" ` + 'functions.' ); } this._scalarConfig = config; } // Serializes an internal value to include in a response. serialize(value: mixed): mixed { const serializer = this._scalarConfig.serialize; return serializer(value); } // Parses an externally provided value to use as an input. parseValue(value: mixed): mixed { const parser = this._scalarConfig.parseValue; return parser ? parser(value) : null; } // Parses an externally provided literal value to use as an input. parseLiteral(valueNode: ValueNode): mixed { const parser = this._scalarConfig.parseLiteral; return parser ? parser(valueNode) : null; } toString(): string { return this.name; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLScalarType.prototype.toJSON = GraphQLScalarType.prototype.inspect = GraphQLScalarType.prototype.toString; export type GraphQLScalarTypeConfig<TInternal, TExternal> = { name: string; description?: ?string; serialize: (value: mixed) => ?TExternal; parseValue?: (value: mixed) => ?TInternal; parseLiteral?: (valueNode: ValueNode) => ?TInternal; }; /** * Object Type Definition * * Almost all of the GraphQL types you define will be object types. Object types * have a name, but most importantly describe their fields. * * Example: * * const AddressType = new GraphQLObjectType({ * name: 'Address', * fields: { * street: { type: GraphQLString }, * number: { type: GraphQLInt }, * formatted: { * type: GraphQLString, * resolve(obj) { * return obj.number + ' ' + obj.street * } * } * } * }); * * When two types need to refer to each other, or a type needs to refer to * itself in a field, you can use a function expression (aka a closure or a * thunk) to supply the fields lazily. * * Example: * * const PersonType = new GraphQLObjectType({ * name: 'Person', * fields: () => ({ * name: { type: GraphQLString }, * bestFriend: { type: PersonType }, * }) * }); * */ export class GraphQLObjectType { name: string; description: ?string; isTypeOf: ?GraphQLIsTypeOfFn<*, *>; _typeConfig: GraphQLObjectTypeConfig<*, *>; _fields: GraphQLFieldMap<*, *>; _interfaces: Array<GraphQLInterfaceType>; constructor(config: GraphQLObjectTypeConfig<*, *>) { assertValidName(config.name, config.isIntrospection); this.name = config.name; this.description = config.description; if (config.isTypeOf) { invariant( typeof config.isTypeOf === 'function', `${this.name} must provide "isTypeOf" as a function.` ); } this.isTypeOf = config.isTypeOf; this._typeConfig = config; } getFields(): GraphQLFieldMap<*, *> { return this._fields || (this._fields = defineFieldMap(this, this._typeConfig.fields) ); } getInterfaces(): Array<GraphQLInterfaceType> { return this._interfaces || (this._interfaces = defineInterfaces(this, this._typeConfig.interfaces) ); } toString(): string { return this.name; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLObjectType.prototype.toJSON = GraphQLObjectType.prototype.inspect = GraphQLObjectType.prototype.toString; function defineInterfaces( type: GraphQLObjectType, interfacesThunk: Thunk<?Array<GraphQLInterfaceType>> ): Array<GraphQLInterfaceType> { const interfaces = resolveThunk(interfacesThunk); if (!interfaces) { return []; } invariant( Array.isArray(interfaces), `${type.name} interfaces must be an Array or a function which returns ` + 'an Array.' ); interfaces.forEach(iface => { invariant( iface instanceof GraphQLInterfaceType, `${type.name} may only implement Interface types, it cannot ` + `implement: ${String(iface)}.` ); if (typeof iface.resolveType !== 'function') { invariant( typeof type.isTypeOf === 'function', `Interface Type ${iface.name} does not provide a "resolveType" ` + `function and implementing Type ${type.name} does not provide a ` + '"isTypeOf" function. There is no way to resolve this implementing ' + 'type during execution.' ); } }); return interfaces; } function defineFieldMap<TSource, TContext>( type: GraphQLNamedType, fieldsThunk: Thunk<GraphQLFieldConfigMap<TSource, TContext>> ): GraphQLFieldMap<TSource, TContext> { const fieldMap = resolveThunk(fieldsThunk); invariant( isPlainObj(fieldMap), `${type.name} fields must be an object with field names as keys or a ` + 'function which returns such an object.' ); const fieldNames = Object.keys(fieldMap); invariant( fieldNames.length > 0, `${type.name} fields must be an object with field names as keys or a ` + 'function which returns such an object.' ); const resultFieldMap = {}; fieldNames.forEach(fieldName => { assertValidName(fieldName); const fieldConfig = fieldMap[fieldName]; invariant( isPlainObj(fieldConfig), `${type.name}.${fieldName} field config must be an object` ); invariant( !fieldConfig.hasOwnProperty('isDeprecated'), `${type.name}.${fieldName} should provide "deprecationReason" instead ` + 'of "isDeprecated".' ); const field = { ...fieldConfig, isDeprecated: Boolean(fieldConfig.deprecationReason), name: fieldName }; invariant( isOutputType(field.type), `${type.name}.${fieldName} field type must be Output Type but ` + `got: ${String(field.type)}.` ); invariant( isValidResolver(field.resolve), `${type.name}.${fieldName} field resolver must be a function if ` + `provided, but got: ${String(field.resolve)}.` ); const argsConfig = fieldConfig.args; if (!argsConfig) { field.args = []; } else { invariant( isPlainObj(argsConfig), `${type.name}.${fieldName} args must be an object with argument ` + 'names as keys.' ); field.args = Object.keys(argsConfig).map(argName => { assertValidName(argName); const arg = argsConfig[argName]; invariant( isInputType(arg.type), `${type.name}.${fieldName}(${argName}:) argument type must be ` + `Input Type but got: ${String(arg.type)}.` ); return { name: argName, description: arg.description === undefined ? null : arg.description, type: arg.type, defaultValue: arg.defaultValue }; }); } resultFieldMap[fieldName] = field; }); return resultFieldMap; } function isPlainObj(obj) { return obj && typeof obj === 'object' && !Array.isArray(obj); } // If a resolver is defined, it must be a function. function isValidResolver(resolver: any): boolean { return (resolver == null || typeof resolver === 'function'); } export type GraphQLObjectTypeConfig<TSource, TContext> = { name: string; interfaces?: Thunk<?Array<GraphQLInterfaceType>>; fields: Thunk<GraphQLFieldConfigMap<TSource, TContext>>; isTypeOf?: ?GraphQLIsTypeOfFn<TSource, TContext>; description?: ?string; isIntrospection?: boolean; }; export type GraphQLTypeResolver<TSource, TContext> = ( value: TSource, context: TContext, info: GraphQLResolveInfo ) => ?GraphQLObjectType | string | Promise<?GraphQLObjectType | string>; export type GraphQLIsTypeOfFn<TSource, TContext> = ( source: TSource, context: TContext, info: GraphQLResolveInfo ) => boolean | Promise<boolean>; export type GraphQLFieldResolver<TSource, TContext> = ( source: TSource, args: { [argName: string]: any }, context: TContext, info: GraphQLResolveInfo ) => mixed; export type GraphQLResolveInfo = { fieldName: string; fieldNodes: Array<FieldNode>; returnType: GraphQLOutputType; parentType: GraphQLCompositeType; path: ResponsePath; schema: GraphQLSchema; fragments: { [fragmentName: string]: FragmentDefinitionNode }; rootValue: mixed; operation: OperationDefinitionNode; variableValues: { [variableName: string]: mixed }; }; export type ResponsePath = { prev: ResponsePath, key: string | number } | void; export type GraphQLFieldConfig<TSource, TContext> = { type: GraphQLOutputType; args?: GraphQLFieldConfigArgumentMap; resolve?: GraphQLFieldResolver<TSource, TContext>; deprecationReason?: ?string; description?: ?string; }; export type GraphQLFieldConfigArgumentMap = { [argName: string]: GraphQLArgumentConfig; }; export type GraphQLArgumentConfig = { type: GraphQLInputType; defaultValue?: mixed; description?: ?string; }; export type GraphQLFieldConfigMap<TSource, TContext> = { [fieldName: string]: GraphQLFieldConfig<TSource, TContext>; }; export type GraphQLField<TSource, TContext> = { name: string; description: ?string; type: GraphQLOutputType; args: Array<GraphQLArgument>; resolve?: GraphQLFieldResolver<TSource, TContext>; isDeprecated?: boolean; deprecationReason?: ?string; }; export type GraphQLArgument = { name: string; type: GraphQLInputType; defaultValue?: mixed; description?: ?string; }; export type GraphQLFieldMap<TSource, TContext> = { [fieldName: string]: GraphQLField<TSource, TContext>; }; /** * Interface Type Definition * * When a field can return one of a heterogeneous set of types, a Interface type * is used to describe what types are possible, what fields are in common across * all types, as well as a function to determine which type is actually used * when the field is resolved. * * Example: * * const EntityType = new GraphQLInterfaceType({ * name: 'Entity', * fields: { * name: { type: GraphQLString } * } * }); * */ export class GraphQLInterfaceType { name: string; description: ?string; resolveType: ?GraphQLTypeResolver<*, *>; _typeConfig: GraphQLInterfaceTypeConfig<*, *>; _fields: GraphQLFieldMap<*, *>; constructor(config: GraphQLInterfaceTypeConfig<*, *>) { assertValidName(config.name); this.name = config.name; this.description = config.description; if (config.resolveType) { invariant( typeof config.resolveType === 'function', `${this.name} must provide "resolveType" as a function.` ); } this.resolveType = config.resolveType; this._typeConfig = config; } getFields(): GraphQLFieldMap<*, *> { return this._fields || (this._fields = defineFieldMap(this, this._typeConfig.fields)); } toString(): string { return this.name; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLInterfaceType.prototype.toJSON = GraphQLInterfaceType.prototype.inspect = GraphQLInterfaceType.prototype.toString; export type GraphQLInterfaceTypeConfig<TSource, TContext> = { name: string, fields: Thunk<GraphQLFieldConfigMap<TSource, TContext>>, /** * Optionally provide a custom type resolver function. If one is not provided, * the default implementation will call `isTypeOf` on each implementing * Object type. */ resolveType?: ?GraphQLTypeResolver<TSource, TContext>, description?: ?string }; /** * Union Type Definition * * When a field can return one of a heterogeneous set of types, a Union type * is used to describe what types are possible as well as providing a function * to determine which type is actually used when the field is resolved. * * Example: * * const PetType = new GraphQLUnionType({ * name: 'Pet', * types: [ DogType, CatType ], * resolveType(value) { * if (value instanceof Dog) { * return DogType; * } * if (value instanceof Cat) { * return CatType; * } * } * }); * */ export class GraphQLUnionType { name: string; description: ?string; resolveType: ?GraphQLTypeResolver<*, *>; _typeConfig: GraphQLUnionTypeConfig<*, *>; _types: Array<GraphQLObjectType>; _possibleTypeNames: {[typeName: string]: boolean}; constructor(config: GraphQLUnionTypeConfig<*, *>) { assertValidName(config.name); this.name = config.name; this.description = config.description; if (config.resolveType) { invariant( typeof config.resolveType === 'function', `${this.name} must provide "resolveType" as a function.` ); } this.resolveType = config.resolveType; this._typeConfig = config; } getTypes(): Array<GraphQLObjectType> { return this._types || (this._types = defineTypes(this, this._typeConfig.types) ); } toString(): string { return this.name; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLUnionType.prototype.toJSON = GraphQLUnionType.prototype.inspect = GraphQLUnionType.prototype.toString; function defineTypes( unionType: GraphQLUnionType, typesThunk: Thunk<Array<GraphQLObjectType>> ): Array<GraphQLObjectType> { const types = resolveThunk(typesThunk); invariant( Array.isArray(types) && types.length > 0, 'Must provide Array of types or a function which returns ' + `such an array for Union ${unionType.name}.` ); const includedTypeNames = {}; types.forEach(objType => { invariant( objType instanceof GraphQLObjectType, `${unionType.name} may only contain Object types, it cannot contain: ` + `${String(objType)}.` ); invariant( !includedTypeNames[objType.name], `${unionType.name} can include ${objType.name} type only once.` ); includedTypeNames[objType.name] = true; if (typeof unionType.resolveType !== 'function') { invariant( typeof objType.isTypeOf === 'function', `Union type "${unionType.name}" does not provide a "resolveType" ` + `function and possible type "${objType.name}" does not provide an ` + '"isTypeOf" function. There is no way to resolve this possible type ' + 'during execution.' ); } }); return types; } export type GraphQLUnionTypeConfig<TSource, TContext> = { name: string, types: Thunk<Array<GraphQLObjectType>>, /** * Optionally provide a custom type resolver function. If one is not provided, * the default implementation will call `isTypeOf` on each implementing * Object type. */ resolveType?: ?GraphQLTypeResolver<TSource, TContext>; description?: ?string; }; /** * Enum Type Definition * * Some leaf values of requests and input values are Enums. GraphQL serializes * Enum values as strings, however internally Enums can be represented by any * kind of type, often integers. * * Example: * * const RGBType = new GraphQLEnumType({ * name: 'RGB', * values: { * RED: { value: 0 }, * GREEN: { value: 1 }, * BLUE: { value: 2 } * } * }); * * Note: If a value is not provided in a definition, the name of the enum value * will be used as its internal value. */ export class GraphQLEnumType/* <T> */ { name: string; description: ?string; _enumConfig: GraphQLEnumTypeConfig/* <T> */; _values: Array<GraphQLEnumValue/* <T> */>; _valueLookup: Map<any/* T */, GraphQLEnumValue>; _nameLookup: { [valueName: string]: GraphQLEnumValue }; constructor(config: GraphQLEnumTypeConfig/* <T> */) { this.name = config.name; assertValidName(config.name, config.isIntrospection); this.description = config.description; this._values = defineEnumValues(this, config.values); this._enumConfig = config; } getValues(): Array<GraphQLEnumValue/* <T> */> { return this._values; } getValue(name: string): ?GraphQLEnumValue { return this._getNameLookup()[name]; } serialize(value: any/* T */): ?string { const enumValue = this._getValueLookup().get(value); return enumValue ? enumValue.name : null; } parseValue(value: mixed): ?any/* T */ { if (typeof value === 'string') { const enumValue = this._getNameLookup()[value]; if (enumValue) { return enumValue.value; } } } parseLiteral(valueNode: ValueNode): ?any/* T */ { if (valueNode.kind === ENUM) { const enumValue = this._getNameLookup()[valueNode.value]; if (enumValue) { return enumValue.value; } } } _getValueLookup(): Map<any/* T */, GraphQLEnumValue> { if (!this._valueLookup) { const lookup = new Map(); this.getValues().forEach(value => { lookup.set(value.value, value); }); this._valueLookup = lookup; } return this._valueLookup; } _getNameLookup(): { [valueName: string]: GraphQLEnumValue } { if (!this._nameLookup) { const lookup = Object.create(null); this.getValues().forEach(value => { lookup[value.name] = value; }); this._nameLookup = lookup; } return this._nameLookup; } toString(): string { return this.name; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLEnumType.prototype.toJSON = GraphQLEnumType.prototype.inspect = GraphQLEnumType.prototype.toString; function defineEnumValues( type: GraphQLEnumType, valueMap: GraphQLEnumValueConfigMap/* <T> */ ): Array<GraphQLEnumValue/* <T> */> { invariant( isPlainObj(valueMap), `${type.name} values must be an object with value names as keys.` ); const valueNames = Object.keys(valueMap); invariant( valueNames.length > 0, `${type.name} values must be an object with value names as keys.` ); return valueNames.map(valueName => { assertValidName(valueName); const value = valueMap[valueName]; invariant( isPlainObj(value), `${type.name}.${valueName} must refer to an object with a "value" key ` + `representing an internal value but got: ${String(value)}.` ); invariant( !value.hasOwnProperty('isDeprecated'), `${type.name}.${valueName} should provide "deprecationReason" instead ` + 'of "isDeprecated".' ); return { name: valueName, description: value.description, isDeprecated: Boolean(value.deprecationReason), deprecationReason: value.deprecationReason, value: isNullish(value.value) ? valueName : value.value, }; }); } export type GraphQLEnumTypeConfig/* <T> */ = { name: string; values: GraphQLEnumValueConfigMap/* <T> */; description?: ?string; isIntrospection?: boolean; }; export type GraphQLEnumValueConfigMap/* <T> */ = { [valueName: string]: GraphQLEnumValueConfig/* <T> */; }; export type GraphQLEnumValueConfig/* <T> */ = { value?: any/* T */; deprecationReason?: ?string; description?: ?string; }; export type GraphQLEnumValue/* <T> */ = { name: string; description: ?string; isDeprecated?: boolean; deprecationReason: ?string; value: any/* T */; }; /** * Input Object Type Definition * * An input object defines a structured collection of fields which may be * supplied to a field argument. * * Using `NonNull` will ensure that a value must be provided by the query * * Example: * * const GeoPoint = new GraphQLInputObjectType({ * name: 'GeoPoint', * fields: { * lat: { type: new GraphQLNonNull(GraphQLFloat) }, * lon: { type: new GraphQLNonNull(GraphQLFloat) }, * alt: { type: GraphQLFloat, defaultValue: 0 }, * } * }); * */ export class GraphQLInputObjectType { name: string; description: ?string; _typeConfig: GraphQLInputObjectTypeConfig; _fields: GraphQLInputFieldMap; constructor(config: GraphQLInputObjectTypeConfig) { assertValidName(config.name); this.name = config.name; this.description = config.description; this._typeConfig = config; } getFields(): GraphQLInputFieldMap { return this._fields || (this._fields = this._defineFieldMap()); } _defineFieldMap(): GraphQLInputFieldMap { const fieldMap: any = resolveThunk(this._typeConfig.fields); invariant( isPlainObj(fieldMap), `${this.name} fields must be an object with field names as keys or a ` + 'function which returns such an object.' ); const fieldNames = Object.keys(fieldMap); invariant( fieldNames.length > 0, `${this.name} fields must be an object with field names as keys or a ` + 'function which returns such an object.' ); const resultFieldMap = {}; fieldNames.forEach(fieldName => { assertValidName(fieldName); const field = { ...fieldMap[fieldName], name: fieldName }; invariant( isInputType(field.type), `${this.name}.${fieldName} field type must be Input Type but ` + `got: ${String(field.type)}.` ); invariant( field.resolve == null, `${this.name}.${fieldName} field type has a resolve property, but ` + 'Input Types cannot define resolvers.' ); resultFieldMap[fieldName] = field; }); return resultFieldMap; } toString(): string { return this.name; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLInputObjectType.prototype.toJSON = GraphQLInputObjectType.prototype.inspect = GraphQLInputObjectType.prototype.toString; export type GraphQLInputObjectTypeConfig = { name: string; fields: Thunk<GraphQLInputFieldConfigMap>; description?: ?string; }; export type GraphQLInputFieldConfig = { type: GraphQLInputType; defaultValue?: mixed; description?: ?string; }; export type GraphQLInputFieldConfigMap = { [fieldName: string]: GraphQLInputFieldConfig; }; export type GraphQLInputField = { name: string; type: GraphQLInputType; defaultValue?: mixed; description?: ?string; }; export type GraphQLInputFieldMap = { [fieldName: string]: GraphQLInputField; }; /** * List Modifier * * A list is a kind of type marker, a wrapping type which points to another * type. Lists are often created within the context of defining the fields of * an object type. * * Example: * * const PersonType = new GraphQLObjectType({ * name: 'Person', * fields: () => ({ * parents: { type: new GraphQLList(Person) }, * children: { type: new GraphQLList(Person) }, * }) * }) * */ export class GraphQLList<T: GraphQLType> { ofType: T; constructor(type: T) { invariant( isType(type), `Can only create List of a GraphQLType but got: ${String(type)}.` ); this.ofType = type; } toString(): string { return '[' + String(this.ofType) + ']'; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLList.prototype.toJSON = GraphQLList.prototype.inspect = GraphQLList.prototype.toString; /** * Non-Null Modifier * * A non-null is a kind of type marker, a wrapping type which points to another * type. Non-null types enforce that their values are never null and can ensure * an error is raised if this ever occurs during a request. It is useful for * fields which you can make a strong guarantee on non-nullability, for example * usually the id field of a database row will never be null. * * Example: * * const RowType = new GraphQLObjectType({ * name: 'Row', * fields: () => ({ * id: { type: new GraphQLNonNull(GraphQLString) }, * }) * }) * * Note: the enforcement of non-nullability occurs within the executor. */ export class GraphQLNonNull<T: GraphQLNullableType> { ofType: T; constructor(type: T) { invariant( isType(type) && !(type instanceof GraphQLNonNull), 'Can only create NonNull of a Nullable GraphQLType but got: ' + `${String(type)}.` ); this.ofType = type; } toString(): string { return this.ofType.toString() + '!'; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLNonNull.prototype.toJSON = GraphQLNonNull.prototype.inspect = GraphQLNonNull.prototype.toString;
src/type/definition.js
/* @flow */ /** * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import invariant from '../jsutils/invariant'; import isNullish from '../jsutils/isNullish'; import { ENUM } from '../language/kinds'; import { assertValidName } from '../utilities/assertValidName'; import type { OperationDefinitionNode, FieldNode, FragmentDefinitionNode, ValueNode, } from '../language/ast'; import type { GraphQLSchema } from './schema'; // Predicates & Assertions /** * These are all of the possible kinds of types. */ export type GraphQLType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<any> | GraphQLNonNull<any>; export function isType(type: mixed): boolean { return ( type instanceof GraphQLScalarType || type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType || type instanceof GraphQLEnumType || type instanceof GraphQLInputObjectType || type instanceof GraphQLList || type instanceof GraphQLNonNull ); } export function assertType(type: mixed): GraphQLType { invariant( isType(type), `Expected ${String(type)} to be a GraphQL type.` ); return (type: any); } /** * These types may be used as input types for arguments and directives. */ export type GraphQLInputType = GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLInputType> | GraphQLNonNull< GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<GraphQLInputType> >; export function isInputType(type: ?GraphQLType): boolean { const namedType = getNamedType(type); return ( namedType instanceof GraphQLScalarType || namedType instanceof GraphQLEnumType || namedType instanceof GraphQLInputObjectType ); } export function assertInputType(type: ?GraphQLType): GraphQLInputType { invariant( isInputType(type), `Expected ${String(type)} to be a GraphQL input type.` ); return (type: any); } /** * These types may be used as output types as the result of fields. */ export type GraphQLOutputType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList<GraphQLOutputType> | GraphQLNonNull< GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLList<GraphQLOutputType> >; export function isOutputType(type: ?GraphQLType): boolean { const namedType = getNamedType(type); return ( namedType instanceof GraphQLScalarType || namedType instanceof GraphQLObjectType || namedType instanceof GraphQLInterfaceType || namedType instanceof GraphQLUnionType || namedType instanceof GraphQLEnumType ); } export function assertOutputType(type: ?GraphQLType): GraphQLOutputType { invariant( isOutputType(type), `Expected ${String(type)} to be a GraphQL output type.`, ); return (type: any); } /** * These types may describe types which may be leaf values. */ export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType; export function isLeafType(type: ?GraphQLType): boolean { return ( type instanceof GraphQLScalarType || type instanceof GraphQLEnumType ); } export function assertLeafType(type: ?GraphQLType): GraphQLLeafType { invariant( isLeafType(type), `Expected ${String(type)} to be a GraphQL leaf type.`, ); return (type: any); } /** * These types may describe the parent context of a selection set. */ export type GraphQLCompositeType = GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType; export function isCompositeType(type: ?GraphQLType): boolean { return ( type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType ); } export function assertCompositeType(type: ?GraphQLType): GraphQLCompositeType { invariant( isCompositeType(type), `Expected ${String(type)} to be a GraphQL composite type.`, ); return (type: any); } /** * These types may describe the parent context of a selection set. */ export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionType; export function isAbstractType(type: ?GraphQLType): boolean { return ( type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType ); } export function assertAbstractType(type: ?GraphQLType): GraphQLAbstractType { invariant( isAbstractType(type), `Expected ${String(type)} to be a GraphQL abstract type.`, ); return (type: any); } /** * These types can all accept null as a value. */ export type GraphQLNullableType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType | GraphQLList<*>; export function getNullableType<T: GraphQLType>( type: ?T ): ?(T & GraphQLNullableType) { return type instanceof GraphQLNonNull ? type.ofType : type; } /** * These named types do not include modifiers like List or NonNull. */ export type GraphQLNamedType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType | GraphQLEnumType | GraphQLInputObjectType; export function isNamedType(type: ?GraphQLType): boolean { return ( type instanceof GraphQLScalarType || type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType || type instanceof GraphQLEnumType || type instanceof GraphQLInputObjectType ); } export function assertNamedType(type: ?GraphQLType): GraphQLNamedType { invariant( isNamedType(type), `Expected ${String(type)} to be a GraphQL named type.`, ); return (type: any); } export function getNamedType(type: ?GraphQLType): ?GraphQLNamedType { let unmodifiedType = type; while ( unmodifiedType instanceof GraphQLList || unmodifiedType instanceof GraphQLNonNull ) { unmodifiedType = unmodifiedType.ofType; } return unmodifiedType; } /** * Used while defining GraphQL types to allow for circular references in * otherwise immutable type definitions. */ export type Thunk<T> = (() => T) | T; function resolveThunk<T>(thunk: Thunk<T>): T { return typeof thunk === 'function' ? thunk() : thunk; } /** * Scalar Type Definition * * The leaf values of any request and input values to arguments are * Scalars (or Enums) and are defined with a name and a series of functions * used to parse input from ast or variables and to ensure validity. * * Example: * * const OddType = new GraphQLScalarType({ * name: 'Odd', * serialize(value) { * return value % 2 === 1 ? value : null; * } * }); * */ export class GraphQLScalarType { name: string; description: ?string; _scalarConfig: GraphQLScalarTypeConfig<*, *>; constructor(config: GraphQLScalarTypeConfig<*, *>) { assertValidName(config.name); this.name = config.name; this.description = config.description; invariant( typeof config.serialize === 'function', `${this.name} must provide "serialize" function. If this custom Scalar ` + 'is also used as an input type, ensure "parseValue" and "parseLiteral" ' + 'functions are also provided.' ); if (config.parseValue || config.parseLiteral) { invariant( typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function', `${this.name} must provide both "parseValue" and "parseLiteral" ` + 'functions.' ); } this._scalarConfig = config; } // Serializes an internal value to include in a response. serialize(value: mixed): mixed { const serializer = this._scalarConfig.serialize; return serializer(value); } // Parses an externally provided value to use as an input. parseValue(value: mixed): mixed { const parser = this._scalarConfig.parseValue; return parser ? parser(value) : null; } // Parses an externally provided literal value to use as an input. parseLiteral(valueNode: ValueNode): mixed { const parser = this._scalarConfig.parseLiteral; return parser ? parser(valueNode) : null; } toString(): string { return this.name; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLScalarType.prototype.toJSON = GraphQLScalarType.prototype.inspect = GraphQLScalarType.prototype.toString; export type GraphQLScalarTypeConfig<TInternal, TExternal> = { name: string; description?: ?string; serialize: (value: mixed) => ?TExternal; parseValue?: (value: mixed) => ?TInternal; parseLiteral?: (valueNode: ValueNode) => ?TInternal; }; /** * Object Type Definition * * Almost all of the GraphQL types you define will be object types. Object types * have a name, but most importantly describe their fields. * * Example: * * const AddressType = new GraphQLObjectType({ * name: 'Address', * fields: { * street: { type: GraphQLString }, * number: { type: GraphQLInt }, * formatted: { * type: GraphQLString, * resolve(obj) { * return obj.number + ' ' + obj.street * } * } * } * }); * * When two types need to refer to each other, or a type needs to refer to * itself in a field, you can use a function expression (aka a closure or a * thunk) to supply the fields lazily. * * Example: * * const PersonType = new GraphQLObjectType({ * name: 'Person', * fields: () => ({ * name: { type: GraphQLString }, * bestFriend: { type: PersonType }, * }) * }); * */ export class GraphQLObjectType { name: string; description: ?string; isTypeOf: ?GraphQLIsTypeOfFn<*, *>; _typeConfig: GraphQLObjectTypeConfig<*, *>; _fields: GraphQLFieldMap<*, *>; _interfaces: Array<GraphQLInterfaceType>; constructor(config: GraphQLObjectTypeConfig<*, *>) { assertValidName(config.name, config.isIntrospection); this.name = config.name; this.description = config.description; if (config.isTypeOf) { invariant( typeof config.isTypeOf === 'function', `${this.name} must provide "isTypeOf" as a function.` ); } this.isTypeOf = config.isTypeOf; this._typeConfig = config; } getFields(): GraphQLFieldMap<*, *> { return this._fields || (this._fields = defineFieldMap(this, this._typeConfig.fields) ); } getInterfaces(): Array<GraphQLInterfaceType> { return this._interfaces || (this._interfaces = defineInterfaces(this, this._typeConfig.interfaces) ); } toString(): string { return this.name; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLObjectType.prototype.toJSON = GraphQLObjectType.prototype.inspect = GraphQLObjectType.prototype.toString; function defineInterfaces( type: GraphQLObjectType, interfacesThunk: Thunk<?Array<GraphQLInterfaceType>> ): Array<GraphQLInterfaceType> { const interfaces = resolveThunk(interfacesThunk); if (!interfaces) { return []; } invariant( Array.isArray(interfaces), `${type.name} interfaces must be an Array or a function which returns ` + 'an Array.' ); interfaces.forEach(iface => { invariant( iface instanceof GraphQLInterfaceType, `${type.name} may only implement Interface types, it cannot ` + `implement: ${String(iface)}.` ); if (typeof iface.resolveType !== 'function') { invariant( typeof type.isTypeOf === 'function', `Interface Type ${iface.name} does not provide a "resolveType" ` + `function and implementing Type ${type.name} does not provide a ` + '"isTypeOf" function. There is no way to resolve this implementing ' + 'type during execution.' ); } }); return interfaces; } function defineFieldMap<TSource, TContext>( type: GraphQLNamedType, fieldsThunk: Thunk<GraphQLFieldConfigMap<TSource, TContext>> ): GraphQLFieldMap<TSource, TContext> { const fieldMap = resolveThunk(fieldsThunk); invariant( isPlainObj(fieldMap), `${type.name} fields must be an object with field names as keys or a ` + 'function which returns such an object.' ); const fieldNames = Object.keys(fieldMap); invariant( fieldNames.length > 0, `${type.name} fields must be an object with field names as keys or a ` + 'function which returns such an object.' ); const resultFieldMap = {}; fieldNames.forEach(fieldName => { assertValidName(fieldName); const fieldConfig = fieldMap[fieldName]; invariant( isPlainObj(fieldConfig), `${type.name}.${fieldName} field config must be an object` ); invariant( !fieldConfig.hasOwnProperty('isDeprecated'), `${type.name}.${fieldName} should provide "deprecationReason" instead ` + 'of "isDeprecated".' ); const field = { ...fieldConfig, isDeprecated: Boolean(fieldConfig.deprecationReason), name: fieldName }; invariant( isOutputType(field.type), `${type.name}.${fieldName} field type must be Output Type but ` + `got: ${String(field.type)}.` ); invariant( isValidResolver(field.resolve), `${type.name}.${fieldName} field resolver must be a function if ` + `provided, but got: ${String(field.resolve)}.` ); const argsConfig = fieldConfig.args; if (!argsConfig) { field.args = []; } else { invariant( isPlainObj(argsConfig), `${type.name}.${fieldName} args must be an object with argument ` + 'names as keys.' ); field.args = Object.keys(argsConfig).map(argName => { assertValidName(argName); const arg = argsConfig[argName]; invariant( isInputType(arg.type), `${type.name}.${fieldName}(${argName}:) argument type must be ` + `Input Type but got: ${String(arg.type)}.` ); return { name: argName, description: arg.description === undefined ? null : arg.description, type: arg.type, defaultValue: arg.defaultValue }; }); } resultFieldMap[fieldName] = field; }); return resultFieldMap; } function isPlainObj(obj) { return obj && typeof obj === 'object' && !Array.isArray(obj); } // If a resolver is defined, it must be a function. function isValidResolver(resolver: any): boolean { return (resolver == null || typeof resolver === 'function'); } export type GraphQLObjectTypeConfig<TSource, TContext> = { name: string; interfaces?: Thunk<?Array<GraphQLInterfaceType>>; fields: Thunk<GraphQLFieldConfigMap<TSource, TContext>>; isTypeOf?: ?GraphQLIsTypeOfFn<TSource, TContext>; description?: ?string; isIntrospection?: boolean; }; export type GraphQLTypeResolver<TSource, TContext> = ( value: TSource, context: TContext, info: GraphQLResolveInfo ) => ?GraphQLObjectType | string | Promise<?GraphQLObjectType | string>; export type GraphQLIsTypeOfFn<TSource, TContext> = ( source: TSource, context: TContext, info: GraphQLResolveInfo ) => boolean | Promise<boolean>; export type GraphQLFieldResolver<TSource, TContext> = ( source: TSource, args: { [argName: string]: any }, context: TContext, info: GraphQLResolveInfo ) => mixed; export type GraphQLResolveInfo = { fieldName: string; fieldNodes: Array<FieldNode>; returnType: GraphQLOutputType; parentType: GraphQLCompositeType; path: ResponsePath; schema: GraphQLSchema; fragments: { [fragmentName: string]: FragmentDefinitionNode }; rootValue: mixed; operation: OperationDefinitionNode; variableValues: { [variableName: string]: mixed }; }; export type ResponsePath = { prev: ResponsePath, key: string | number } | void; export type GraphQLFieldConfig<TSource, TContext> = { type: GraphQLOutputType; args?: GraphQLFieldConfigArgumentMap; resolve?: GraphQLFieldResolver<TSource, TContext>; deprecationReason?: ?string; description?: ?string; }; export type GraphQLFieldConfigArgumentMap = { [argName: string]: GraphQLArgumentConfig; }; export type GraphQLArgumentConfig = { type: GraphQLInputType; defaultValue?: mixed; description?: ?string; }; export type GraphQLFieldConfigMap<TSource, TContext> = { [fieldName: string]: GraphQLFieldConfig<TSource, TContext>; }; export type GraphQLField<TSource, TContext> = { name: string; description: ?string; type: GraphQLOutputType; args: Array<GraphQLArgument>; resolve?: GraphQLFieldResolver<TSource, TContext>; isDeprecated?: boolean; deprecationReason?: ?string; }; export type GraphQLArgument = { name: string; type: GraphQLInputType; defaultValue?: mixed; description?: ?string; }; export type GraphQLFieldMap<TSource, TContext> = { [fieldName: string]: GraphQLField<TSource, TContext>; }; /** * Interface Type Definition * * When a field can return one of a heterogeneous set of types, a Interface type * is used to describe what types are possible, what fields are in common across * all types, as well as a function to determine which type is actually used * when the field is resolved. * * Example: * * const EntityType = new GraphQLInterfaceType({ * name: 'Entity', * fields: { * name: { type: GraphQLString } * } * }); * */ export class GraphQLInterfaceType { name: string; description: ?string; resolveType: ?GraphQLTypeResolver<*, *>; _typeConfig: GraphQLInterfaceTypeConfig<*, *>; _fields: GraphQLFieldMap<*, *>; constructor(config: GraphQLInterfaceTypeConfig<*, *>) { assertValidName(config.name); this.name = config.name; this.description = config.description; if (config.resolveType) { invariant( typeof config.resolveType === 'function', `${this.name} must provide "resolveType" as a function.` ); } this.resolveType = config.resolveType; this._typeConfig = config; } getFields(): GraphQLFieldMap<*, *> { return this._fields || (this._fields = defineFieldMap(this, this._typeConfig.fields)); } toString(): string { return this.name; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLInterfaceType.prototype.toJSON = GraphQLInterfaceType.prototype.inspect = GraphQLInterfaceType.prototype.toString; export type GraphQLInterfaceTypeConfig<TSource, TContext> = { name: string, fields: Thunk<GraphQLFieldConfigMap<TSource, TContext>>, /** * Optionally provide a custom type resolver function. If one is not provided, * the default implementation will call `isTypeOf` on each implementing * Object type. */ resolveType?: ?GraphQLTypeResolver<TSource, TContext>, description?: ?string }; /** * Union Type Definition * * When a field can return one of a heterogeneous set of types, a Union type * is used to describe what types are possible as well as providing a function * to determine which type is actually used when the field is resolved. * * Example: * * const PetType = new GraphQLUnionType({ * name: 'Pet', * types: [ DogType, CatType ], * resolveType(value) { * if (value instanceof Dog) { * return DogType; * } * if (value instanceof Cat) { * return CatType; * } * } * }); * */ export class GraphQLUnionType { name: string; description: ?string; resolveType: ?GraphQLTypeResolver<*, *>; _typeConfig: GraphQLUnionTypeConfig<*, *>; _types: Array<GraphQLObjectType>; _possibleTypeNames: {[typeName: string]: boolean}; constructor(config: GraphQLUnionTypeConfig<*, *>) { assertValidName(config.name); this.name = config.name; this.description = config.description; if (config.resolveType) { invariant( typeof config.resolveType === 'function', `${this.name} must provide "resolveType" as a function.` ); } this.resolveType = config.resolveType; this._typeConfig = config; } getTypes(): Array<GraphQLObjectType> { return this._types || (this._types = defineTypes(this, this._typeConfig.types) ); } toString(): string { return this.name; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLUnionType.prototype.toJSON = GraphQLUnionType.prototype.inspect = GraphQLUnionType.prototype.toString; function defineTypes( unionType: GraphQLUnionType, typesThunk: Thunk<Array<GraphQLObjectType>> ): Array<GraphQLObjectType> { const types = resolveThunk(typesThunk); invariant( Array.isArray(types) && types.length > 0, 'Must provide Array of types or a function which returns ' + `such an array for Union ${unionType.name}.` ); const seenObjectNames = []; types.forEach(objType => { invariant( objType instanceof GraphQLObjectType, `${unionType.name} may only contain Object types, it cannot contain: ` + `${String(objType)}.` ); invariant( seenObjectNames.indexOf(objType.name) === -1, `${unionType.name} can include ${objType.name} type only once.` ); seenObjectNames.push(objType.name); if (typeof unionType.resolveType !== 'function') { invariant( typeof objType.isTypeOf === 'function', `Union type "${unionType.name}" does not provide a "resolveType" ` + `function and possible type "${objType.name}" does not provide an ` + '"isTypeOf" function. There is no way to resolve this possible type ' + 'during execution.' ); } }); return types; } export type GraphQLUnionTypeConfig<TSource, TContext> = { name: string, types: Thunk<Array<GraphQLObjectType>>, /** * Optionally provide a custom type resolver function. If one is not provided, * the default implementation will call `isTypeOf` on each implementing * Object type. */ resolveType?: ?GraphQLTypeResolver<TSource, TContext>; description?: ?string; }; /** * Enum Type Definition * * Some leaf values of requests and input values are Enums. GraphQL serializes * Enum values as strings, however internally Enums can be represented by any * kind of type, often integers. * * Example: * * const RGBType = new GraphQLEnumType({ * name: 'RGB', * values: { * RED: { value: 0 }, * GREEN: { value: 1 }, * BLUE: { value: 2 } * } * }); * * Note: If a value is not provided in a definition, the name of the enum value * will be used as its internal value. */ export class GraphQLEnumType/* <T> */ { name: string; description: ?string; _enumConfig: GraphQLEnumTypeConfig/* <T> */; _values: Array<GraphQLEnumValue/* <T> */>; _valueLookup: Map<any/* T */, GraphQLEnumValue>; _nameLookup: { [valueName: string]: GraphQLEnumValue }; constructor(config: GraphQLEnumTypeConfig/* <T> */) { this.name = config.name; assertValidName(config.name, config.isIntrospection); this.description = config.description; this._values = defineEnumValues(this, config.values); this._enumConfig = config; } getValues(): Array<GraphQLEnumValue/* <T> */> { return this._values; } getValue(name: string): ?GraphQLEnumValue { return this._getNameLookup()[name]; } serialize(value: any/* T */): ?string { const enumValue = this._getValueLookup().get(value); return enumValue ? enumValue.name : null; } parseValue(value: mixed): ?any/* T */ { if (typeof value === 'string') { const enumValue = this._getNameLookup()[value]; if (enumValue) { return enumValue.value; } } } parseLiteral(valueNode: ValueNode): ?any/* T */ { if (valueNode.kind === ENUM) { const enumValue = this._getNameLookup()[valueNode.value]; if (enumValue) { return enumValue.value; } } } _getValueLookup(): Map<any/* T */, GraphQLEnumValue> { if (!this._valueLookup) { const lookup = new Map(); this.getValues().forEach(value => { lookup.set(value.value, value); }); this._valueLookup = lookup; } return this._valueLookup; } _getNameLookup(): { [valueName: string]: GraphQLEnumValue } { if (!this._nameLookup) { const lookup = Object.create(null); this.getValues().forEach(value => { lookup[value.name] = value; }); this._nameLookup = lookup; } return this._nameLookup; } toString(): string { return this.name; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLEnumType.prototype.toJSON = GraphQLEnumType.prototype.inspect = GraphQLEnumType.prototype.toString; function defineEnumValues( type: GraphQLEnumType, valueMap: GraphQLEnumValueConfigMap/* <T> */ ): Array<GraphQLEnumValue/* <T> */> { invariant( isPlainObj(valueMap), `${type.name} values must be an object with value names as keys.` ); const valueNames = Object.keys(valueMap); invariant( valueNames.length > 0, `${type.name} values must be an object with value names as keys.` ); return valueNames.map(valueName => { assertValidName(valueName); const value = valueMap[valueName]; invariant( isPlainObj(value), `${type.name}.${valueName} must refer to an object with a "value" key ` + `representing an internal value but got: ${String(value)}.` ); invariant( !value.hasOwnProperty('isDeprecated'), `${type.name}.${valueName} should provide "deprecationReason" instead ` + 'of "isDeprecated".' ); return { name: valueName, description: value.description, isDeprecated: Boolean(value.deprecationReason), deprecationReason: value.deprecationReason, value: isNullish(value.value) ? valueName : value.value, }; }); } export type GraphQLEnumTypeConfig/* <T> */ = { name: string; values: GraphQLEnumValueConfigMap/* <T> */; description?: ?string; isIntrospection?: boolean; }; export type GraphQLEnumValueConfigMap/* <T> */ = { [valueName: string]: GraphQLEnumValueConfig/* <T> */; }; export type GraphQLEnumValueConfig/* <T> */ = { value?: any/* T */; deprecationReason?: ?string; description?: ?string; }; export type GraphQLEnumValue/* <T> */ = { name: string; description: ?string; isDeprecated?: boolean; deprecationReason: ?string; value: any/* T */; }; /** * Input Object Type Definition * * An input object defines a structured collection of fields which may be * supplied to a field argument. * * Using `NonNull` will ensure that a value must be provided by the query * * Example: * * const GeoPoint = new GraphQLInputObjectType({ * name: 'GeoPoint', * fields: { * lat: { type: new GraphQLNonNull(GraphQLFloat) }, * lon: { type: new GraphQLNonNull(GraphQLFloat) }, * alt: { type: GraphQLFloat, defaultValue: 0 }, * } * }); * */ export class GraphQLInputObjectType { name: string; description: ?string; _typeConfig: GraphQLInputObjectTypeConfig; _fields: GraphQLInputFieldMap; constructor(config: GraphQLInputObjectTypeConfig) { assertValidName(config.name); this.name = config.name; this.description = config.description; this._typeConfig = config; } getFields(): GraphQLInputFieldMap { return this._fields || (this._fields = this._defineFieldMap()); } _defineFieldMap(): GraphQLInputFieldMap { const fieldMap: any = resolveThunk(this._typeConfig.fields); invariant( isPlainObj(fieldMap), `${this.name} fields must be an object with field names as keys or a ` + 'function which returns such an object.' ); const fieldNames = Object.keys(fieldMap); invariant( fieldNames.length > 0, `${this.name} fields must be an object with field names as keys or a ` + 'function which returns such an object.' ); const resultFieldMap = {}; fieldNames.forEach(fieldName => { assertValidName(fieldName); const field = { ...fieldMap[fieldName], name: fieldName }; invariant( isInputType(field.type), `${this.name}.${fieldName} field type must be Input Type but ` + `got: ${String(field.type)}.` ); invariant( field.resolve == null, `${this.name}.${fieldName} field type has a resolve property, but ` + 'Input Types cannot define resolvers.' ); resultFieldMap[fieldName] = field; }); return resultFieldMap; } toString(): string { return this.name; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLInputObjectType.prototype.toJSON = GraphQLInputObjectType.prototype.inspect = GraphQLInputObjectType.prototype.toString; export type GraphQLInputObjectTypeConfig = { name: string; fields: Thunk<GraphQLInputFieldConfigMap>; description?: ?string; }; export type GraphQLInputFieldConfig = { type: GraphQLInputType; defaultValue?: mixed; description?: ?string; }; export type GraphQLInputFieldConfigMap = { [fieldName: string]: GraphQLInputFieldConfig; }; export type GraphQLInputField = { name: string; type: GraphQLInputType; defaultValue?: mixed; description?: ?string; }; export type GraphQLInputFieldMap = { [fieldName: string]: GraphQLInputField; }; /** * List Modifier * * A list is a kind of type marker, a wrapping type which points to another * type. Lists are often created within the context of defining the fields of * an object type. * * Example: * * const PersonType = new GraphQLObjectType({ * name: 'Person', * fields: () => ({ * parents: { type: new GraphQLList(Person) }, * children: { type: new GraphQLList(Person) }, * }) * }) * */ export class GraphQLList<T: GraphQLType> { ofType: T; constructor(type: T) { invariant( isType(type), `Can only create List of a GraphQLType but got: ${String(type)}.` ); this.ofType = type; } toString(): string { return '[' + String(this.ofType) + ']'; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLList.prototype.toJSON = GraphQLList.prototype.inspect = GraphQLList.prototype.toString; /** * Non-Null Modifier * * A non-null is a kind of type marker, a wrapping type which points to another * type. Non-null types enforce that their values are never null and can ensure * an error is raised if this ever occurs during a request. It is useful for * fields which you can make a strong guarantee on non-nullability, for example * usually the id field of a database row will never be null. * * Example: * * const RowType = new GraphQLObjectType({ * name: 'Row', * fields: () => ({ * id: { type: new GraphQLNonNull(GraphQLString) }, * }) * }) * * Note: the enforcement of non-nullability occurs within the executor. */ export class GraphQLNonNull<T: GraphQLNullableType> { ofType: T; constructor(type: T) { invariant( isType(type) && !(type instanceof GraphQLNonNull), 'Can only create NonNull of a Nullable GraphQLType but got: ' + `${String(type)}.` ); this.ofType = type; } toString(): string { return this.ofType.toString() + '!'; } toJSON: () => string; inspect: () => string; } // Also provide toJSON and inspect aliases for toString. GraphQLNonNull.prototype.toJSON = GraphQLNonNull.prototype.inspect = GraphQLNonNull.prototype.toString;
Use a hashmap instead of array find
src/type/definition.js
Use a hashmap instead of array find
<ide><path>rc/type/definition.js <ide> 'Must provide Array of types or a function which returns ' + <ide> `such an array for Union ${unionType.name}.` <ide> ); <del> const seenObjectNames = []; <add> const includedTypeNames = {}; <ide> types.forEach(objType => { <ide> invariant( <ide> objType instanceof GraphQLObjectType, <ide> `${String(objType)}.` <ide> ); <ide> invariant( <del> seenObjectNames.indexOf(objType.name) === -1, <add> !includedTypeNames[objType.name], <ide> `${unionType.name} can include ${objType.name} type only once.` <ide> ); <del> seenObjectNames.push(objType.name); <add> includedTypeNames[objType.name] = true; <ide> if (typeof unionType.resolveType !== 'function') { <ide> invariant( <ide> typeof objType.isTypeOf === 'function',
JavaScript
apache-2.0
88449b18d1f9ba567db72e71827a68ed39f3685e
0
unicef/un-partner-portal,unicef/un-partner-portal,unicef/un-partner-portal,unicef/un-partner-portal
/* eslint-disable camelcase */ import { combineReducers } from 'redux'; import R from 'ramda'; import cfeiDetailsStatus, { loadCfeiDetailStarted, loadCfeiDetailEnded, loadCfeiDetailSuccess, loadCfeiDetailFailure, loadUCNDetailSuccess, LOAD_CFEI_DETAIL_SUCCESS, LOAD_UCN_DETAIL_SUCCESS, } from './cfeiDetailsStatus'; import { } from './apiStatus'; import { normalizeSingleCfei } from './cfei'; import { getOpenCfeiDetails, getApplicationDetails } from '../helpers/api/api'; const initialState = {}; export const loadCfei = id => (dispatch) => { dispatch(loadCfeiDetailStarted()); return getOpenCfeiDetails(id) .then((cfei) => { dispatch(loadCfeiDetailEnded()); dispatch(loadCfeiDetailSuccess(cfei)); return cfei; }) .catch((error) => { dispatch(loadCfeiDetailEnded()); dispatch(loadCfeiDetailFailure(error)); }); }; export const loadUnsolicitedCfei = id => (dispatch) => { dispatch(loadCfeiDetailStarted()); return getApplicationDetails(id) .then((cfei) => { dispatch(loadCfeiDetailEnded()); dispatch(loadUCNDetailSuccess(cfei)); return cfei; }) .catch((error) => { dispatch(loadCfeiDetailEnded()); dispatch(loadCfeiDetailFailure(error)); }); }; const mergeCountries = (k, l, r) => { if (k === 'adminLevel') { if (l.includes(r)) return l; return `${l}, ${r}`; } return l; }; const mapLocations = R.map(location => ({ country: location.admin_level_1.country_code, adminLevel: location.admin_level_1.name, }), ); const normalizeLocations = R.compose( R.map(R.reduce(R.mergeDeepWithKey(mergeCountries), {})), R.groupWith(R.eqProps('country')), mapLocations, ); const saveCfei = (state, action) => { let cfei = normalizeSingleCfei(action.cfei); cfei = R.assoc('locations', normalizeLocations(cfei.locations), cfei); return R.assoc(cfei.id, cfei, state); }; const saveUCN = (state, action) => { const { ucn } = action; const newUCN = { id: ucn.id, partner_name: ucn.partner.id, display_type: ucn.partner.display_type, title: R.path(['proposal_of_eoi_details', 'title'], ucn), locations: ucn.locations_proposal_of_eoi, specializations: R.path(['proposal_of_eoi_details', 'specializations'], ucn), agency: ucn.agency, cn: ucn.cn, }; return R.assoc(ucn.id, normalizeSingleCfei(newUCN), state); }; export function selectCfeiDetail(state, id) { const { [id]: cfei = null } = state; return cfei; } export function selectCfeiTitle(state, id) { const { [id]: { title = '' } = {} } = state; return title; } export function selectCfeiStatus(state, id) { const { [id]: { status = null } = {} } = state; return status; } export function isCfeiCompleted(state, id) { const { [id]: { completed_reason = null } = {} } = state; return !!completed_reason; } export function isCfeiPinned(state, id) { const { [id]: { is_pinned = null } = {} } = state; return is_pinned; } export function selectCfeiCriteria(state, id) { const { [id]: { assessments_criteria = [] } = {} } = state; return assessments_criteria; } export function isUserAReviewer(state, cfeiId, userId) { const cfei = R.prop(cfeiId, state); if (cfei) return cfei.reviewers.includes(userId); return false; } export function isUserAFocalPoint(state, cfeiId, userId) { const cfei = R.prop(cfeiId, state); if (cfei) return cfei.focal_points.includes(userId); return false; } const cfeiDetails = (state = initialState, action) => { switch (action.type) { case LOAD_CFEI_DETAIL_SUCCESS: { return saveCfei(state, action); } case LOAD_UCN_DETAIL_SUCCESS: { return saveUCN(state, action); } default: return state; } }; export default combineReducers({ cfeiDetails, cfeiDetailsStatus });
frontend/src/reducers/cfeiDetails.js
/* eslint-disable camelcase */ import { combineReducers } from 'redux'; import R from 'ramda'; import cfeiDetailsStatus, { loadCfeiDetailStarted, loadCfeiDetailEnded, loadCfeiDetailSuccess, loadCfeiDetailFailure, loadUCNDetailSuccess, LOAD_CFEI_DETAIL_SUCCESS, LOAD_UCN_DETAIL_SUCCESS, } from './cfeiDetailsStatus'; import { } from './apiStatus'; import { normalizeSingleCfei } from './cfei'; import { getOpenCfeiDetails, getApplicationDetails } from '../helpers/api/api'; const initialState = {}; export const loadCfei = id => (dispatch) => { dispatch(loadCfeiDetailStarted()); return getOpenCfeiDetails(id) .then((cfei) => { dispatch(loadCfeiDetailEnded()); dispatch(loadCfeiDetailSuccess(cfei)); return cfei; }) .catch((error) => { dispatch(loadCfeiDetailEnded()); dispatch(loadCfeiDetailFailure(error)); }); }; export const loadUnsolicitedCfei = id => (dispatch) => { dispatch(loadCfeiDetailStarted()); return getApplicationDetails(id) .then((cfei) => { dispatch(loadCfeiDetailEnded()); dispatch(loadUCNDetailSuccess(cfei)); return cfei; }) .catch((error) => { dispatch(loadCfeiDetailEnded()); dispatch(loadCfeiDetailFailure(error)); }); }; const mergeCountries = (k, l, r) => { if (k === 'adminLevel') { if (l.includes(r)) return l; return `${l}, ${r}`; } return l; }; const mapLocations = R.map(location => ({ country: location.admin_level_1.country_code, adminLevel: location.admin_level_1.name, }), ); const normalizeLocations = R.compose( R.map(R.reduce(R.mergeDeepWithKey(mergeCountries), {})), R.groupWith(R.eqProps('country')), mapLocations, ); const saveCfei = (state, action) => { let cfei = normalizeSingleCfei(action.cfei); cfei = R.assoc('locations', normalizeLocations(cfei.locations), cfei); return R.assoc(cfei.id, cfei, state); }; const saveUCN = (state, action) => { const { ucn } = action; const newUCN = { id: ucn.id, partner_name: ucn.partner.id, display_type: 1, title: R.path(['proposal_of_eoi_details', 'title'], ucn), locations: ucn.locations_proposal_of_eoi, specializations: R.path(['proposal_of_eoi_details', 'specializations'], ucn), agency: ucn.agency, cn: ucn.cn, }; return R.assoc(ucn.id, normalizeSingleCfei(newUCN), state); }; export function selectCfeiDetail(state, id) { const { [id]: cfei = null } = state; return cfei; } export function selectCfeiTitle(state, id) { const { [id]: { title = '' } = {} } = state; return title; } export function selectCfeiStatus(state, id) { const { [id]: { status = null } = {} } = state; return status; } export function isCfeiCompleted(state, id) { const { [id]: { completed_reason = null } = {} } = state; return !!completed_reason; } export function isCfeiPinned(state, id) { const { [id]: { is_pinned = null } = {} } = state; return is_pinned; } export function selectCfeiCriteria(state, id) { const { [id]: { assessments_criteria = [] } = {} } = state; return assessments_criteria; } export function isUserAReviewer(state, cfeiId, userId) { const cfei = R.prop(cfeiId, state); if (cfei) return cfei.reviewers.includes(userId); return false; } export function isUserAFocalPoint(state, cfeiId, userId) { const cfei = R.prop(cfeiId, state); if (cfei) return cfei.focal_points.includes(userId); return false; } const cfeiDetails = (state = initialState, action) => { switch (action.type) { case LOAD_CFEI_DETAIL_SUCCESS: { return saveCfei(state, action); } case LOAD_UCN_DETAIL_SUCCESS: { return saveUCN(state, action); } default: return state; } }; export default combineReducers({ cfeiDetails, cfeiDetailsStatus });
missing ingo field
frontend/src/reducers/cfeiDetails.js
missing ingo field
<ide><path>rontend/src/reducers/cfeiDetails.js <ide> const newUCN = { <ide> id: ucn.id, <ide> partner_name: ucn.partner.id, <del> display_type: 1, <add> display_type: ucn.partner.display_type, <ide> title: R.path(['proposal_of_eoi_details', 'title'], ucn), <ide> locations: ucn.locations_proposal_of_eoi, <ide> specializations: R.path(['proposal_of_eoi_details', 'specializations'], ucn),
JavaScript
mit
8235376c3e461ec5ed8e5a907285f9e3480ea039
0
fent/node-kat
var Readable = require('readable-stream').Readable; var util = require('util'); var fs = require('fs'); var path = require('path'); var Queue = require('./queue'); /** * @constructor * @extends {Readable} * @param {String|Readable|Stream} file... List of files to add * when initiating. * @param {Object} options */ var Kat = module.exports = function() { // Default options. this.options = { start: 0 , end: Infinity , concurrency: 250 , allowFiles: true , allowDirs: true , allowStreams: true , continueOnErr: false , autoEnd: true }; // Check for options. var args = Array.prototype.slice.call(arguments); var last = args.pop(); if (last) { if (typeof last !== 'string' && !isReadableStream(last)) { for (var key in this.options) { if (this.options.hasOwnProperty(key)) { if (last[key] === undefined) continue; this.options[key] = last[key]; } } if (typeof this.options.start !== 'number') { throw new Error('start must be a number'); } if (typeof this.options.end !== 'number') { throw new Error('end must be a number'); } if (this.options.start > this.options.end) { throw new Error('start and end must be start <= end'); } if (typeof this.options.concurrency !== 'number' || this.options.concurrency <= 0) { throw new Error('concurrency must be a number and over 0'); } } else { args.push(last); } } Readable.call(this, this.options); this.bytesRead = 0; this.pos = 0; this._sized = 0; // A queue for opening and reading a file's stats. var self = this; this._openQueue = new Queue(function(file, callback) { if (!self.readable) return callback(); var indir = this.injected; if (typeof file === 'string') { fs.open(file, self.flags || 'r', self.mode || 438, function(err, fd) { if (err) return callback(err); fs.fstat(fd, function(err, stat) { if (err) return callback(err); if (stat.isFile()) { if (!indir && !self.options.allowFiles) { return callback(new Error('Cannot add files')); } self.emit('fd', fd, file); callback(function(callback) { self._addFile(file, fd, stat.size, callback); }); } else if (stat.isDirectory()) { if (!self.options.allowDirs) { return callback(new Error('Cannot add directories')); } var noerr = true; var readdir = function readdir(err, files) { if (noerr && err) { noerr = false; return callback(err); } if (!files || !files.length) return; files = files.sort().map(function(f) { return path.join(file, f); }); callback(files); }; fs.readdir(file, readdir); fs.close(fd, readdir); } }); }); } else if (isReadableStream(file)) { if (isOldStyleStream(file)) { file.pause(); } process.nextTick(function() { if (!self.options.allowStreams) { return callback(new Error('Cannot add streams')); } callback(self._addStream.bind(self, file, false)); }); } else { callback(new Error('Invalid argument given: ' + file)); } }, this.options.concurrency); this._openQueue.on('error', function(err) { if (!self.options.continueOnErr) { self.readable = false; self._cleanup(); } self.emit('error', err); }); this._queue = []; this._files = []; this._totalFiles = 0; // Call add with possible given files to read. if (args.length > 0) { this.add.apply(this, args); } }; util.inherits(Kat, Readable); /** * Adds a file, folder, or readable stream. * * @param {String|Readable|Stream} file... */ Kat.prototype.add = function() { if (!this.readable) throw new Error('Cannot add any more files'); var self = this; for (var i = 0, len = arguments.length; i < len; i++) { var file = arguments[i]; self._openQueue.push(file); } }; /** * Addds a file from a given path. * * @param {String} file * @param {Number} fd * @param {Number} size * @param {Function(!Error)} callback */ Kat.prototype._addFile = function(file, fd, size, callback) { if (this._skip) return callback(); var start = 0, end = Infinity; // Calculate start and end positions for this file. // Uncertain means that a stream was added before this file // which the size of is unknown. // Thus the position of the stream when it reaches this file // will be uncertain. if (!this._uncertain) { if (this.options.start > this._sized) { start = this.options.start - this._sized; } // If the end position is reached, make note of it. var newSize = this._sized + size; if (this.options.end <= newSize) { this._skip = true; end = this.options.end - this._sized; } this.pos += Math.min(start, size); // Add size to total. this._sized = newSize; // If no data will be read from this file, skip it. if (start >= size || end && start >= end) return callback(); } var options = { fd: fd, start: start, end: end }; if (this.options.encoding) { options.encoding = this.options.encoding; } if (this.options.bufferSize) { options.bufferSize = this.options.bufferSize; } var rs = fs.createReadStream(file, options); this._addStream(rs, true, callback); }; /** * Addds a readable stream. * * @param {Readable} stream * @param {Boolean} sized Wether or not this stream's size is known. * @param {Function(!Error)} callback */ Kat.prototype._addStream = function(stream, sized, callback) { // If no more data needs to be read, call callback right away. if (this.bytesRead > this.options.end) { return callback(); } // Take note if the size of this stream is not known. if (!sized) this._uncertain = true; var self = this; var filepath = stream.path || this._totalFiles++; // Wether this stream is a file or not. Not set by openQueue because // of the possibility of directly adding a `fs.ReadStream`. var isFile = stream instanceof fs.ReadStream; // Check if this stream is using the old style API. if (isOldStyleStream(stream)) { var readable = new Readable(); readable.wrap(stream); stream.resume(); stream = readable; } var data = { // Keep track of how many bytes are read from this stream. bytesRead: 0, // Add to list of files. path: filepath, stream: stream, // Cleanup when this this stream ends, closes, errors, // or Kat is finished. cleanup: cleanup, // Note that stream is not yet readable until it fires // the `readable` event. readable: false, onend: onend }; // When an error occurs, stop if `options.continueOnErr` is `false`. // Otherwise, treat this stream as if it ended // and continue to the next one. function onerr(err) { if (!self.options.continueOnErr) { self._cleanup(); } else { onend(); } self.emit('error', err); } stream.on('error', onerr); // Proxy `fd` and `close` events to this instance. function onfd(fd) { self.emit('fd', fd, data.path); } function onclose() { self.emit('close', data.path); onend(); } // Called to signal the next stream to begin reading. // Check if there is another stream in the queue, // if there isn't then we are finished. function onend() { cleanup(); callback(); // Add to list of files. if (data.bytesRead) { self._files.push({ path: data.path, size: data.bytesRead }); } // Check if Kat has ended. if (self._ended) { self._end(); } else { var next = self._queue.shift(); if (next) { self._addCurrentStream(next); } else if (self.options.autoEnd && self._openQueue.workers === 0) { self._end(); } else { delete self._current; } } } if (isFile) { stream.on('fd', onfd); stream.on('close', onclose); } else { stream.on('end', onend); } function onreadable() { // Make note that it's readable so that `stream.read()` can be called // when it becomes the active stream. data.readable = true; } stream.on('readable', onreadable); // Cleanup all listeners when this stream is no longer needed. function cleanup() { stream.removeListener('error', onerr); stream.removeListener('readable', onreadable); if (isFile) { stream.removeListener('fd', onfd); stream.removeListener('close', onclose); } else { stream.removeListener('end', onend); } } if (this._current) { // If another stream is active, add it to the queue. this._queue.push(data); } else { // Otherwise make this stream the current stream. this._addCurrentStream(data); } }; /** * Add a stream and make it the currently active one. * * @param {Object} data * {Number} bytesRead * {String} path * {Readable} stream * {Function} cleanup */ Kat.prototype._addCurrentStream = function(data) { // Mark this stream as having been read from in order to // add it to the list of files later. data.read = true; this.emit('start', data.path); this._current = data; if (this._waiting) { // If `Kat#_read()` has already been called, // start reading from the stream right away. var size = this._waiting; delete this._waiting; this._readStream(size); } }; /** * Read method needed by the Readable class. * * @param {Number} size */ Kat.prototype._read = function(size) { if (this._current) { if (this._current.readable) { // If the current stream has already fired the `readable` event, // read from it right away. this._readStream(size); this._current.readable = false; } else { // If not, wait until it does. var self = this; this._current.stream.once('readable', function onreadable() { self._readStream(size); }); } } else { // If no stream has been added yet, note that `Kat#_read()` has // been called. this._waiting = size; } }; /** * Read from the current stream. This is called when the `readable` event * has been fired on the current active stream. */ Kat.prototype._readStream = function(size) { var self = this; // Check if reading the `size` amount of data would go over `end`. if (this.options.end < newPos) { size -= newPos - this.options.end; } var oldPos = self.pos; var newPos = self.pos + size; var data = this._current.stream.read(size); if (data) { // Add data length to total bytes read. self.bytesRead += data.length; self.pos += data.length; // Check if there is any uncertainty if this data should be emitted // in case `start` and `end` options were given. if (oldPos >= self._sized) { // Check if `start` is in this data read. if (self.options.start > oldPos) { // Skip this data read if `start` is in a later one. if (self.options.start > self.pos) { this._waiting = size; this.push(''); return; } var start = self.options.start - oldPos; data = data.slice(start); } // Check if end has been reached. if (self.options.end < oldPos) { return; } // Check if end position is in this data event. if (self.options.end < self.pos) { var end = self.options.end - oldPos + 1; data = data.slice(0, end); } } // Emit data to Kat instance. this._current.bytesRead += data.length; this.push(data); // Take note if less data was retrieved than requested. if (data.length < size) { this._waiting = size - data.length; } // End stream if end will be reached on this `data` event reached. if (self.options.end < self.pos) { this._ended = true; if (typeof this._current.stream.close === 'function') { // If this is a file stream, close the file descripter. this._current.stream.close(); } else { // If this stream is not a file, call its `onend()` method right away // so it is not read any further. this._current.onend(); } } } else { this._current.stream.once('readable', function onreadable() { self._readStream(size); }); } }; /** * Cleans up all streams including the ones in queue. */ Kat.prototype._cleanup = function() { this.readable = false; delete this._current; delete this._waiting; this._openQueue.die(); this._queue.forEach(function(data) { data.cleanup(); }); this._queue = []; }; /** * End stream. */ Kat.prototype._end = function() { this._cleanup(); this.emit('files', this._files); this.push(null); }; /** * Returns true if obj is a readable stream. * * @param {Object} obj */ function isReadableStream(obj) { return typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.readable === 'boolean' && obj.readable; } /** * Returns true if obj is an old style stream. From node v0.8 or older. */ function isOldStyleStream(obj) { return typeof obj.read !== 'function' || typeof obj._read !== 'function' || typeof obj.push !== 'function' || typeof obj.unshift !== 'function' || typeof obj.wrap !== 'function'; }
lib/index.js
var Readable = require('readable-stream').Readable; var util = require('util'); var fs = require('fs'); var path = require('path'); var Queue = require('./queue'); /** * @constructor * @extends {Readable} * @param {String|Readable|Stream} file... List of files to add * when initiating. * @param {Object} options */ var Kat = module.exports = function() { // Default options. this.options = { start: 0 , end: Infinity , concurrency: 250 , allowFiles: true , allowDirs: true , allowStreams: true , continueOnErr: false , autoEnd: true }; // Check for options. var args = Array.prototype.slice.call(arguments); var last = args.pop(); if (last) { if (typeof last !== 'string' && !isReadableStream(last)) { for (var key in this.options) { if (this.options.hasOwnProperty(key)) { if (last[key] === undefined) continue; this.options[key] = last[key]; } } if (typeof this.options.start !== 'number') { throw new Error('start must be a number'); } if (typeof this.options.end !== 'number') { throw new Error('end must be a number'); } if (this.options.start > this.options.end) { throw new Error('start and end must be start <= end'); } if (typeof this.options.concurrency !== 'number' || this.options.concurrency <= 0) { throw new Error('concurrency must be a number and over 0'); } } else { args.push(last); } } Readable.call(this, this.options); this.bytesRead = 0; this.pos = 0; this._sized = 0; // A queue for opening and reading a file's stats. var self = this; this._openQueue = new Queue(function(file, callback) { if (!self.readable) return callback(); var indir = this.injected; if (typeof file === 'string') { fs.open(file, self.flags || 'r', self.mode || 438, function(err, fd) { if (err) return callback(err); fs.fstat(fd, function(err, stat) { if (err) return callback(err); if (stat.isFile()) { if (!indir && !self.options.allowFiles) { return callback(new Error('Cannot add files')); } self.emit('fd', fd, file); callback(function(callback) { self._addFile(file, fd, stat.size, callback); }); } else if (stat.isDirectory()) { if (!self.options.allowDirs) { return callback(new Error('Cannot add directories')); } var noerr = true; var readdir = function readdir(err, files) { if (noerr && err) { noerr = false; return callback(err); } if (!files || !files.length) return; files = files.sort().map(function(f) { return path.join(file, f); }); callback(files); }; fs.readdir(file, readdir); fs.close(fd, readdir); } }); }); } else if (isReadableStream(file)) { if (isOldStyleStream(file)) { file.pause(); } process.nextTick(function() { if (!self.options.allowStreams) { return callback(new Error('Cannot add streams')); } callback(self._addStream.bind(self, file, false)); }); } else { callback(new Error('Invalid argument given: ' + file)); } }, this.options.concurrency); this._openQueue.on('error', function(err) { if (!self.options.continueOnErr) { self.readable = false; self._cleanup(); } self.emit('error', err); }); this._queue = []; this._files = []; this._totalFiles = 0; // Call add with possible given files to read. if (args.length > 0) { this.add.apply(this, args); } }; util.inherits(Kat, Readable); /** * Adds a file, folder, or readable stream. * * @param {String|Readable|Stream} file... */ Kat.prototype.add = function() { if (!this.readable) throw new Error('Cannot add any more files'); var self = this; for (var i = 0, len = arguments.length; i < len; i++) { var file = arguments[i]; self._openQueue.push(file); } }; /** * Addds a file from a given path. * * @param {String} file * @param {Number} fd * @param {Number} size * @param {Function(!Error)} callback */ Kat.prototype._addFile = function(file, fd, size, callback) { if (this._skip) return callback(); var start = 0, end = Infinity; // Calculate start and end positions for this file. // Uncertain means that a stream was added before this file // which the size of is unknown. // Thus the position of the stream when it reaches this file // will be uncertain. if (!this._uncertain) { if (this.options.start > this._sized) { start = this.options.start - this._sized; } // If the end position is reached, make note of it. var newSize = this._sized + size; if (this.options.end <= newSize) { this._skip = true; end = this.options.end - this._sized; } this.pos += Math.min(start, size); // Add size to total. this._sized = newSize; // If no data will be read from this file, skip it. if (start >= size || end && start >= end) return callback(); } var options = { fd: fd, start: start, end: end }; if (this.options.encoding) { options.encoding = this.options.encoding; } if (this.options.bufferSize) { options.bufferSize = this.options.bufferSize; } var rs = fs.createReadStream(file, options); this._addStream(rs, true, callback); }; /** * Addds a readable stream. * * @param {Readable} stream * @param {Boolean} sized Wether or not this stream's size is known. * @param {Function(!Error)} callback */ Kat.prototype._addStream = function(stream, sized, callback) { // If no more data needs to be read, call callback right away. if (this.bytesRead > this.options.end) { return callback(); } // Take note if the size of this stream is not known. if (!sized) this._uncertain = true; var self = this; var filepath = stream.path || this._totalFiles++; var isFile = stream instanceof fs.ReadStream; // Check if this stream is using the old style API. if (isOldStyleStream(stream)) { var readable = new Readable(); readable.wrap(stream); stream.resume(); stream = readable; } var data = { // Keep track of how many bytes are read from this stream. bytesRead: 0, // Add to list of files. path: filepath, stream: stream, // Cleanup when this this stream ends, closes, errors, // or Kat is finished. cleanup: cleanup, // Note that stream is not yet readable until it fires // the `readable` event. readable: false, // Wether this stream is a file or not. Not set by openQueue because // of the possibility of directly adding a `fs.ReadStream`. isFile: isFile, onend: onend }; // When an error occurs, stop if `options.continueOnErr` is `false`. // Otherwise, treat this stream as if it ended // and continue to the next one. function onerr(err) { if (!self.options.continueOnErr) { self._cleanup(); } else { onend(); } self.emit('error', err); } stream.on('error', onerr); // Proxy `fd` and `close` events to this instance. function onfd(fd) { self.emit('fd', fd, data.path); } function onclose() { self.emit('close', data.path); onend(); } // Called to signal the next stream to begin reading. // Check if there is another stream in the queue, // if there isn't then we are finished. function onend() { cleanup(); callback(); // Add to list of files. if (data.bytesRead) { self._files.push({ path: data.path, size: data.bytesRead }); } // Check if Kat has ended. if (self._ended) { self._end(); } else { var next = self._queue.shift(); if (next) { self._addCurrentStream(next); } else if (self.options.autoEnd && self._openQueue.workers === 0) { self._end(); } else { delete self._current; } } } if (data.isFile) { stream.on('fd', onfd); stream.on('close', onclose); } else { stream.on('end', onend); } function onreadable() { // Make note that it's readable so that `stream.read()` can be called // when it becomes the active stream. data.readable = true; } stream.on('readable', onreadable); // Cleanup all listeners when this stream is no longer needed. function cleanup() { stream.removeListener('error', onerr); stream.removeListener('readable', onreadable); if (data.isFile) { stream.removeListener('fd', onfd); stream.removeListener('close', onclose); } else { stream.removeListener('end', onend); } } if (this._current) { // If another stream is active, add it to the queue. this._queue.push(data); } else { // Otherwise make this stream the current stream. this._addCurrentStream(data); } }; /** * Add a stream and make it the currently active one. * * @param {Object} data * {Number} bytesRead * {String} path * {Readable} stream * {Function} cleanup */ Kat.prototype._addCurrentStream = function(data) { // Mark this stream as having been read from in order to // add it to the list of files later. data.read = true; this.emit('start', data.path); this._current = data; if (this._waiting) { // If `Kat#_read()` has already been called, // start reading from the stream right away. var size = this._waiting; delete this._waiting; this._readStream(size); } }; /** * Read method needed by the Readable class. * * @param {Number} size */ Kat.prototype._read = function(size) { if (this._current) { if (this._current.readable) { // If the current stream has already fired the `readable` event, // read from it right away. this._readStream(size); this._current.readable = false; } else { // If not, wait until it does. var self = this; this._current.stream.once('readable', function onreadable() { self._readStream(size); }); } } else { // If no stream has been added yet, note that `Kat#_read()` has // been called. this._waiting = size; } }; /** * Read from the current stream. This is called when the `readable` event * has been fired on the current active stream. */ Kat.prototype._readStream = function(size) { var self = this; // Check if reading the `size` amount of data would go over `end`. if (this.options.end < newPos) { size -= newPos - this.options.end; } var oldPos = self.pos; var newPos = self.pos + size; var data = this._current.stream.read(size); if (data) { // Add data length to total bytes read. self.bytesRead += data.length; self.pos += data.length; // Check if there is any uncertainty if this data should be emitted // in case `start` and `end` options were given. if (oldPos >= self._sized) { // Check if `start` is in this data read. if (self.options.start > oldPos) { // Skip this data read if `start` is in a later one. if (self.options.start > self.pos) { this._waiting = size; this.push(''); return; } var start = self.options.start - oldPos; data = data.slice(start); } // Check if end has been reached. if (self.options.end < oldPos) { return; } // Check if end position is in this data event. if (self.options.end < self.pos) { var end = self.options.end - oldPos + 1; data = data.slice(0, end); } } // Emit data to Kat instance. this._current.bytesRead += data.length; this.push(data); // Take note if less data was retrieved than requested. if (data.length < size) { this._waiting = size - data.length; } // End stream if end will be reached on this `data` event reached. if (self.options.end < self.pos) { this._ended = true; if (this._current.isFile) { // If this is a file stream, close the file descripter. this._current.stream.close(); } else { // If this stream is not a file, call its `onend()` method right away // so it is not read any further. this._current.onend(); } } } else { this._current.stream.once('readable', function onreadable() { self._readStream(size); }); } }; /** * Cleans up all streams including the ones in queue. */ Kat.prototype._cleanup = function() { this.readable = false; delete this._current; delete this._waiting; this._openQueue.die(); this._queue.forEach(function(data) { data.cleanup(); }); this._queue = []; }; /** * End stream. */ Kat.prototype._end = function() { this._cleanup(); this.emit('files', this._files); this.push(null); }; /** * Returns true if obj is a readable stream. * * @param {Object} obj */ function isReadableStream(obj) { return typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.readable === 'boolean' && obj.readable; } /** * Returns true if obj is an old style stream. From node v0.8 or older. */ function isOldStyleStream(obj) { return typeof obj.read !== 'function' || typeof obj._read !== 'function' || typeof obj.push !== 'function' || typeof obj.unshift !== 'function' || typeof obj.wrap !== 'function'; }
check `fs.ReadStream#close()` method exists before calling for node v0.8
lib/index.js
check `fs.ReadStream#close()` method exists before calling for node v0.8
<ide><path>ib/index.js <ide> <ide> var self = this; <ide> var filepath = stream.path || this._totalFiles++; <add> <add> // Wether this stream is a file or not. Not set by openQueue because <add> // of the possibility of directly adding a `fs.ReadStream`. <ide> var isFile = stream instanceof fs.ReadStream; <ide> <ide> // Check if this stream is using the old style API. <ide> // Note that stream is not yet readable until it fires <ide> // the `readable` event. <ide> readable: false, <del> <del> // Wether this stream is a file or not. Not set by openQueue because <del> // of the possibility of directly adding a `fs.ReadStream`. <del> isFile: isFile, <ide> <ide> onend: onend <ide> }; <ide> } <ide> } <ide> <del> if (data.isFile) { <add> if (isFile) { <ide> stream.on('fd', onfd); <ide> stream.on('close', onclose); <ide> } else { <ide> function cleanup() { <ide> stream.removeListener('error', onerr); <ide> stream.removeListener('readable', onreadable); <del> if (data.isFile) { <add> if (isFile) { <ide> stream.removeListener('fd', onfd); <ide> stream.removeListener('close', onclose); <ide> } else { <ide> if (self.options.end < self.pos) { <ide> this._ended = true; <ide> <del> if (this._current.isFile) { <add> if (typeof this._current.stream.close === 'function') { <ide> // If this is a file stream, close the file descripter. <ide> this._current.stream.close(); <ide>
Java
apache-2.0
7b93b47af89e030d23e608ae3268845c92ead489
0
wskplho/jdroid,wskplho/jdroid,wskplho/jdroid
package com.jdroid.android.contextual; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import com.jdroid.android.ActivityLauncher; import com.jdroid.android.R; import com.jdroid.android.activity.AbstractFragmentActivity; import com.jdroid.android.fragment.OnItemSelectedListener; import com.jdroid.android.tabs.TabAction; import com.jdroid.android.utils.AndroidUtils; /** * * @param <T> * @author Maxi Rosson */ public abstract class ContextualActivity<T extends TabAction> extends AbstractFragmentActivity implements OnItemSelectedListener<T> { public static final String DEFAULT_CONTEXTUAL_ITEM_EXTRA = "defaultContextualItem"; /** * @see com.jdroid.android.activity.ActivityIf#getContentView() */ @Override public int getContentView() { return AndroidUtils.isLargeScreenOrBigger() ? R.layout.contextual_activity : R.layout.fragment_container_activity; } /** * @see android.preference.PreferenceActivity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { T defaultContextualItem = getExtra(DEFAULT_CONTEXTUAL_ITEM_EXTRA); if (defaultContextualItem == null) { defaultContextualItem = getDefaultContextualItem(); } FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); int contextualListFragmentId = AndroidUtils.isLargeScreenOrBigger() ? R.id.contextualFragmentContainer : R.id.fragmentContainer; fragmentTransaction.add(contextualListFragmentId, newContextualListFragment(getContextualItems(), defaultContextualItem)); if (AndroidUtils.isLargeScreenOrBigger()) { fragmentTransaction.add(R.id.detailsFragmentContainer, defaultContextualItem.createFragment(null), defaultContextualItem.getName()); } fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); fragmentTransaction.commit(); } } protected Fragment newContextualListFragment(List<T> actions, T defaultContextualItem) { return new ContextualListFragment(getContextualItems(), defaultContextualItem); } protected abstract List<T> getContextualItems(); protected abstract T getDefaultContextualItem(); /** * @see com.jdroid.android.fragment.OnItemSelectedListener#onItemSelected(java.lang.Object) */ @Override public void onItemSelected(T item) { Fragment oldFragment = getSupportFragmentManager().findFragmentById(R.id.detailsFragmentContainer); if (oldFragment == null) { ActivityLauncher.launchActivity(item.getActivityClass()); } else { if (!oldFragment.getTag().equals(item.getName())) { replaceDetailsFragment(item); } } } private void replaceDetailsFragment(T item) { FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.detailsFragmentContainer, item.createFragment(null), item.getName()); fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); fragmentTransaction.commit(); } /** * @see android.support.v4.app.FragmentActivity#onNewIntent(android.content.Intent) */ @SuppressWarnings("unchecked") @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); T contextualItem = (T)intent.getExtras().getSerializable(DEFAULT_CONTEXTUAL_ITEM_EXTRA); if (AndroidUtils.isLargeScreenOrBigger()) { // Refresh the detail replaceDetailsFragment(contextualItem); // Refresh the list (only on large or bigger) FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.contextualFragmentContainer, newContextualListFragment(getContextualItems(), contextualItem)); fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); fragmentTransaction.commit(); } } }
jdroid-android/src/main/java/com/jdroid/android/contextual/ContextualActivity.java
package com.jdroid.android.contextual; import java.util.List; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import com.jdroid.android.ActivityLauncher; import com.jdroid.android.R; import com.jdroid.android.activity.AbstractFragmentActivity; import com.jdroid.android.fragment.OnItemSelectedListener; import com.jdroid.android.tabs.TabAction; import com.jdroid.android.utils.AndroidUtils; /** * * @param <T> * @author Maxi Rosson */ public abstract class ContextualActivity<T extends TabAction> extends AbstractFragmentActivity implements OnItemSelectedListener<T> { public static final String DEFAULT_CONTEXTUAL_ITEM_EXTRA = "defaultContextualItem"; /** * @see com.jdroid.android.activity.ActivityIf#getContentView() */ @Override public int getContentView() { return AndroidUtils.isLargeScreenOrBigger() ? R.layout.contextual_activity : R.layout.fragment_container_activity; } /** * @see android.preference.PreferenceActivity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { T defaultContextualItem = getExtra(DEFAULT_CONTEXTUAL_ITEM_EXTRA); if (defaultContextualItem == null) { defaultContextualItem = getDefaultContextualItem(); } FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); int contextualListFragmentId = AndroidUtils.isLargeScreenOrBigger() ? R.id.contextualFragmentContainer : R.id.fragmentContainer; fragmentTransaction.add(contextualListFragmentId, newContextualListFragment(getContextualItems(), defaultContextualItem)); if (AndroidUtils.isLargeScreenOrBigger()) { fragmentTransaction.add(R.id.detailsFragmentContainer, defaultContextualItem.createFragment(null), defaultContextualItem.getName()); } fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); fragmentTransaction.commit(); } } protected Fragment newContextualListFragment(List<T> actions, T defaultContextualItem) { return new ContextualListFragment(getContextualItems(), defaultContextualItem); } protected abstract List<T> getContextualItems(); protected abstract T getDefaultContextualItem(); /** * @see com.jdroid.android.fragment.OnItemSelectedListener#onItemSelected(java.lang.Object) */ @Override public void onItemSelected(T item) { Fragment oldFragment = getSupportFragmentManager().findFragmentById(R.id.detailsFragmentContainer); if (oldFragment == null) { ActivityLauncher.launchActivity(item.getActivityClass()); } else { if (!oldFragment.getTag().equals(item.getName())) { FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.detailsFragmentContainer, item.createFragment(null), item.getName()); fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); fragmentTransaction.commit(); } } } }
Added onNewIntent support to contextual activity
jdroid-android/src/main/java/com/jdroid/android/contextual/ContextualActivity.java
Added onNewIntent support to contextual activity
<ide><path>droid-android/src/main/java/com/jdroid/android/contextual/ContextualActivity.java <ide> package com.jdroid.android.contextual; <ide> <ide> import java.util.List; <add>import android.content.Intent; <ide> import android.os.Bundle; <ide> import android.support.v4.app.Fragment; <ide> import android.support.v4.app.FragmentTransaction; <ide> ActivityLauncher.launchActivity(item.getActivityClass()); <ide> } else { <ide> if (!oldFragment.getTag().equals(item.getName())) { <del> FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); <del> fragmentTransaction.replace(R.id.detailsFragmentContainer, item.createFragment(null), item.getName()); <del> fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); <del> fragmentTransaction.commit(); <add> replaceDetailsFragment(item); <ide> } <ide> } <ide> } <add> <add> private void replaceDetailsFragment(T item) { <add> FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); <add> fragmentTransaction.replace(R.id.detailsFragmentContainer, item.createFragment(null), item.getName()); <add> fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); <add> fragmentTransaction.commit(); <add> } <add> <add> /** <add> * @see android.support.v4.app.FragmentActivity#onNewIntent(android.content.Intent) <add> */ <add> @SuppressWarnings("unchecked") <add> @Override <add> protected void onNewIntent(Intent intent) { <add> super.onNewIntent(intent); <add> <add> T contextualItem = (T)intent.getExtras().getSerializable(DEFAULT_CONTEXTUAL_ITEM_EXTRA); <add> <add> if (AndroidUtils.isLargeScreenOrBigger()) { <add> <add> // Refresh the detail <add> replaceDetailsFragment(contextualItem); <add> <add> // Refresh the list (only on large or bigger) <add> FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); <add> fragmentTransaction.replace(R.id.contextualFragmentContainer, <add> newContextualListFragment(getContextualItems(), contextualItem)); <add> fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); <add> fragmentTransaction.commit(); <add> } <add> } <ide> }
Java
apache-2.0
e564042c81a9678e60b6fd5211b61cdbd2865531
0
kuali/rice-playground,kuali/rice-playground,kuali/rice-playground,ricepanda/rice-git3,kuali/rice-playground,ricepanda/rice-git2,ricepanda/rice-git3,ricepanda/rice-git2,ricepanda/rice-git3,ricepanda/rice-git3,ricepanda/rice-git2,ricepanda/rice-git2
/* * Copyright 2007 The Kuali Foundation * * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php * * 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. */ package org.kuali.rice.krad.uif.util; import org.apache.commons.lang.StringUtils; import org.kuali.rice.krad.uif.UifConstants; import org.kuali.rice.krad.uif.UifPropertyPaths; import org.kuali.rice.krad.uif.view.View; import org.kuali.rice.krad.uif.component.BindingInfo; import org.kuali.rice.krad.uif.component.Component; import org.kuali.rice.krad.uif.layout.LayoutManager; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Utility class for UIF expressions * * @author Kuali Rice Team ([email protected]) */ public class ExpressionUtils { /** * @param view * @param object */ public static void adjustPropertyExpressions(View view, Object object) { if (object == null) { return; } // get the map of property expressions to adjust Map<String, String> propertyExpressions = new HashMap<String, String>(); if (Component.class.isAssignableFrom(object.getClass())) { propertyExpressions = ((Component) object).getPropertyExpressions(); } else if (LayoutManager.class.isAssignableFrom(object.getClass())) { propertyExpressions = ((LayoutManager) object).getPropertyExpressions(); } else if (BindingInfo.class.isAssignableFrom(object.getClass())) { propertyExpressions = ((BindingInfo) object).getPropertyExpressions(); } boolean defaultPathSet = StringUtils.isNotBlank(view.getDefaultBindingObjectPath()); Map<String, String> adjustedPropertyExpressions = new HashMap<String, String>(); for (Map.Entry<String, String> propertyExpression : propertyExpressions.entrySet()) { String propertyName = propertyExpression.getKey(); String expression = propertyExpression.getValue(); // if property name is nested, need to move the expression to the parent object if (StringUtils.contains(propertyName, ".")) { boolean expressionMoved = moveNestedPropertyExpression(object, propertyName, expression); // if expression moved, skip rest of control statement so it is not added to the adjusted map if (expressionMoved) { continue; } } adjustedPropertyExpressions.put(propertyName, expression); } // update property expressions map on object ObjectPropertyUtils.setPropertyValue(object, UifPropertyPaths.PROPERTY_EXPRESSIONS, adjustedPropertyExpressions); // TODO: In progress, adjusting paths in expressions // if (defaultPathSet) { // String adjustedExpression = ""; // // // check for expression placeholder wrapper or multiple expressions (template) // if (StringUtils.contains(expression, "@{") && StringUtils.contains(expression, "}")) { // String remainder = expression; // // while (StringUtils.isNotBlank(remainder) && StringUtils.contains(remainder, "@{") && StringUtils // .contains(remainder, "}")) { // String beforeLiteral = StringUtils.substringBefore(remainder, "@{"); // String afterBeginDelimiter = StringUtils.substringAfter(remainder, "@{"); // String nestedExpression = StringUtils.substringBefore(afterBeginDelimiter, "}"); // remainder = StringUtils.substringAfter(afterBeginDelimiter, "}"); // // if (StringUtils.isNotBlank(beforeLiteral)) { // adjustedExpression += beforeLiteral; // } // adjustedExpression += "@{"; // // if (StringUtils.isNotBlank(nestedExpression)) { // String adjustedNestedExpression = processExpression(nestedExpression, // view.getDefaultBindingObjectPath()); // adjustedExpression += adjustedNestedExpression; // } // adjustedExpression += "}"; // } // // // add last remainder if was a literal (did not contain expression placeholders) // if (StringUtils.isNotBlank(remainder)) { // adjustedExpression += remainder; // } // } else { // // treat expression as one // adjustedExpression = processExpression(expression, view.getDefaultBindingObjectPath()); // } // // adjustedPropertyExpressions.put(propertyName, adjustedExpression); // } else { // adjustedPropertyExpressions.put(propertyName, expression); // } // } // } protected static String processExpression(String expression, String pathPrefix) { String processedExpression = ""; Tokenizer tokenizer = new Tokenizer(expression); tokenizer.process(); Tokenizer.Token previousToken = null; for (Tokenizer.Token token : tokenizer.getTokens()) { if (token.isIdentifier()) { // if an identifier, verify it is a model property name (must be at beginning of expression of // come after a space) String identifier = token.stringValue(); if ((previousToken == null) || (previousToken.isIdentifier() && StringUtils.isBlank( previousToken.stringValue()))) { // append path prefix unless specified as form property if (!StringUtils.startsWith(identifier, "form")) { identifier = pathPrefix + "." + identifier; } } processedExpression += identifier; } else if (token.getKind().tokenChars.length != 0) { processedExpression += new String(token.getKind().tokenChars); } else { processedExpression += token.stringValue(); } previousToken = token; } // remove special binding prefixes processedExpression = StringUtils.replace(processedExpression, UifConstants.NO_BIND_ADJUST_PREFIX, ""); return processedExpression; } protected static boolean moveNestedPropertyExpression(Object object, String propertyName, String expression) { boolean moved = false; // get the parent object for the property String parentPropertyName = StringUtils.substringBeforeLast(propertyName, "."); String propertyNameInParent = StringUtils.substringAfterLast(propertyName, "."); Object parentObject = ObjectPropertyUtils.getPropertyValue(object, parentPropertyName); if ((parentObject != null) && ObjectPropertyUtils.isReadableProperty(parentObject, UifPropertyPaths.PROPERTY_EXPRESSIONS) && ((parentObject instanceof Component) || (parentObject instanceof LayoutManager) || (parentObject instanceof BindingInfo))) { Map<String, String> propertyExpressions = ObjectPropertyUtils.getPropertyValue(parentObject, UifPropertyPaths.PROPERTY_EXPRESSIONS); if (propertyExpressions == null) { propertyExpressions = new HashMap<String, String>(); } // add expression to map on parent object propertyExpressions.put(propertyNameInParent, expression); ObjectPropertyUtils.setPropertyValue(parentObject, UifPropertyPaths.PROPERTY_EXPRESSIONS, propertyExpressions); moved = true; } return moved; } /** * Takes in an expression and a list to be filled in with names(property names) * of controls found in the expression. This method returns a js expression which can * be executed on the client to determine if the original exp was satisfied before * interacting with the server - ie, this js expression is equivalent to the one passed in. * * There are limitations on the Spring expression language that can be used as this method. * It is only used to parse expressions which are valid case statements for determining if * some action/processing should be performed. ONLY Properties, comparison operators, booleans, * strings, matches expression, and boolean logic are supported. Properties must * be a valid property on the form, and should have a visible control within the view. * * Example valid exp: account.name == 'Account Name' * * @param exp * @param controlNames * @return */ public static String parseExpression(String exp, List<String> controlNames) { // clean up expression to ease parsing exp = exp.trim(); if(exp.startsWith("@{")){ exp = StringUtils.removeStart(exp, "@{"); if(exp.endsWith("}")){ exp = StringUtils.removeEnd(exp,"}"); } } exp = StringUtils.replace(exp, "!=", " != "); exp = StringUtils.replace(exp, "==", " == "); exp = StringUtils.replace(exp, ">", " > "); exp = StringUtils.replace(exp, "<", " < "); exp = StringUtils.replace(exp, "<=", " <= "); exp = StringUtils.replace(exp, ">=", " >= "); String conditionJs = exp; String stack = ""; boolean expectingSingleQuote = false; boolean ignoreNext = false; for (int i = 0; i < exp.length(); i++) { char c = exp.charAt(i); if (!expectingSingleQuote && !ignoreNext && (c == '(' || c == ' ' || c == ')')) { evaluateCurrentStack(stack.trim(), controlNames); //reset stack stack = ""; continue; } else if (!ignoreNext && c == '\'') { stack = stack + c; expectingSingleQuote = !expectingSingleQuote; } else if (c == '\\') { stack = stack + c; ignoreNext = !ignoreNext; } else { stack = stack + c; ignoreNext = false; } } if(StringUtils.isNotEmpty(stack)){ evaluateCurrentStack(stack.trim(), controlNames); } conditionJs = conditionJs.replaceAll("\\s(?i:ne)\\s", " != ").replaceAll("\\s(?i:eq)\\s", " == ").replaceAll( "\\s(?i:gt)\\s", " > ").replaceAll("\\s(?i:lt)\\s", " < ").replaceAll("\\s(?i:lte)\\s", " <= ") .replaceAll("\\s(?i:gte)\\s", " >= ").replaceAll("\\s(?i:and)\\s", " && ").replaceAll("\\s(?i:or)\\s", " || ").replaceAll("\\s(?i:not)\\s", " != ").replaceAll("\\s(?i:null)\\s?", " '' ").replaceAll( "\\s?(?i:#empty)\\((.*?)\\)", "isValueEmpty($1)"); if (conditionJs.contains("matches")) { conditionJs = conditionJs.replaceAll("\\s+(?i:matches)\\s+'.*'", ".match(/" + "$0" + "/) != null "); conditionJs = conditionJs.replaceAll("\\(/\\s+(?i:matches)\\s+'", "(/"); conditionJs = conditionJs.replaceAll("'\\s*/\\)", "/)"); } for (String propertyName : controlNames) { conditionJs = conditionJs.replace(propertyName, "coerceValue(\"" + propertyName + "\")"); } return conditionJs; } /** * Used internally by parseExpression to evalute if the current stack is a property * name (ie, will be a control on the form) * * @param stack * @param controlNames */ public static void evaluateCurrentStack(String stack, List<String> controlNames) { if (StringUtils.isNotBlank(stack)) { if (!(stack.equals("==") || stack.equals("!=") || stack.equals(">") || stack.equals("<") || stack.equals(">=") || stack.equals("<=") || stack.equalsIgnoreCase("ne") || stack.equalsIgnoreCase("eq") || stack.equalsIgnoreCase("gt") || stack.equalsIgnoreCase("lt") || stack.equalsIgnoreCase("lte") || stack.equalsIgnoreCase("gte") || stack.equalsIgnoreCase("matches") || stack.equalsIgnoreCase("null") || stack.equalsIgnoreCase("false") || stack.equalsIgnoreCase("true") || stack.equalsIgnoreCase("and") || stack.equalsIgnoreCase("or") || stack.contains("#empty") || stack.startsWith("'") || stack.endsWith("'"))) { boolean isNumber = false; if ((StringUtils.isNumeric(stack.substring(0, 1)) || stack.substring(0, 1).equals("-"))) { try { Double.parseDouble(stack); isNumber = true; } catch (NumberFormatException e) { isNumber = false; } } if (!(isNumber)) { if (!controlNames.contains(stack)) { controlNames.add(stack); } } } } } }
krad/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/util/ExpressionUtils.java
/* * Copyright 2007 The Kuali Foundation * * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php * * 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. */ package org.kuali.rice.krad.uif.util; import org.apache.commons.lang.StringUtils; import org.kuali.rice.krad.uif.UifConstants; import org.kuali.rice.krad.uif.UifPropertyPaths; import org.kuali.rice.krad.uif.view.View; import org.kuali.rice.krad.uif.component.BindingInfo; import org.kuali.rice.krad.uif.component.Component; import org.kuali.rice.krad.uif.layout.LayoutManager; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Utility class for UIF expressions * * @author Kuali Rice Team ([email protected]) */ public class ExpressionUtils { /** * @param view * @param object */ public static void adjustPropertyExpressions(View view, Object object) { if (object == null) { return; } // get the map of property expressions to adjust Map<String, String> propertyExpressions = new HashMap<String, String>(); if (Component.class.isAssignableFrom(object.getClass())) { propertyExpressions = ((Component) object).getPropertyExpressions(); } else if (LayoutManager.class.isAssignableFrom(object.getClass())) { propertyExpressions = ((LayoutManager) object).getPropertyExpressions(); } else if (BindingInfo.class.isAssignableFrom(object.getClass())) { propertyExpressions = ((BindingInfo) object).getPropertyExpressions(); } boolean defaultPathSet = StringUtils.isNotBlank(view.getDefaultBindingObjectPath()); Map<String, String> adjustedPropertyExpressions = new HashMap<String, String>(); for (Map.Entry<String, String> propertyExpression : propertyExpressions.entrySet()) { String propertyName = propertyExpression.getKey(); String expression = propertyExpression.getValue(); // if property name is nested, need to move the expression to the parent object if (StringUtils.contains(propertyName, ".")) { boolean expressionMoved = moveNestedPropertyExpression(object, propertyName, expression); // if expression moved, skip rest of control statement so it is not added to the adjusted map if (expressionMoved) { continue; } } adjustedPropertyExpressions.put(propertyName, expression); } // update property expressions map on object ObjectPropertyUtils.setPropertyValue(object, UifPropertyPaths.PROPERTY_EXPRESSIONS, adjustedPropertyExpressions); // TODO: In progress, adjusting paths in expressions // if (defaultPathSet) { // String adjustedExpression = ""; // // // check for expression placeholder wrapper or multiple expressions (template) // if (StringUtils.contains(expression, "@{") && StringUtils.contains(expression, "}")) { // String remainder = expression; // // while (StringUtils.isNotBlank(remainder) && StringUtils.contains(remainder, "@{") && StringUtils // .contains(remainder, "}")) { // String beforeLiteral = StringUtils.substringBefore(remainder, "@{"); // String afterBeginDelimiter = StringUtils.substringAfter(remainder, "@{"); // String nestedExpression = StringUtils.substringBefore(afterBeginDelimiter, "}"); // remainder = StringUtils.substringAfter(afterBeginDelimiter, "}"); // // if (StringUtils.isNotBlank(beforeLiteral)) { // adjustedExpression += beforeLiteral; // } // adjustedExpression += "@{"; // // if (StringUtils.isNotBlank(nestedExpression)) { // String adjustedNestedExpression = processExpression(nestedExpression, // view.getDefaultBindingObjectPath()); // adjustedExpression += adjustedNestedExpression; // } // adjustedExpression += "}"; // } // // // add last remainder if was a literal (did not contain expression placeholders) // if (StringUtils.isNotBlank(remainder)) { // adjustedExpression += remainder; // } // } else { // // treat expression as one // adjustedExpression = processExpression(expression, view.getDefaultBindingObjectPath()); // } // // adjustedPropertyExpressions.put(propertyName, adjustedExpression); // } else { // adjustedPropertyExpressions.put(propertyName, expression); // } // } // } protected static String processExpression(String expression, String pathPrefix) { String processedExpression = ""; Tokenizer tokenizer = new Tokenizer(expression); tokenizer.process(); Tokenizer.Token previousToken = null; for (Tokenizer.Token token : tokenizer.getTokens()) { if (token.isIdentifier()) { // if an identifier, verify it is a model property name (must be at beginning of expression of // come after a space) String identifier = token.stringValue(); if ((previousToken == null) || (previousToken.isIdentifier() && StringUtils.isBlank( previousToken.stringValue()))) { // append path prefix unless specified as form property if (!StringUtils.startsWith(identifier, "form")) { identifier = pathPrefix + "." + identifier; } } processedExpression += identifier; } else if (token.getKind().tokenChars.length != 0) { processedExpression += new String(token.getKind().tokenChars); } else { processedExpression += token.stringValue(); } previousToken = token; } // remove special binding prefixes processedExpression = StringUtils.replace(processedExpression, UifConstants.NO_BIND_ADJUST_PREFIX, ""); return processedExpression; } protected static boolean moveNestedPropertyExpression(Object object, String propertyName, String expression) { boolean moved = false; // get the parent object for the property String parentPropertyName = StringUtils.substringBeforeLast(propertyName, "."); String propertyNameInParent = StringUtils.substringAfterLast(propertyName, "."); Object parentObject = ObjectPropertyUtils.getPropertyValue(object, parentPropertyName); if ((parentObject != null) && ObjectPropertyUtils.isReadableProperty(parentObject, UifPropertyPaths.PROPERTY_EXPRESSIONS) && ((parentObject instanceof Component) || (parentObject instanceof LayoutManager) || (parentObject instanceof BindingInfo))) { Map<String, String> propertyExpressions = ObjectPropertyUtils.getPropertyValue(parentObject, UifPropertyPaths.PROPERTY_EXPRESSIONS); if (propertyExpressions == null) { propertyExpressions = new HashMap<String, String>(); } // add expression to map on parent object propertyExpressions.put(propertyNameInParent, expression); ObjectPropertyUtils.setPropertyValue(parentObject, UifPropertyPaths.PROPERTY_EXPRESSIONS, propertyExpressions); moved = true; } return moved; } /** * Takes in an expression and a list to be filled in with names(property names) * of controls found in the expression. This method returns a js expression which can * be executed on the client to determine if the original exp was satisfied before * interacting with the server - ie, this js expression is equivalent to the one passed in. * * There are limitations on the Spring expression language that can be used as this method. * It is only used to parse expressions which are valid case statements for determining if * some action/processing should be performed. ONLY Properties, comparison operators, booleans, * strings, matches expression, and boolean logic are supported. Properties must * be a valid property on the form, and should have a visible control within the view. * * Example valid exp: account.name == 'Account Name' * * @param exp * @param controlNames * @return */ public static String parseExpression(String exp, List<String> controlNames) { // clean up expression to ease parsing exp = exp.trim(); if(exp.startsWith("@{")){ exp = StringUtils.removeStart(exp, "@{"); if(exp.endsWith("}")){ exp = StringUtils.removeEnd(exp,"}"); } } exp = StringUtils.replace(exp, "!=", " != "); exp = StringUtils.replace(exp, "==", " == "); exp = StringUtils.replace(exp, ">", " > "); exp = StringUtils.replace(exp, "<", " < "); exp = StringUtils.replace(exp, "<=", " <= "); exp = StringUtils.replace(exp, ">=", " >= "); String conditionJs = exp; String stack = ""; boolean expectingSingleQuote = false; boolean ignoreNext = false; for (int i = 0; i < exp.length(); i++) { char c = exp.charAt(i); if (!expectingSingleQuote && !ignoreNext && (c == '(' || c == ' ' || c == ')')) { evaluateCurrentStack(stack.trim(), controlNames); //reset stack stack = ""; continue; } else if (!ignoreNext && c == '\'') { stack = stack + c; expectingSingleQuote = !expectingSingleQuote; } else if (c == '\\') { stack = stack + c; ignoreNext = !ignoreNext; } else { stack = stack + c; ignoreNext = false; } } conditionJs = conditionJs.replaceAll("\\s(?i:ne)\\s", " != ").replaceAll("\\s(?i:eq)\\s", " == ").replaceAll( "\\s(?i:gt)\\s", " > ").replaceAll("\\s(?i:lt)\\s", " < ").replaceAll("\\s(?i:lte)\\s", " <= ") .replaceAll("\\s(?i:gte)\\s", " >= ").replaceAll("\\s(?i:and)\\s", " && ").replaceAll("\\s(?i:or)\\s", " || ").replaceAll("\\s(?i:not)\\s", " != ").replaceAll("\\s(?i:null)\\s?", " '' ").replaceAll( "\\s?(?i:#empty)\\((.*?)\\)", "isValueEmpty($1)"); if (conditionJs.contains("matches")) { conditionJs = conditionJs.replaceAll("\\s+(?i:matches)\\s+'.*'", ".match(/" + "$0" + "/) != null "); conditionJs = conditionJs.replaceAll("\\(/\\s+(?i:matches)\\s+'", "(/"); conditionJs = conditionJs.replaceAll("'\\s*/\\)", "/)"); } for (String propertyName : controlNames) { conditionJs = conditionJs.replace(propertyName, "coerceValue(\"" + propertyName + "\")"); } return conditionJs; } /** * Used internally by parseExpression to evalute if the current stack is a property * name (ie, will be a control on the form) * * @param stack * @param controlNames */ public static void evaluateCurrentStack(String stack, List<String> controlNames) { if (StringUtils.isNotBlank(stack)) { if (!(stack.equals("==") || stack.equals("!=") || stack.equals(">") || stack.equals("<") || stack.equals(">=") || stack.equals("<=") || stack.equalsIgnoreCase("ne") || stack.equalsIgnoreCase("eq") || stack.equalsIgnoreCase("gt") || stack.equalsIgnoreCase("lt") || stack.equalsIgnoreCase("lte") || stack.equalsIgnoreCase("gte") || stack.equalsIgnoreCase("matches") || stack.equalsIgnoreCase("null") || stack.equalsIgnoreCase("false") || stack.equalsIgnoreCase("true") || stack.equalsIgnoreCase("and") || stack.equalsIgnoreCase("or") || stack.contains("#empty") || stack.startsWith("'") || stack.endsWith("'"))) { boolean isNumber = false; if ((StringUtils.isNumeric(stack.substring(0, 1)) || stack.substring(0, 1).equals("-"))) { try { Double.parseDouble(stack); isNumber = true; } catch (NumberFormatException e) { isNumber = false; } } if (!(isNumber)) { if (!controlNames.contains(stack)) { controlNames.add(stack); } } } } } }
Small fix for expression evaluator git-svn-id: 2a5d2b5a02908a0c4ba7967b726d8c4198d1b9ed@22316 7a7aa7f6-c479-11dc-97e2-85a2497f191d
krad/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/util/ExpressionUtils.java
Small fix for expression evaluator
<ide><path>rad/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/util/ExpressionUtils.java <ide> stack = stack + c; <ide> ignoreNext = false; <ide> } <add> } <add> <add> if(StringUtils.isNotEmpty(stack)){ <add> evaluateCurrentStack(stack.trim(), controlNames); <ide> } <ide> <ide> conditionJs = conditionJs.replaceAll("\\s(?i:ne)\\s", " != ").replaceAll("\\s(?i:eq)\\s", " == ").replaceAll(
Java
mit
c5d992f2d5f867feb16af0bac8d2a88ca71aef2e
0
ganthore/docker-workflow-plugin,ganthore/docker-workflow-plugin,ganthore/docker-workflow-plugin
/* * The MIT License * * Copyright 2015 CloudBees, Inc. * * 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. */ package org.jenkinsci.plugins.workflow.multibranch; import hudson.Extension; import hudson.model.ItemGroup; import hudson.model.Queue; import hudson.model.TaskListener; import hudson.model.TopLevelItem; import hudson.scm.SCM; import hudson.scm.SCMDescriptor; import java.io.IOException; import java.util.List; import jenkins.branch.BranchProjectFactory; import jenkins.branch.MultiBranchProject; import jenkins.branch.MultiBranchProjectDescriptor; import jenkins.scm.api.SCMSource; import jenkins.scm.api.SCMSourceCriteria; import org.acegisecurity.Authentication; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; /** * Representation of a set of workflows keyed off of source branches. */ @SuppressWarnings({"unchecked", "rawtypes"}) // core’s fault public class WorkflowMultiBranchProject extends MultiBranchProject<WorkflowJob,WorkflowRun> { public WorkflowMultiBranchProject(ItemGroup parent, String name) { super(parent, name); } @Override protected BranchProjectFactory<WorkflowJob,WorkflowRun> newProjectFactory() { return new WorkflowBranchProjectFactory(); } @Override public SCMSourceCriteria getSCMSourceCriteria(SCMSource source) { return new SCMSourceCriteria() { @Override public boolean isHead(SCMSourceCriteria.Probe probe, TaskListener listener) throws IOException { return probe.exists(WorkflowBranchProjectFactory.SCRIPT); } }; } // TODO unnecessary to override once branch-api on 1.592+ @Override public Authentication getDefaultAuthentication(Queue.Item item) { return getDefaultAuthentication(); } @Extension public static class DescriptorImpl extends MultiBranchProjectDescriptor { @Override public String getDisplayName() { return "Multibranch Workflow"; } @Override public TopLevelItem newInstance(ItemGroup parent, String name) { return new WorkflowMultiBranchProject(parent, name); } @Override public List<SCMDescriptor<?>> getSCMDescriptors() { // TODO this is a problem. We need to select only those compatible with Workflow. // Yet SCMDescriptor.isApplicable requires an actual Job, whereas we can only pass WorkflowJob.class! // Can we create a dummy WorkflowJob instance? return SCM.all(); } } }
multibranch/src/main/java/org/jenkinsci/plugins/workflow/multibranch/WorkflowMultiBranchProject.java
/* * The MIT License * * Copyright 2015 CloudBees, Inc. * * 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. */ package org.jenkinsci.plugins.workflow.multibranch; import hudson.Extension; import hudson.model.ItemGroup; import hudson.model.TaskListener; import hudson.model.TopLevelItem; import hudson.scm.SCM; import hudson.scm.SCMDescriptor; import java.io.IOException; import java.util.List; import jenkins.branch.BranchProjectFactory; import jenkins.branch.MultiBranchProject; import jenkins.branch.MultiBranchProjectDescriptor; import jenkins.scm.api.SCMSource; import jenkins.scm.api.SCMSourceCriteria; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; /** * Representation of a set of workflows keyed off of source branches. */ @SuppressWarnings({"unchecked", "rawtypes"}) // core’s fault public class WorkflowMultiBranchProject extends MultiBranchProject<WorkflowJob,WorkflowRun> { public WorkflowMultiBranchProject(ItemGroup parent, String name) { super(parent, name); } @Override protected BranchProjectFactory<WorkflowJob,WorkflowRun> newProjectFactory() { return new WorkflowBranchProjectFactory(); } @Override public SCMSourceCriteria getSCMSourceCriteria(SCMSource source) { return new SCMSourceCriteria() { @Override public boolean isHead(SCMSourceCriteria.Probe probe, TaskListener listener) throws IOException { return probe.exists(WorkflowBranchProjectFactory.SCRIPT); } }; } @Extension public static class DescriptorImpl extends MultiBranchProjectDescriptor { @Override public String getDisplayName() { return "Multibranch Workflow"; } @Override public TopLevelItem newInstance(ItemGroup parent, String name) { return new WorkflowMultiBranchProject(parent, name); } @Override public List<SCMDescriptor<?>> getSCMDescriptors() { // TODO this is a problem. We need to select only those compatible with Workflow. // Yet SCMDescriptor.isApplicable requires an actual Job, whereas we can only pass WorkflowJob.class! // Can we create a dummy WorkflowJob instance? return SCM.all(); } } }
Adapted to upstream being on only 1.580.x.
multibranch/src/main/java/org/jenkinsci/plugins/workflow/multibranch/WorkflowMultiBranchProject.java
Adapted to upstream being on only 1.580.x.
<ide><path>ultibranch/src/main/java/org/jenkinsci/plugins/workflow/multibranch/WorkflowMultiBranchProject.java <ide> <ide> import hudson.Extension; <ide> import hudson.model.ItemGroup; <add>import hudson.model.Queue; <ide> import hudson.model.TaskListener; <ide> import hudson.model.TopLevelItem; <ide> import hudson.scm.SCM; <ide> import jenkins.branch.MultiBranchProjectDescriptor; <ide> import jenkins.scm.api.SCMSource; <ide> import jenkins.scm.api.SCMSourceCriteria; <add>import org.acegisecurity.Authentication; <ide> import org.jenkinsci.plugins.workflow.job.WorkflowJob; <ide> import org.jenkinsci.plugins.workflow.job.WorkflowRun; <ide> <ide> }; <ide> } <ide> <add> // TODO unnecessary to override once branch-api on 1.592+ <add> @Override public Authentication getDefaultAuthentication(Queue.Item item) { <add> return getDefaultAuthentication(); <add> } <add> <ide> @Extension public static class DescriptorImpl extends MultiBranchProjectDescriptor { <ide> <ide> @Override public String getDisplayName() {
Java
apache-2.0
696da8b94232a77dc419892ef8028954bada5934
0
fbk/utils
/* * Copyright (2010) Fondazione Bruno Kessler (FBK) * * FBK reserves all rights in the Program as delivered. * The Program or any portion thereof may not be reproduced * in any form whatsoever except as provided by license * without the written consent of FBK. A license under FBK's * rights in the Program may be available directly from FBK. */ package eu.fbk.utils.math; import eu.fbk.utils.mylibsvm.svm_node; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import java.util.Iterator; /** * This class implements a dense vector. * * @author Claudio Giuliano * @version %I%, %G% * @since 1.0 */ public class DenseVector implements Vector { /** * Define a static logger variable so that it references the * Logger instance named <code>DenseVector</code>. */ static Logger logger = Logger.getLogger(DenseVector.class.getName()); // protected float[] vector; // public DenseVector(int size) throws IllegalArgumentException { if (size <= 0) { throw new IllegalArgumentException(); } vector = new float[size]; } // end constructor // public DenseVector(float[] vector) { this.vector = vector; } // end constructor // public void add(int index, float value) throws IndexOutOfBoundsException { if (index < 0) { throw new IndexOutOfBoundsException(); } if (index > vector.length) { throw new IndexOutOfBoundsException(); } vector[index] += value; } // end add // public float get(int index) throws IndexOutOfBoundsException { //logger.info("get " + index); if (index < 0 || index > vector.length) { throw new IndexOutOfBoundsException(); } return vector[index]; } // end get // public boolean isSparse() { return false; } // end isSparse // public boolean isDense() { return true; } // end isDense // public Vector merge(Vector v) { if (v.isDense()) { return mergeDense((DenseVector) v); } return mergeSparse((SparseVector) v); } // end merge // protected Vector mergeSparse(SparseVector v) { Vector m = new SparseVector(); for (int i = 0; i < size(); i++) { m.add(i, get(i)); } Iterator<Integer> it2 = v.nonZeroElements(); int i = 0; while (it2.hasNext()) { i = it2.next(); m.add(i + size(), v.get(i)); } // end while return m; } // end mergeSparse // protected Vector mergeDense(DenseVector v) { Vector m = new DenseVector(size() + v.size()); for (int i = 0; i < size(); i++) { m.add(i, get(i)); } for (int i = 0; i < v.size(); i++) { m.add(i + size(), v.get(i)); } return m; } // end mergeDense // public boolean existsIndex(int index) { //logger.debug("existsIndex: " + index); if (index >= 0 && index < vector.length) { return true; } return false; } // end existsIndex // public void set(int index, float value) throws IndexOutOfBoundsException { //logger.debug("set " + index + ", " + value); if (index < 0) { throw new IndexOutOfBoundsException(); } if (index > vector.length) { throw new IndexOutOfBoundsException(); } vector[index] = value; } // end set // public int size() { return vector.length; } // end vector.length // public int elementCount() { return size(); } // end elementCount // public Iterator<Float> iterator() { return new ValueIterator(vector); } // end iterator // public Iterator<Integer> nonZeroElements() { return new IndexIterator(vector.length); } // end nonZeroElements // public String toString(int fromIndex) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < vector.length; i++) { if (vector[i] != 0) { if (i > 0) { sb.append(" "); } sb.append(fromIndex + i); sb.append(":"); sb.append(vector[i]); } } // end while return sb.toString(); } // end toString // public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < vector.length; i++) { if (vector[i] != 0) { if (i > 0) { sb.append(" "); } sb.append(i); sb.append(":"); sb.append(vector[i]); } } // end while return sb.toString(); } // end toString // public Node[] toNodeArray() { Node[] node = new Node[vector.length]; for (int i = 0; i < vector.length; i++) { node[i] = new Node(); node[i].index = i; node[i].value = vector[i]; } return node; } // end toNodeArray // public Node[] toNodeArray(int fromIndex) { Node[] node = new Node[vector.length]; for (int i = 0; i < vector.length; i++) { node[i] = new Node(); node[i].index = fromIndex + i; node[i].value = vector[i]; } return node; } // end toNodeArray // public svm_node[] toSvmNodeArray() { svm_node[] node = new svm_node[vector.length]; for (int i = 0; i < vector.length; i++) { node[i] = new svm_node(); node[i].index = i; node[i].value = vector[i]; } return node; } // end toNodeArray // public svm_node[] toSvmNodeArray(int fromIndex) { svm_node[] node = new svm_node[vector.length]; for (int i = 0; i < vector.length; i++) { node[i] = new svm_node(); node[i].index = fromIndex + i; node[i].value = vector[i]; } return node; } // end toNodeArray public float[] toArray() { return vector; } // end toArray // public float dotProduct(DenseVector anotherDenseVector) { //logger.info("dotProduct(DenseVector) " + anotherDenseVector); float[] anotherVector = anotherDenseVector.toArray(); int len = vector.length; if (len > anotherVector.length) { len = anotherVector.length; } float d = 0; for (int i = 0; i < len; i++) { d += vector[i] * anotherVector[i]; } return d; } // end dotProduct // public float dotProduct(Vector anotherVector) { //logger.info("dotProduct(Vector) " + anotherVector); if (anotherVector.getClass() == this.getClass()) { return dotProduct((DenseVector) anotherVector); } float d = 0; int len = vector.length; if (vector.length > anotherVector.size()) { Iterator<Integer> it = anotherVector.nonZeroElements(); while (it.hasNext()) { int index = it.next().intValue(); d += vector[index] * anotherVector.get(index); } } else { for (int i = 0; i < len; i++) { d += vector[i] * anotherVector.get(i); } } return d; } // end dotProduct // public float norm() { float norm = 0; for (int i = 0; i < vector.length; i++) { norm += Math.pow(vector[i], 2); } return (float) Math.sqrt(norm); } // end norm // public void normalize() { float norm = norm(); //logger.debug("norm before = " + norm); // CHECK THIS! if (norm == 0) { return; } for (int i = 0; i < vector.length; i++) { vector[i] /= norm; } //logger.debug("norm after = " + norm()); } // end normalize // class ValueIterator implements Iterator { // private float[] vector; // private int i; // public ValueIterator(float[] vector) { this.vector = vector; i = 0; } // end constructor // public boolean hasNext() { return i < vector.length; } // end hasNext // public Object next() { return new Float(vector[i++]); } // end next // public void remove() { // do nothing } // end remove } // end IndexIterator // class IndexIterator implements Iterator { // private int len; // private int i; // public IndexIterator(int len) { this.len = len; i = 0; } // end constructor // public boolean hasNext() { return i < len; } // end hasNext public Object next() { return new Integer(i++); } // end next // public void remove() { // do nothing } // end remove } // end IndexIterator // public static void main(String args[]) throws Exception { String logConfig = System.getProperty("log-config"); if (logConfig == null) { logConfig = "log-config.txt"; } PropertyConfigurator.configure(logConfig); long begin = System.currentTimeMillis(); /* DenseVector vector = new DenseVector(); // java org.fbk.it.hlt.termsim.DenseVector int max = 50000; for (int i=0;i<max;i++) { double r = Math.random(); int j = (int) (r * max); //System.out.println(i + ":" + j + ":" + r); if (r < 0.0005) vector.add(i, r); } // end for i System.out.println(vector); System.out.println(vector.vector.length()); */ DenseVector v1 = new DenseVector(2); v1.add(0, 1); v1.add(1, 1); logger.info("v1.size: " + v1.size()); logger.info("v1: " + v1); logger.info("v1.norm: " + v1.norm()); v1.normalize(); logger.info("n1: " + v1); logger.info(""); //DenseVector v2 = new DenseVector(43); SparseVector v2 = new SparseVector(); v2.add(0, 1); v2.add(1, 1); v2.add(7, 1); v2.add(42, 1); v2.add(13, 1); v2.add(12, 1); v2.add(5, 1); v2.add(8, 1); v2.add(42, 1); logger.info("v2.size: " + v2.size()); logger.info("v2: " + v2); logger.info("v2.norm: " + v2.norm()); v2.normalize(); logger.info("n2: " + v2); logger.info(""); logger.info(v1 + " * " + v2 + " = " + v1.dotProduct(v2)); float f1 = v1.dotProduct(v1); float f2 = v2.dotProduct(v2); float f = v1.dotProduct(v2) / (float) Math.sqrt(f1 * f2); logger.info("f = " + f); long end = System.currentTimeMillis(); System.out.println("time " + (end - begin) + " ms"); } // end main } // end class DenseVector
utils-math/src/main/java/eu/fbk/utils/math/DenseVector.java
/* * Copyright (2010) Fondazione Bruno Kessler (FBK) * * FBK reserves all rights in the Program as delivered. * The Program or any portion thereof may not be reproduced * in any form whatsoever except as provided by license * without the written consent of FBK. A license under FBK's * rights in the Program may be available directly from FBK. */ package eu.fbk.utils.math; import eu.fbk.utils.mylibsvm.svm_node; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import java.util.Iterator; /** * This class implements a dense vector. * * @author Claudio Giuliano * @version %I%, %G% * @since 1.0 */ public class DenseVector implements Vector { /** * Define a static logger variable so that it references the * Logger instance named <code>DenseVector</code>. */ static Logger logger = Logger.getLogger(DenseVector.class.getName()); // protected float[] vector; // public DenseVector(int size) throws IllegalArgumentException { if (size <= 0) { throw new IllegalArgumentException(); } vector = new float[size]; } // end constructor // public DenseVector(float[] vector) { this.vector = vector; } // end constructor // public void add(int index, float value) throws IndexOutOfBoundsException { if (index < 0) { throw new IndexOutOfBoundsException(); } if (index > vector.length) { throw new IndexOutOfBoundsException(); } vector[index] += value; } // end add // public float get(int index) throws IndexOutOfBoundsException { //logger.info("get " + index); if (index < 0 || index > vector.length) { throw new IndexOutOfBoundsException(); } return vector[index]; } // end get // public boolean isSparse() { return false; } // end isSparse // public boolean isDense() { return true; } // end isDense // public Vector merge(Vector v) { if (v.isDense()) { return mergeDense((DenseVector) v); } return mergeSparse((SparseVector) v); } // end merge // protected Vector mergeSparse(SparseVector v) { Vector m = new SparseVector(); for (int i = 0; i < size(); i++) { m.add(i, get(i)); } Iterator<Integer> it2 = v.nonZeroElements(); int i = 0; while (it2.hasNext()) { i = it2.next(); m.add(i + v.size(), v.get(i)); } // end while return m; } // end mergeSparse // protected Vector mergeDense(DenseVector v) { Vector m = new DenseVector(size() + v.size()); for (int i = 0; i < size(); i++) { m.add(i, get(i)); } for (int i = 0; i < v.size(); i++) { m.add(i + v.size(), v.get(i)); } return m; } // end mergeDense // public boolean existsIndex(int index) { //logger.debug("existsIndex: " + index); if (index >= 0 && index < vector.length) { return true; } return false; } // end existsIndex // public void set(int index, float value) throws IndexOutOfBoundsException { //logger.debug("set " + index + ", " + value); if (index < 0) { throw new IndexOutOfBoundsException(); } if (index > vector.length) { throw new IndexOutOfBoundsException(); } vector[index] = value; } // end set // public int size() { return vector.length; } // end vector.length // public int elementCount() { return size(); } // end elementCount // public Iterator<Float> iterator() { return new ValueIterator(vector); } // end iterator // public Iterator<Integer> nonZeroElements() { return new IndexIterator(vector.length); } // end nonZeroElements // public String toString(int fromIndex) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < vector.length; i++) { if (vector[i] != 0) { if (i > 0) { sb.append(" "); } sb.append(fromIndex + i); sb.append(":"); sb.append(vector[i]); } } // end while return sb.toString(); } // end toString // public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < vector.length; i++) { if (vector[i] != 0) { if (i > 0) { sb.append(" "); } sb.append(i); sb.append(":"); sb.append(vector[i]); } } // end while return sb.toString(); } // end toString // public Node[] toNodeArray() { Node[] node = new Node[vector.length]; for (int i = 0; i < vector.length; i++) { node[i] = new Node(); node[i].index = i; node[i].value = vector[i]; } return node; } // end toNodeArray // public Node[] toNodeArray(int fromIndex) { Node[] node = new Node[vector.length]; for (int i = 0; i < vector.length; i++) { node[i] = new Node(); node[i].index = fromIndex + i; node[i].value = vector[i]; } return node; } // end toNodeArray // public svm_node[] toSvmNodeArray() { svm_node[] node = new svm_node[vector.length]; for (int i = 0; i < vector.length; i++) { node[i] = new svm_node(); node[i].index = i; node[i].value = vector[i]; } return node; } // end toNodeArray // public svm_node[] toSvmNodeArray(int fromIndex) { svm_node[] node = new svm_node[vector.length]; for (int i = 0; i < vector.length; i++) { node[i] = new svm_node(); node[i].index = fromIndex + i; node[i].value = vector[i]; } return node; } // end toNodeArray public float[] toArray() { return vector; } // end toArray // public float dotProduct(DenseVector anotherDenseVector) { //logger.info("dotProduct(DenseVector) " + anotherDenseVector); float[] anotherVector = anotherDenseVector.toArray(); int len = vector.length; if (len > anotherVector.length) { len = anotherVector.length; } float d = 0; for (int i = 0; i < len; i++) { d += vector[i] * anotherVector[i]; } return d; } // end dotProduct // public float dotProduct(Vector anotherVector) { //logger.info("dotProduct(Vector) " + anotherVector); if (anotherVector.getClass() == this.getClass()) { return dotProduct((DenseVector) anotherVector); } float d = 0; int len = vector.length; if (vector.length > anotherVector.size()) { Iterator<Integer> it = anotherVector.nonZeroElements(); while (it.hasNext()) { int index = it.next().intValue(); d += vector[index] * anotherVector.get(index); } } else { for (int i = 0; i < len; i++) { d += vector[i] * anotherVector.get(i); } } return d; } // end dotProduct // public float norm() { float norm = 0; for (int i = 0; i < vector.length; i++) { norm += Math.pow(vector[i], 2); } return (float) Math.sqrt(norm); } // end norm // public void normalize() { float norm = norm(); //logger.debug("norm before = " + norm); // CHECK THIS! if (norm == 0) { return; } for (int i = 0; i < vector.length; i++) { vector[i] /= norm; } //logger.debug("norm after = " + norm()); } // end normalize // class ValueIterator implements Iterator { // private float[] vector; // private int i; // public ValueIterator(float[] vector) { this.vector = vector; i = 0; } // end constructor // public boolean hasNext() { return i < vector.length; } // end hasNext // public Object next() { return new Float(vector[i++]); } // end next // public void remove() { // do nothing } // end remove } // end IndexIterator // class IndexIterator implements Iterator { // private int len; // private int i; // public IndexIterator(int len) { this.len = len; i = 0; } // end constructor // public boolean hasNext() { return i < len; } // end hasNext public Object next() { return new Integer(i++); } // end next // public void remove() { // do nothing } // end remove } // end IndexIterator // public static void main(String args[]) throws Exception { String logConfig = System.getProperty("log-config"); if (logConfig == null) { logConfig = "log-config.txt"; } PropertyConfigurator.configure(logConfig); long begin = System.currentTimeMillis(); /* DenseVector vector = new DenseVector(); // java org.fbk.it.hlt.termsim.DenseVector int max = 50000; for (int i=0;i<max;i++) { double r = Math.random(); int j = (int) (r * max); //System.out.println(i + ":" + j + ":" + r); if (r < 0.0005) vector.add(i, r); } // end for i System.out.println(vector); System.out.println(vector.vector.length()); */ DenseVector v1 = new DenseVector(2); v1.add(0, 1); v1.add(1, 1); logger.info("v1.size: " + v1.size()); logger.info("v1: " + v1); logger.info("v1.norm: " + v1.norm()); v1.normalize(); logger.info("n1: " + v1); logger.info(""); //DenseVector v2 = new DenseVector(43); SparseVector v2 = new SparseVector(); v2.add(0, 1); v2.add(1, 1); v2.add(7, 1); v2.add(42, 1); v2.add(13, 1); v2.add(12, 1); v2.add(5, 1); v2.add(8, 1); v2.add(42, 1); logger.info("v2.size: " + v2.size()); logger.info("v2: " + v2); logger.info("v2.norm: " + v2.norm()); v2.normalize(); logger.info("n2: " + v2); logger.info(""); logger.info(v1 + " * " + v2 + " = " + v1.dotProduct(v2)); float f1 = v1.dotProduct(v1); float f2 = v2.dotProduct(v2); float f = v1.dotProduct(v2) / (float) Math.sqrt(f1 * f2); logger.info("f = " + f); long end = System.currentTimeMillis(); System.out.println("time " + (end - begin) + " ms"); } // end main } // end class DenseVector
Fixed issue #4
utils-math/src/main/java/eu/fbk/utils/math/DenseVector.java
Fixed issue #4
<ide><path>tils-math/src/main/java/eu/fbk/utils/math/DenseVector.java <ide> int i = 0; <ide> while (it2.hasNext()) { <ide> i = it2.next(); <del> m.add(i + v.size(), v.get(i)); <add> m.add(i + size(), v.get(i)); <ide> } // end while <ide> <ide> return m; <ide> } <ide> <ide> for (int i = 0; i < v.size(); i++) { <del> m.add(i + v.size(), v.get(i)); <add> m.add(i + size(), v.get(i)); <ide> } <ide> return m; <ide> } // end mergeDense
JavaScript
mit
0e4b24156a94ec73cf0a39d624af8897d0cd5c1b
0
brrd/electron-tabs
if (!document) { throw Error("electron-tabs module must be called in renderer process"); } // Inject styles (function () { const styles = ` webview { display: flex; flex: 0 1; width: 0px; height: 0px; } webview.visible { width: 100%; height: 100%; top: 0; right: 0; bottom: 0; left: 0; } `; let styleTag = document.createElement("style"); styleTag.innerHTML = styles; document.getElementsByTagName("head")[0].appendChild(styleTag); })(); class TabGroup { constructor (args) { let options = this.options = { tabContainerSelector: args.tabContainerSelector || ".tabs-tabcontainer", viewContainerSelector: args.viewContainerSelector || ".tabs-viewcontainer", tabClass: args.tabClass || "tabs-tab", viewClass: args.viewClass || "tabs-view" }; this.tabContainer = document.querySelector(options.tabContainerSelector); this.viewContainer = document.querySelector(options.viewContainerSelector); this.tabs = []; this.newTabId = 0; } addTab (args) { let id = this.newTabId; this.newTabId++; let tab = new Tab(this, id, args); this.pushTab(tab); return tab; } pushTab (tab) { this.tabs.push(tab); } removeTab (tab) { let id = tab.id; for (let i in this.tabs) { if (this.tabs[i].id === id) { this.tabs.splice(i, 1); break; } } } setActiveTab (tab) { this.removeTab(tab); this.pushTab(tab); } getActiveTab () { if (this.tabs.length < 1) return null; return this.tabs[this.tabs.length - 1]; } activateRecentTab (tab) { let recentTab = this.tabs[this.tabs.length - 1]; if (!recentTab) return; recentTab.activate(); } } class Tab { constructor (tabGroup, id, args) { this.tabGroup = tabGroup; this.id = id; this.title = args.title; this.iconURL = args.iconURL; this.webviewAttributes = args.webviewAttributes || {}; this.webviewAttributes.src = args.src; this.tabElements = {}; this.initTab(); this.initWebview(); } initTab () { let tabClass = this.tabGroup.options.tabClass; // Create tab element let tab = this.tab = document.createElement("div"); tab.classList.add(tabClass); for (let el of ["icon", "title", "buttons"]) { let span = tab.appendChild(document.createElement("span")); span.classList.add(`${tabClass}-${el}`); this.tabElements[el] = span; } this.setTitle(this.title); this.setIcon(this.iconURL); tab.addEventListener("click", this.activate.bind(this), false); this.tabGroup.tabContainer.appendChild(this.tab); // TODO: close button // TODO: handle middle click } initWebview () { this.webview = document.createElement("webview"); this.webview.classList.add(this.tabGroup.options.viewClass); if (this.webviewAttributes) { let attrs = this.webviewAttributes; for (let key in attrs) { this.webview.setAttribute(key, attrs[key]); } } this.tabGroup.viewContainer.appendChild(this.webview); } setTitle (title) { let span = this.tabElements.title; span.innerHTML = title; this.title = title; } getTitle () { return this.title; } setIcon (iconURL) { this.iconURL = iconURL; let span = this.tabElements.icon; if (iconURL) { span.innerHTML = `<img src="${iconURL}" />`; } } getIcon () { return this.iconURL; } activate () { let activeTab = this.tabGroup.getActiveTab(); if (activeTab) { activeTab.tab.classList.remove("active"); activeTab.webview.classList.remove("visible"); } this.tabGroup.setActiveTab(this); this.tab.classList.add("active"); this.webview.classList.add("visible"); } flash (flag) { if (flag !== false) { this.tab.classList.add("flash"); } else { this.tab.classList.remove("flash"); } } move (index) { // TODO: move } close () { let tabGroup = this.tabGroup; tabGroup.tabContainer.removeChild(this.tab); tabGroup.viewContainer.removeChild(this.webview); tabGroup.removeTab(this); tabGroup.activateRecentTab(); } } module.exports = TabGroup;
index.js
if (!document) { throw Error("electron-tabs module must be called in renderer process"); } // Inject styles (function () { const styles = ` webview { display: flex; flex: 0 1; width: 0px; height: 0px; } webview.visible { width: 100%; height: 100%; top: 0; right: 0; bottom: 0; left: 0; } `; let styleTag = document.createElement("style"); styleTag.innerHTML = styles; document.getElementsByTagName("head")[0].appendChild(styleTag); })(); class TabGroup { constructor (args) { let options = this.options = { tabContainerSelector: args.tabContainerSelector || ".tabs-tabcontainer", viewContainerSelector: args.viewContainerSelector || ".tabs-viewcontainer", tabClass: args.tabClass || "tabs-tab", viewClass: args.viewClass || "tabs-view" }; this.tabContainer = document.querySelector(options.tabContainerSelector); this.viewContainer = document.querySelector(options.viewContainerSelector); this.tabs = []; this.newTabId = 0; } addTab (args) { let id = this.newTabId; this.newTabId++; let tab = new Tab(this, id, args); this.pushTab(tab); return tab; } pushTab (tab) { this.tabs.push(tab); } removeTab (tab) { let id = tab.id; for (let i in this.tabs) { if (this.tabs[i].id === id) { this.tabs.splice(i, 1); break; } } } setActiveTab (tab) { this.removeTab(tab); this.pushTab(tab); } getActiveTab () { if (this.tabs.length < 1) return null; return this.tabs[this.tabs.length - 1]; } activateRecentTab (tab) { let recentTab = this.tabs[this.tabs.length - 1]; if (!recentTab) return; recentTab.activate(); } } class Tab { constructor (tabGroup, id, args) { this.tabGroup = tabGroup; this.id = id; this.title = args.title; this.iconURL = args.iconURL; this.webviewAttributes = args.webviewAttributes || {}; this.webviewAttributes.src = args.src; this.initTab(); this.initWebview(); } initTab () { this.tab = document.createElement("div"); this.setTitle(this.title); this.tab.classList.add(this.tabGroup.options.tabClass); this.tab.addEventListener("click", this.activate.bind(this), false); this.tabGroup.tabContainer.appendChild(this.tab); // TODO: icon // TODO: close button // TODO: handle middle click } initWebview () { this.webview = document.createElement("webview"); this.webview.classList.add(this.tabGroup.options.viewClass); if (this.webviewAttributes) { let attrs = this.webviewAttributes; for (let key in attrs) { this.webview.setAttribute(key, attrs[key]); } } this.tabGroup.viewContainer.appendChild(this.webview); } setTitle (title) { this.title = title; this.tab.innerHTML = title; } getTitle () { return this.tab.innerHTML; } setIcon (iconURL) { this.iconURL = iconURL; this.tab.setAttribute("data-icon", iconURL); } activate () { let activeTab = this.tabGroup.getActiveTab(); if (activeTab) { activeTab.tab.classList.remove("active"); activeTab.webview.classList.remove("visible"); } this.tabGroup.setActiveTab(this); this.tab.classList.add("active"); this.webview.classList.add("visible"); } flash (flag) { if (flag !== false) { this.tab.classList.add("flash"); } else { this.tab.classList.remove("flash"); } } move (index) { // TODO: move } close () { let tabGroup = this.tabGroup; tabGroup.tabContainer.removeChild(this.tab); tabGroup.viewContainer.removeChild(this.webview); tabGroup.removeTab(this); tabGroup.activateRecentTab(); } } module.exports = TabGroup;
Support iconURL
index.js
Support iconURL
<ide><path>ndex.js <ide> this.iconURL = args.iconURL; <ide> this.webviewAttributes = args.webviewAttributes || {}; <ide> this.webviewAttributes.src = args.src; <add> this.tabElements = {}; <ide> this.initTab(); <ide> this.initWebview(); <ide> } <ide> <ide> initTab () { <del> this.tab = document.createElement("div"); <add> let tabClass = this.tabGroup.options.tabClass; <add> <add> // Create tab element <add> let tab = this.tab = document.createElement("div"); <add> tab.classList.add(tabClass); <add> for (let el of ["icon", "title", "buttons"]) { <add> let span = tab.appendChild(document.createElement("span")); <add> span.classList.add(`${tabClass}-${el}`); <add> this.tabElements[el] = span; <add> } <add> <ide> this.setTitle(this.title); <del> this.tab.classList.add(this.tabGroup.options.tabClass); <del> this.tab.addEventListener("click", this.activate.bind(this), false); <add> this.setIcon(this.iconURL); <add> <add> tab.addEventListener("click", this.activate.bind(this), false); <ide> this.tabGroup.tabContainer.appendChild(this.tab); <del> // TODO: icon <ide> // TODO: close button <ide> // TODO: handle middle click <ide> } <ide> } <ide> <ide> setTitle (title) { <add> let span = this.tabElements.title; <add> span.innerHTML = title; <ide> this.title = title; <del> this.tab.innerHTML = title; <ide> } <ide> <ide> getTitle () { <del> return this.tab.innerHTML; <add> return this.title; <ide> } <ide> <ide> setIcon (iconURL) { <ide> this.iconURL = iconURL; <del> this.tab.setAttribute("data-icon", iconURL); <add> let span = this.tabElements.icon; <add> if (iconURL) { <add> span.innerHTML = `<img src="${iconURL}" />`; <add> } <add> } <add> <add> getIcon () { <add> return this.iconURL; <ide> } <ide> <ide> activate () {
Java
bsd-3-clause
daa07c3eb0eea04da7e84a7423449d9369004793
0
Tiger66639/choco3,chocoteam/choco3,chocoteam/choco3,cp-profiler/choco3,cp-profiler/choco3,piyushsh/choco3,piyushsh/choco3,chocoteam/choco3,PhilAndrew/choco3gwt,piyushsh/choco3,cp-profiler/choco3,cp-profiler/choco3,PhilAndrew/choco3gwt,chocoteam/choco3,Tiger66639/choco3,piyushsh/choco3,PhilAndrew/choco3gwt,Tiger66639/choco3,Tiger66639/choco3
/** * Copyright (c) 1999-2011, Ecole des Mines de Nantes * 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 Ecole des Mines de Nantes 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 REGENTS 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 REGENTS AND 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. */ package solver.recorders.coarse; import solver.Solver; import solver.constraints.propagators.Propagator; import solver.exception.ContradictionException; import solver.search.loop.AbstractSearchLoop; import solver.variables.EventType; /** * <br/> * * @author Charles Prud'homme * @since 05/12/11 */ public class CoarseEventRecorder extends AbstractCoarseEventRecorder { int timestamp; // timestamp of the last clear call -- for lazy clear protected final Propagator propagator; int evtmask; // reference to events occuring -- inclusive OR over event mask public CoarseEventRecorder(Propagator propagator, Solver solver) { super(); this.propagator = propagator; this.evtmask = EventType.FULL_PROPAGATION.mask; // initialize with full propagation event propagator.addRecorder(this); } @Override public Propagator[] getPropagators() { return new Propagator[]{propagator}; } public void update(EventType e) { if ((e.mask & propagator.getPropagationConditions()) != 0) { // LoggerFactory.getLogger("solver").info("\t << {}", this.toString()); // 1. clear the structure if necessar if (LAZY) { if (timestamp - AbstractSearchLoop.timeStamp != 0) { this.evtmask = 0; timestamp = AbstractSearchLoop.timeStamp; } } // 2. store information concerning event if ((e.mask & evtmask) == 0) { // if the event has not been recorded yet (through strengthened event also). evtmask |= e.strengthened_mask; } // 3. schedule this if (!enqueued) { scheduler.schedule(this); } } } @Override public boolean execute() throws ContradictionException { if (!propagator.isActive()) { //promote event to top level event FULL_PROPAGATION evtmask |= EventType.FULL_PROPAGATION.strengthened_mask; propagator.setActive(); } if(propagator.getNbPendingER() > 0) { evtmask |= EventType.FULL_PROPAGATION.strengthened_mask; } if (evtmask > 0) { // LoggerFactory.getLogger("solver").info(">> {}", this.toString()); propagator.coarseERcalls++; int _evt = evtmask; evtmask = 0; propagator.propagate(_evt); } // unfreeze (and eventually unschedule) every fine event attached to this propagator propagator.forEachFineEvent(virtExec); return true; } @Override public void flush() { this.evtmask = 0; } @Override public String toString() { return propagator.toString(); } }
solver/src/main/java/solver/recorders/coarse/CoarseEventRecorder.java
/** * Copyright (c) 1999-2011, Ecole des Mines de Nantes * 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 Ecole des Mines de Nantes 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 REGENTS 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 REGENTS AND 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. */ package solver.recorders.coarse; import solver.Solver; import solver.constraints.propagators.Propagator; import solver.exception.ContradictionException; import solver.recorders.IEventRecorder; import solver.recorders.fine.AbstractFineEventRecorder; import solver.search.loop.AbstractSearchLoop; import solver.variables.EventType; import solver.variables.Variable; import solver.variables.delta.IDeltaMonitor; /** * <br/> * * @author Charles Prud'homme * @since 05/12/11 */ public class CoarseEventRecorder extends AbstractCoarseEventRecorder { int timestamp; // timestamp of the last clear call -- for lazy clear protected final Propagator propagator; int evtmask; // reference to events occuring -- inclusive OR over event mask public CoarseEventRecorder(Propagator propagator, Solver solver) { super(); this.propagator = propagator; this.evtmask = EventType.FULL_PROPAGATION.mask; // initialize with full propagation event propagator.addRecorder(this); } @Override public Propagator[] getPropagators() { return new Propagator[]{propagator}; } public void update(EventType e) { if ((e.mask & propagator.getPropagationConditions()) != 0) { // LoggerFactory.getLogger("solver").info("\t << {}", this.toString()); // 1. clear the structure if necessar if (LAZY) { if (timestamp - AbstractSearchLoop.timeStamp != 0) { this.evtmask = 0; timestamp = AbstractSearchLoop.timeStamp; } } // 2. store information concerning event if ((e.mask & evtmask) == 0) { // if the event has not been recorded yet (through strengthened event also). evtmask |= e.strengthened_mask; } // 3. schedule this if (!enqueued) { scheduler.schedule(this); } } } @Override public boolean execute() throws ContradictionException { if (!propagator.isActive()) { //promote event to top level event FULL_PROPAGATION evtmask |= EventType.FULL_PROPAGATION.strengthened_mask; propagator.setActive(); } if(propagator.getNbPendingER() > 0) { evtmask |= EventType.FULL_PROPAGATION.strengthened_mask; } if (evtmask > 0) { // LoggerFactory.getLogger("solver").info(">> {}", this.toString()); propagator.coarseERcalls++; int _evt = evtmask; evtmask = 0; propagator.propagate(_evt); } // if there is at least one fine event scheduled, if (propagator.getNbPendingER() > 0) { // So, the propagator will be localy consistent, // then remove every fine event attached to this propagator generated BEFORE calling this // if views schedule event, they will be considered after propagator.forEachFineEvent(virtExec); } return true; } @Override public void flush() { this.evtmask = 0; } @Override public String toString() { return propagator.toString(); } }
CoarseEvent fix bug see Issue #36 unfreeze all fine event (even those which are not scheduled)
solver/src/main/java/solver/recorders/coarse/CoarseEventRecorder.java
CoarseEvent fix bug
<ide><path>olver/src/main/java/solver/recorders/coarse/CoarseEventRecorder.java <ide> import solver.Solver; <ide> import solver.constraints.propagators.Propagator; <ide> import solver.exception.ContradictionException; <del>import solver.recorders.IEventRecorder; <del>import solver.recorders.fine.AbstractFineEventRecorder; <ide> import solver.search.loop.AbstractSearchLoop; <ide> import solver.variables.EventType; <del>import solver.variables.Variable; <del>import solver.variables.delta.IDeltaMonitor; <ide> <ide> /** <ide> * <br/> <ide> evtmask = 0; <ide> propagator.propagate(_evt); <ide> } <del> // if there is at least one fine event scheduled, <del> if (propagator.getNbPendingER() > 0) { <del> // So, the propagator will be localy consistent, <del> // then remove every fine event attached to this propagator generated BEFORE calling this <del> // if views schedule event, they will be considered after <del> propagator.forEachFineEvent(virtExec); <del> } <add> // unfreeze (and eventually unschedule) every fine event attached to this propagator <add> propagator.forEachFineEvent(virtExec); <ide> return true; <ide> } <ide>
Java
apache-2.0
08242084915d00f543d7d24220876d1a7f476630
0
Shashikanth-Huawei/bmp,maheshraju-Huawei/actn,opennetworkinglab/onos,gkatsikas/onos,lsinfo3/onos,Shashikanth-Huawei/bmp,y-higuchi/onos,kuujo/onos,donNewtonAlpha/onos,opennetworkinglab/onos,mengmoya/onos,oplinkoms/onos,gkatsikas/onos,Shashikanth-Huawei/bmp,donNewtonAlpha/onos,osinstom/onos,lsinfo3/onos,osinstom/onos,kuujo/onos,oplinkoms/onos,VinodKumarS-Huawei/ietf96yang,LorenzReinhart/ONOSnew,opennetworkinglab/onos,LorenzReinhart/ONOSnew,LorenzReinhart/ONOSnew,oplinkoms/onos,maheshraju-Huawei/actn,mengmoya/onos,Shashikanth-Huawei/bmp,VinodKumarS-Huawei/ietf96yang,kuujo/onos,opennetworkinglab/onos,y-higuchi/onos,mengmoya/onos,LorenzReinhart/ONOSnew,gkatsikas/onos,sonu283304/onos,gkatsikas/onos,osinstom/onos,oplinkoms/onos,sdnwiselab/onos,lsinfo3/onos,VinodKumarS-Huawei/ietf96yang,osinstom/onos,kuujo/onos,donNewtonAlpha/onos,y-higuchi/onos,gkatsikas/onos,sonu283304/onos,sdnwiselab/onos,oplinkoms/onos,gkatsikas/onos,lsinfo3/onos,kuujo/onos,opennetworkinglab/onos,sdnwiselab/onos,sdnwiselab/onos,opennetworkinglab/onos,oplinkoms/onos,maheshraju-Huawei/actn,sdnwiselab/onos,donNewtonAlpha/onos,y-higuchi/onos,maheshraju-Huawei/actn,donNewtonAlpha/onos,kuujo/onos,sonu283304/onos,mengmoya/onos,VinodKumarS-Huawei/ietf96yang,Shashikanth-Huawei/bmp,mengmoya/onos,sonu283304/onos,LorenzReinhart/ONOSnew,y-higuchi/onos,VinodKumarS-Huawei/ietf96yang,maheshraju-Huawei/actn,kuujo/onos,sdnwiselab/onos,osinstom/onos,oplinkoms/onos
/* * Copyright 2015 Open Networking Laboratory * * 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. */ package org.onosproject.dhcp.impl; import com.google.common.collect.ImmutableSet; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.Service; import org.onlab.packet.Ip4Address; import org.onlab.packet.MacAddress; import org.onlab.util.KryoNamespace; import org.onlab.util.Tools; import org.onosproject.dhcp.DhcpStore; import org.onosproject.dhcp.IpAssignment; import org.onosproject.net.HostId; import org.onosproject.store.serializers.KryoNamespaces; import org.onosproject.store.service.ConsistentMap; import org.onosproject.store.service.ConsistentMapException; import org.onosproject.store.service.DistributedSet; import org.onosproject.store.service.Serializer; import org.onosproject.store.service.StorageService; import org.onosproject.store.service.Versioned; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.Map; import java.util.List; import java.util.HashMap; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; /** * Manages the pool of available IP Addresses in the network and * Remembers the mapping between MAC ID and IP Addresses assigned. */ @Component(immediate = true) @Service public class DistributedDhcpStore implements DhcpStore { private final Logger log = LoggerFactory.getLogger(getClass()); @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected StorageService storageService; private ConsistentMap<HostId, IpAssignment> allocationMap; private DistributedSet<Ip4Address> freeIPPool; private static Ip4Address startIPRange; private static Ip4Address endIPRange; // Hardcoded values are default values. private static int timeoutForPendingAssignments = 60; private static final int MAX_RETRIES = 3; private static final int MAX_BACKOFF = 10; @Activate protected void activate() { allocationMap = storageService.<HostId, IpAssignment>consistentMapBuilder() .withName("onos-dhcp-assignedIP") .withSerializer(Serializer.using( new KryoNamespace.Builder() .register(KryoNamespaces.API) .register(IpAssignment.class, IpAssignment.AssignmentStatus.class, Date.class, long.class, Ip4Address.class) .build())) .build(); freeIPPool = storageService.<Ip4Address>setBuilder() .withName("onos-dhcp-freeIP") .withSerializer(Serializer.using(KryoNamespaces.API)) .build(); log.info("Started"); } @Deactivate protected void deactivate() { log.info("Stopped"); } @Override public Ip4Address suggestIP(HostId hostId, Ip4Address requestedIP) { IpAssignment assignmentInfo; if (allocationMap.containsKey(hostId)) { assignmentInfo = allocationMap.get(hostId).value(); IpAssignment.AssignmentStatus status = assignmentInfo.assignmentStatus(); Ip4Address ipAddr = assignmentInfo.ipAddress(); if (assignmentInfo.rangeNotEnforced()) { return assignmentInfo.ipAddress(); } else if (status == IpAssignment.AssignmentStatus.Option_Assigned || status == IpAssignment.AssignmentStatus.Option_Requested) { // Client has a currently Active Binding. if (ipWithinRange(ipAddr)) { return ipAddr; } } else if (status == IpAssignment.AssignmentStatus.Option_Expired) { // Client has a Released or Expired Binding. if (freeIPPool.contains(ipAddr)) { assignmentInfo = IpAssignment.builder() .ipAddress(ipAddr) .timestamp(new Date()) .leasePeriod(timeoutForPendingAssignments) .assignmentStatus(IpAssignment.AssignmentStatus.Option_Requested) .build(); if (freeIPPool.remove(ipAddr)) { allocationMap.put(hostId, assignmentInfo); return ipAddr; } } } } else if (requestedIP.toInt() != 0) { // Client has requested an IP. if (freeIPPool.contains(requestedIP)) { assignmentInfo = IpAssignment.builder() .ipAddress(requestedIP) .timestamp(new Date()) .leasePeriod(timeoutForPendingAssignments) .assignmentStatus(IpAssignment.AssignmentStatus.Option_Requested) .build(); if (freeIPPool.remove(requestedIP)) { allocationMap.put(hostId, assignmentInfo); return requestedIP; } } } // Allocate a new IP from the server's pool of available IP. Ip4Address nextIPAddr = fetchNextIP(); if (nextIPAddr != null) { assignmentInfo = IpAssignment.builder() .ipAddress(nextIPAddr) .timestamp(new Date()) .leasePeriod(timeoutForPendingAssignments) .assignmentStatus(IpAssignment.AssignmentStatus.Option_Requested) .build(); allocationMap.put(hostId, assignmentInfo); } return nextIPAddr; } @Override public boolean assignIP(HostId hostId, Ip4Address ipAddr, int leaseTime, boolean rangeNotEnforced, List<Ip4Address> addressList) { log.debug("Assign IP Called w/ Ip4Address: {}, HostId: {}", ipAddr.toString(), hostId.mac().toString()); AtomicBoolean assigned = Tools.retryable(() -> { AtomicBoolean result = new AtomicBoolean(false); allocationMap.compute( hostId, (h, existingAssignment) -> { IpAssignment assignment = existingAssignment; if (existingAssignment == null) { if (rangeNotEnforced) { assignment = IpAssignment.builder() .ipAddress(ipAddr) .timestamp(new Date()) .leasePeriod(leaseTime) .rangeNotEnforced(true) .assignmentStatus(IpAssignment.AssignmentStatus.Option_RangeNotEnforced) .subnetMask((Ip4Address) addressList.toArray()[0]) .dhcpServer((Ip4Address) addressList.toArray()[1]) .routerAddress((Ip4Address) addressList.toArray()[2]) .domainServer((Ip4Address) addressList.toArray()[3]) .build(); result.set(true); } else if (freeIPPool.remove(ipAddr)) { assignment = IpAssignment.builder() .ipAddress(ipAddr) .timestamp(new Date()) .leasePeriod(leaseTime) .assignmentStatus(IpAssignment.AssignmentStatus.Option_Assigned) .build(); result.set(true); } } else if (Objects.equals(existingAssignment.ipAddress(), ipAddr) && (existingAssignment.rangeNotEnforced() || ipWithinRange(ipAddr))) { switch (existingAssignment.assignmentStatus()) { case Option_RangeNotEnforced: assignment = IpAssignment.builder() .ipAddress(ipAddr) .timestamp(new Date()) .leasePeriod(leaseTime) .rangeNotEnforced(true) .assignmentStatus(IpAssignment.AssignmentStatus.Option_RangeNotEnforced) .subnetMask(existingAssignment.subnetMask()) .dhcpServer(existingAssignment.dhcpServer()) .routerAddress(existingAssignment.routerAddress()) .domainServer(existingAssignment.domainServer()) .build(); result.set(true); break; case Option_Assigned: case Option_Requested: assignment = IpAssignment.builder() .ipAddress(ipAddr) .timestamp(new Date()) .leasePeriod(leaseTime) .assignmentStatus(IpAssignment.AssignmentStatus.Option_Assigned) .build(); result.set(true); break; case Option_Expired: if (freeIPPool.remove(ipAddr)) { assignment = IpAssignment.builder() .ipAddress(ipAddr) .timestamp(new Date()) .leasePeriod(leaseTime) .assignmentStatus(IpAssignment.AssignmentStatus.Option_Assigned) .build(); result.set(true); } break; default: break; } } return assignment; }); return result; }, ConsistentMapException.class, MAX_RETRIES, MAX_BACKOFF).get(); return assigned.get(); } @Override public Ip4Address releaseIP(HostId hostId) { if (allocationMap.containsKey(hostId)) { IpAssignment newAssignment = IpAssignment.builder(allocationMap.get(hostId).value()) .assignmentStatus(IpAssignment.AssignmentStatus.Option_Expired) .build(); Ip4Address freeIP = newAssignment.ipAddress(); allocationMap.put(hostId, newAssignment); if (ipWithinRange(freeIP)) { freeIPPool.add(freeIP); } return freeIP; } return null; } @Override public void setDefaultTimeoutForPurge(int timeInSeconds) { timeoutForPendingAssignments = timeInSeconds; } @Override public Map<HostId, IpAssignment> listAssignedMapping() { Map<HostId, IpAssignment> validMapping = new HashMap<>(); IpAssignment assignment; for (Map.Entry<HostId, Versioned<IpAssignment>> entry: allocationMap.entrySet()) { assignment = entry.getValue().value(); if (assignment.assignmentStatus() == IpAssignment.AssignmentStatus.Option_Assigned || assignment.assignmentStatus() == IpAssignment.AssignmentStatus.Option_RangeNotEnforced) { validMapping.put(entry.getKey(), assignment); } } return validMapping; } @Override public Map<HostId, IpAssignment> listAllMapping() { Map<HostId, IpAssignment> validMapping = new HashMap<>(); for (Map.Entry<HostId, Versioned<IpAssignment>> entry: allocationMap.entrySet()) { validMapping.put(entry.getKey(), entry.getValue().value()); } return validMapping; } @Override public boolean assignStaticIP(MacAddress macID, Ip4Address ipAddr, boolean rangeNotEnforced, List<Ip4Address> addressList) { HostId host = HostId.hostId(macID); return assignIP(host, ipAddr, -1, rangeNotEnforced, addressList); } @Override public boolean removeStaticIP(MacAddress macID) { HostId host = HostId.hostId(macID); if (allocationMap.containsKey(host)) { IpAssignment assignment = allocationMap.get(host).value(); if (assignment.rangeNotEnforced()) { allocationMap.remove(host); return true; } Ip4Address freeIP = assignment.ipAddress(); if (assignment.leasePeriod() < 0) { allocationMap.remove(host); if (ipWithinRange(freeIP)) { freeIPPool.add(freeIP); } return true; } } return false; } @Override public Iterable<Ip4Address> getAvailableIPs() { return ImmutableSet.copyOf(freeIPPool); } @Override public void populateIPPoolfromRange(Ip4Address startIP, Ip4Address endIP) { // Clear all entries from previous range. allocationMap.clear(); freeIPPool.clear(); startIPRange = startIP; endIPRange = endIP; int lastIP = endIP.toInt(); Ip4Address nextIP; for (int loopCounter = startIP.toInt(); loopCounter <= lastIP; loopCounter++) { nextIP = Ip4Address.valueOf(loopCounter); freeIPPool.add(nextIP); } } @Override public IpAssignment getIpAssignmentFromAllocationMap(HostId hostId) { return allocationMap.get(hostId).value(); } /** * Fetches the next available IP from the free pool pf IPs. * * @return the next available IP address */ private Ip4Address fetchNextIP() { for (Ip4Address freeIP : freeIPPool) { if (freeIPPool.remove(freeIP)) { return freeIP; } } return null; } /** * Returns true if the given ip is within the range of available IPs. * * @param ip given ip address * @return true if within range, false otherwise */ private boolean ipWithinRange(Ip4Address ip) { if ((ip.toInt() >= startIPRange.toInt()) && (ip.toInt() <= endIPRange.toInt())) { return true; } return false; } }
apps/dhcp/app/src/main/java/org/onosproject/dhcp/impl/DistributedDhcpStore.java
/* * Copyright 2015 Open Networking Laboratory * * 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. */ package org.onosproject.dhcp.impl; import com.google.common.collect.ImmutableSet; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.Service; import org.onlab.packet.Ip4Address; import org.onlab.packet.MacAddress; import org.onlab.util.KryoNamespace; import org.onosproject.dhcp.DhcpStore; import org.onosproject.dhcp.IpAssignment; import org.onosproject.net.HostId; import org.onosproject.store.serializers.KryoNamespaces; import org.onosproject.store.service.ConsistentMap; import org.onosproject.store.service.DistributedSet; import org.onosproject.store.service.Serializer; import org.onosproject.store.service.StorageService; import org.onosproject.store.service.Versioned; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.Map; import java.util.List; import java.util.HashMap; import java.util.Objects; /** * Manages the pool of available IP Addresses in the network and * Remembers the mapping between MAC ID and IP Addresses assigned. */ @Component(immediate = true) @Service public class DistributedDhcpStore implements DhcpStore { private final Logger log = LoggerFactory.getLogger(getClass()); @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected StorageService storageService; private ConsistentMap<HostId, IpAssignment> allocationMap; private DistributedSet<Ip4Address> freeIPPool; private static Ip4Address startIPRange; private static Ip4Address endIPRange; // Hardcoded values are default values. private static int timeoutForPendingAssignments = 60; @Activate protected void activate() { allocationMap = storageService.<HostId, IpAssignment>consistentMapBuilder() .withName("onos-dhcp-assignedIP") .withSerializer(Serializer.using( new KryoNamespace.Builder() .register(KryoNamespaces.API) .register(IpAssignment.class, IpAssignment.AssignmentStatus.class, Date.class, long.class, Ip4Address.class) .build())) .build(); freeIPPool = storageService.<Ip4Address>setBuilder() .withName("onos-dhcp-freeIP") .withSerializer(Serializer.using(KryoNamespaces.API)) .build(); log.info("Started"); } @Deactivate protected void deactivate() { log.info("Stopped"); } @Override public Ip4Address suggestIP(HostId hostId, Ip4Address requestedIP) { IpAssignment assignmentInfo; if (allocationMap.containsKey(hostId)) { assignmentInfo = allocationMap.get(hostId).value(); IpAssignment.AssignmentStatus status = assignmentInfo.assignmentStatus(); Ip4Address ipAddr = assignmentInfo.ipAddress(); if (assignmentInfo.rangeNotEnforced()) { return assignmentInfo.ipAddress(); } else if (status == IpAssignment.AssignmentStatus.Option_Assigned || status == IpAssignment.AssignmentStatus.Option_Requested) { // Client has a currently Active Binding. if (ipWithinRange(ipAddr)) { return ipAddr; } } else if (status == IpAssignment.AssignmentStatus.Option_Expired) { // Client has a Released or Expired Binding. if (freeIPPool.contains(ipAddr)) { assignmentInfo = IpAssignment.builder() .ipAddress(ipAddr) .timestamp(new Date()) .leasePeriod(timeoutForPendingAssignments) .assignmentStatus(IpAssignment.AssignmentStatus.Option_Requested) .build(); if (freeIPPool.remove(ipAddr)) { allocationMap.put(hostId, assignmentInfo); return ipAddr; } } } } else if (requestedIP.toInt() != 0) { // Client has requested an IP. if (freeIPPool.contains(requestedIP)) { assignmentInfo = IpAssignment.builder() .ipAddress(requestedIP) .timestamp(new Date()) .leasePeriod(timeoutForPendingAssignments) .assignmentStatus(IpAssignment.AssignmentStatus.Option_Requested) .build(); if (freeIPPool.remove(requestedIP)) { allocationMap.put(hostId, assignmentInfo); return requestedIP; } } } // Allocate a new IP from the server's pool of available IP. Ip4Address nextIPAddr = fetchNextIP(); if (nextIPAddr != null) { assignmentInfo = IpAssignment.builder() .ipAddress(nextIPAddr) .timestamp(new Date()) .leasePeriod(timeoutForPendingAssignments) .assignmentStatus(IpAssignment.AssignmentStatus.Option_Requested) .build(); allocationMap.put(hostId, assignmentInfo); } return nextIPAddr; } @Override public boolean assignIP(HostId hostId, Ip4Address ipAddr, int leaseTime, boolean rangeNotEnforced, List<Ip4Address> addressList) { IpAssignment assignmentInfo; log.debug("Assign IP Called w/ Ip4Address: {}, HostId: {}", ipAddr.toString(), hostId.mac().toString()); if (allocationMap.containsKey(hostId)) { assignmentInfo = allocationMap.get(hostId).value(); IpAssignment.AssignmentStatus status = assignmentInfo.assignmentStatus(); if (Objects.equals(assignmentInfo.ipAddress(), ipAddr) && ipWithinRange(ipAddr)) { if (status == IpAssignment.AssignmentStatus.Option_Assigned || status == IpAssignment.AssignmentStatus.Option_Requested) { // Client has a currently active binding with the server. assignmentInfo = IpAssignment.builder() .ipAddress(ipAddr) .timestamp(new Date()) .leasePeriod(leaseTime) .assignmentStatus(IpAssignment.AssignmentStatus.Option_Assigned) .build(); allocationMap.put(hostId, assignmentInfo); return true; } else if (status == IpAssignment.AssignmentStatus.Option_Expired) { // Client has an expired binding with the server. if (freeIPPool.contains(ipAddr)) { assignmentInfo = IpAssignment.builder() .ipAddress(ipAddr) .timestamp(new Date()) .leasePeriod(leaseTime) .assignmentStatus(IpAssignment.AssignmentStatus.Option_Assigned) .build(); if (freeIPPool.remove(ipAddr)) { allocationMap.put(hostId, assignmentInfo); return true; } } } } } else if (freeIPPool.contains(ipAddr)) { assignmentInfo = IpAssignment.builder() .ipAddress(ipAddr) .timestamp(new Date()) .leasePeriod(leaseTime) .assignmentStatus(IpAssignment.AssignmentStatus.Option_Assigned) .build(); if (freeIPPool.remove(ipAddr)) { allocationMap.put(hostId, assignmentInfo); return true; } } else if (rangeNotEnforced) { assignmentInfo = IpAssignment.builder() .ipAddress(ipAddr) .timestamp(new Date()) .leasePeriod(leaseTime) .rangeNotEnforced(true) .assignmentStatus(IpAssignment.AssignmentStatus.Option_RangeNotEnforced) .subnetMask((Ip4Address) addressList.toArray()[0]) .dhcpServer((Ip4Address) addressList.toArray()[1]) .routerAddress((Ip4Address) addressList.toArray()[2]) .domainServer((Ip4Address) addressList.toArray()[3]) .build(); allocationMap.put(hostId, assignmentInfo); return true; } return false; } @Override public Ip4Address releaseIP(HostId hostId) { if (allocationMap.containsKey(hostId)) { IpAssignment newAssignment = IpAssignment.builder(allocationMap.get(hostId).value()) .assignmentStatus(IpAssignment.AssignmentStatus.Option_Expired) .build(); Ip4Address freeIP = newAssignment.ipAddress(); allocationMap.put(hostId, newAssignment); if (ipWithinRange(freeIP)) { freeIPPool.add(freeIP); } return freeIP; } return null; } @Override public void setDefaultTimeoutForPurge(int timeInSeconds) { timeoutForPendingAssignments = timeInSeconds; } @Override public Map<HostId, IpAssignment> listAssignedMapping() { Map<HostId, IpAssignment> validMapping = new HashMap<>(); IpAssignment assignment; for (Map.Entry<HostId, Versioned<IpAssignment>> entry: allocationMap.entrySet()) { assignment = entry.getValue().value(); if (assignment.assignmentStatus() == IpAssignment.AssignmentStatus.Option_Assigned || assignment.assignmentStatus() == IpAssignment.AssignmentStatus.Option_RangeNotEnforced) { validMapping.put(entry.getKey(), assignment); } } return validMapping; } @Override public Map<HostId, IpAssignment> listAllMapping() { Map<HostId, IpAssignment> validMapping = new HashMap<>(); for (Map.Entry<HostId, Versioned<IpAssignment>> entry: allocationMap.entrySet()) { validMapping.put(entry.getKey(), entry.getValue().value()); } return validMapping; } @Override public boolean assignStaticIP(MacAddress macID, Ip4Address ipAddr, boolean rangeNotEnforced, List<Ip4Address> addressList) { HostId host = HostId.hostId(macID); return assignIP(host, ipAddr, -1, rangeNotEnforced, addressList); } @Override public boolean removeStaticIP(MacAddress macID) { HostId host = HostId.hostId(macID); if (allocationMap.containsKey(host)) { IpAssignment assignment = allocationMap.get(host).value(); if (assignment.rangeNotEnforced()) { allocationMap.remove(host); return true; } Ip4Address freeIP = assignment.ipAddress(); if (assignment.leasePeriod() < 0) { allocationMap.remove(host); if (ipWithinRange(freeIP)) { freeIPPool.add(freeIP); } return true; } } return false; } @Override public Iterable<Ip4Address> getAvailableIPs() { return ImmutableSet.copyOf(freeIPPool); } @Override public void populateIPPoolfromRange(Ip4Address startIP, Ip4Address endIP) { // Clear all entries from previous range. allocationMap.clear(); freeIPPool.clear(); startIPRange = startIP; endIPRange = endIP; int lastIP = endIP.toInt(); Ip4Address nextIP; for (int loopCounter = startIP.toInt(); loopCounter <= lastIP; loopCounter++) { nextIP = Ip4Address.valueOf(loopCounter); freeIPPool.add(nextIP); } } @Override public IpAssignment getIpAssignmentFromAllocationMap(HostId hostId) { return allocationMap.get(hostId).value(); } /** * Fetches the next available IP from the free pool pf IPs. * * @return the next available IP address */ private Ip4Address fetchNextIP() { for (Ip4Address freeIP : freeIPPool) { if (freeIPPool.remove(freeIP)) { return freeIP; } } return null; } /** * Returns true if the given ip is within the range of available IPs. * * @param ip given ip address * @return true if within range, false otherwise */ private boolean ipWithinRange(Ip4Address ip) { if ((ip.toInt() >= startIPRange.toInt()) && (ip.toInt() <= endIPRange.toInt())) { return true; } return false; } }
ONOS-3549 Fixed NPE during renew for rangeNotEnforced IP Added renew case for IP assigned with rangeNotEnforced option. Addresses ONOS-3549 Change-Id: I6cb43f662332f0d461889d32659f1252ea436102
apps/dhcp/app/src/main/java/org/onosproject/dhcp/impl/DistributedDhcpStore.java
ONOS-3549 Fixed NPE during renew for rangeNotEnforced IP
<ide><path>pps/dhcp/app/src/main/java/org/onosproject/dhcp/impl/DistributedDhcpStore.java <ide> import org.onlab.packet.Ip4Address; <ide> import org.onlab.packet.MacAddress; <ide> import org.onlab.util.KryoNamespace; <add>import org.onlab.util.Tools; <ide> import org.onosproject.dhcp.DhcpStore; <ide> import org.onosproject.dhcp.IpAssignment; <ide> import org.onosproject.net.HostId; <ide> import org.onosproject.store.serializers.KryoNamespaces; <ide> import org.onosproject.store.service.ConsistentMap; <add>import org.onosproject.store.service.ConsistentMapException; <ide> import org.onosproject.store.service.DistributedSet; <ide> import org.onosproject.store.service.Serializer; <ide> import org.onosproject.store.service.StorageService; <ide> import java.util.List; <ide> import java.util.HashMap; <ide> import java.util.Objects; <add>import java.util.concurrent.atomic.AtomicBoolean; <ide> <ide> /** <ide> * Manages the pool of available IP Addresses in the network and <ide> // Hardcoded values are default values. <ide> <ide> private static int timeoutForPendingAssignments = 60; <add> private static final int MAX_RETRIES = 3; <add> private static final int MAX_BACKOFF = 10; <ide> <ide> @Activate <ide> protected void activate() { <ide> @Override <ide> public boolean assignIP(HostId hostId, Ip4Address ipAddr, int leaseTime, boolean rangeNotEnforced, <ide> List<Ip4Address> addressList) { <del> <del> IpAssignment assignmentInfo; <del> <ide> log.debug("Assign IP Called w/ Ip4Address: {}, HostId: {}", ipAddr.toString(), hostId.mac().toString()); <ide> <del> if (allocationMap.containsKey(hostId)) { <del> <del> assignmentInfo = allocationMap.get(hostId).value(); <del> IpAssignment.AssignmentStatus status = assignmentInfo.assignmentStatus(); <del> <del> if (Objects.equals(assignmentInfo.ipAddress(), ipAddr) && ipWithinRange(ipAddr)) { <del> <del> if (status == IpAssignment.AssignmentStatus.Option_Assigned || <del> status == IpAssignment.AssignmentStatus.Option_Requested) { <del> // Client has a currently active binding with the server. <del> assignmentInfo = IpAssignment.builder() <del> .ipAddress(ipAddr) <del> .timestamp(new Date()) <del> .leasePeriod(leaseTime) <del> .assignmentStatus(IpAssignment.AssignmentStatus.Option_Assigned) <del> .build(); <del> allocationMap.put(hostId, assignmentInfo); <del> return true; <del> } else if (status == IpAssignment.AssignmentStatus.Option_Expired) { <del> // Client has an expired binding with the server. <del> if (freeIPPool.contains(ipAddr)) { <del> assignmentInfo = IpAssignment.builder() <del> .ipAddress(ipAddr) <del> .timestamp(new Date()) <del> .leasePeriod(leaseTime) <del> .assignmentStatus(IpAssignment.AssignmentStatus.Option_Assigned) <del> .build(); <del> if (freeIPPool.remove(ipAddr)) { <del> allocationMap.put(hostId, assignmentInfo); <del> return true; <add> AtomicBoolean assigned = Tools.retryable(() -> { <add> AtomicBoolean result = new AtomicBoolean(false); <add> allocationMap.compute( <add> hostId, <add> (h, existingAssignment) -> { <add> IpAssignment assignment = existingAssignment; <add> if (existingAssignment == null) { <add> if (rangeNotEnforced) { <add> assignment = IpAssignment.builder() <add> .ipAddress(ipAddr) <add> .timestamp(new Date()) <add> .leasePeriod(leaseTime) <add> .rangeNotEnforced(true) <add> .assignmentStatus(IpAssignment.AssignmentStatus.Option_RangeNotEnforced) <add> .subnetMask((Ip4Address) addressList.toArray()[0]) <add> .dhcpServer((Ip4Address) addressList.toArray()[1]) <add> .routerAddress((Ip4Address) addressList.toArray()[2]) <add> .domainServer((Ip4Address) addressList.toArray()[3]) <add> .build(); <add> result.set(true); <add> } else if (freeIPPool.remove(ipAddr)) { <add> assignment = IpAssignment.builder() <add> .ipAddress(ipAddr) <add> .timestamp(new Date()) <add> .leasePeriod(leaseTime) <add> .assignmentStatus(IpAssignment.AssignmentStatus.Option_Assigned) <add> .build(); <add> result.set(true); <add> } <add> } else if (Objects.equals(existingAssignment.ipAddress(), ipAddr) && <add> (existingAssignment.rangeNotEnforced() || ipWithinRange(ipAddr))) { <add> switch (existingAssignment.assignmentStatus()) { <add> case Option_RangeNotEnforced: <add> assignment = IpAssignment.builder() <add> .ipAddress(ipAddr) <add> .timestamp(new Date()) <add> .leasePeriod(leaseTime) <add> .rangeNotEnforced(true) <add> .assignmentStatus(IpAssignment.AssignmentStatus.Option_RangeNotEnforced) <add> .subnetMask(existingAssignment.subnetMask()) <add> .dhcpServer(existingAssignment.dhcpServer()) <add> .routerAddress(existingAssignment.routerAddress()) <add> .domainServer(existingAssignment.domainServer()) <add> .build(); <add> result.set(true); <add> break; <add> case Option_Assigned: <add> case Option_Requested: <add> assignment = IpAssignment.builder() <add> .ipAddress(ipAddr) <add> .timestamp(new Date()) <add> .leasePeriod(leaseTime) <add> .assignmentStatus(IpAssignment.AssignmentStatus.Option_Assigned) <add> .build(); <add> result.set(true); <add> break; <add> case Option_Expired: <add> if (freeIPPool.remove(ipAddr)) { <add> assignment = IpAssignment.builder() <add> .ipAddress(ipAddr) <add> .timestamp(new Date()) <add> .leasePeriod(leaseTime) <add> .assignmentStatus(IpAssignment.AssignmentStatus.Option_Assigned) <add> .build(); <add> result.set(true); <add> } <add> break; <add> default: <add> break; <add> } <ide> } <del> } <del> } <del> } <del> } else if (freeIPPool.contains(ipAddr)) { <del> assignmentInfo = IpAssignment.builder() <del> .ipAddress(ipAddr) <del> .timestamp(new Date()) <del> .leasePeriod(leaseTime) <del> .assignmentStatus(IpAssignment.AssignmentStatus.Option_Assigned) <del> .build(); <del> if (freeIPPool.remove(ipAddr)) { <del> allocationMap.put(hostId, assignmentInfo); <del> return true; <del> } <del> } else if (rangeNotEnforced) { <del> assignmentInfo = IpAssignment.builder() <del> .ipAddress(ipAddr) <del> .timestamp(new Date()) <del> .leasePeriod(leaseTime) <del> .rangeNotEnforced(true) <del> .assignmentStatus(IpAssignment.AssignmentStatus.Option_RangeNotEnforced) <del> .subnetMask((Ip4Address) addressList.toArray()[0]) <del> .dhcpServer((Ip4Address) addressList.toArray()[1]) <del> .routerAddress((Ip4Address) addressList.toArray()[2]) <del> .domainServer((Ip4Address) addressList.toArray()[3]) <del> .build(); <del> allocationMap.put(hostId, assignmentInfo); <del> return true; <del> } <del> return false; <add> return assignment; <add> }); <add> return result; <add> }, ConsistentMapException.class, MAX_RETRIES, MAX_BACKOFF).get(); <add> <add> return assigned.get(); <ide> } <ide> <ide> @Override
JavaScript
apache-2.0
885178abf0c93c99fabc4625536afd6dd4b62fc3
0
usc-isi-i2/Web-Karma,usc-isi-i2/Web-Karma,sylvanmist/Web-Karma,usc-isi-i2/Web-Karma,sylvanmist/Web-Karma,rpiotti/Web-Karma,rpiotti/Web-Karma,usc-isi-i2/Web-Karma,sylvanmist/Web-Karma,rpiotti/Web-Karma,sylvanmist/Web-Karma,usc-isi-i2/Web-Karma,rpiotti/Web-Karma,rpiotti/Web-Karma,sylvanmist/Web-Karma
/** * @author Shubham Gupta */ function parse(data) { $.workspaceGlobalInformation = { "id" : data["workspaceId"] } $.each(data["elements"], function(i, element){ /* Update the worksheet list */ if(element["updateType"] == "WorksheetListUpdate") { $.each(element["worksheets"], function(j, worksheet){ // If worksheet doesn't exist yet if($("div#" + worksheet["worksheetId"]).length == 0){ var mainDiv = $("<div>").attr("id", worksheet["worksheetId"]).addClass("Worksheet"); mainDiv.data("isCollapsed", worksheet["isCollapsed"]); // Div for adding title of that worksheet var titleDiv = $("<div>").addClass("WorksheetTitleDiv ui-corner-top"); titleDiv.append($("<div>") .text(worksheet["title"]) .addClass("tableTitleTextDiv") ) .append($("<div>") .addClass("WorksheetOptionsButtonDiv") .attr("id", "optionsButton" + worksheet["worksheetId"]) .data("worksheetId", worksheet["worksheetId"]) .click(openWorksheetOptions) ) .append($("<div>") .addClass("showHideWorkSheet") .attr("id", "hideShow"+worksheet["worksheetId"]) .append( $("<img>").addClass("minimizeWorksheetImg") .attr("src", "../images/blue-box-minimize.png") .data("state", "open") ) .click(function() { $("#" + worksheet["worksheetId"] + "TableDiv").toggle(400); $("#topLevelpagerOptions" + worksheet["worksheetId"]).toggle(400); // Change the corners titleDiv.toggleClass("ui-corner-top"); titleDiv.toggleClass("ui-corner-all"); // Change the icon var img = $(this).find("img"); if(img.data("state") == "open") { img.attr("src", "../images/orange-maximize.png") img.data("state", "close") } else { img.attr("src", "../images/blue-box-minimize.png") img.data("state", "open") } }) ); mainDiv.append(titleDiv); $("#optionsButton" + worksheet["worksheetId"], mainDiv).button({ icons: { primary: 'ui-icon-triangle-1-s' }, text: false }); $("#optionsButton" + worksheet["worksheetId"], mainDiv).mouseleave(function(){ $("#WorksheetOptionsDiv").hide(); }); // Add the table (if it does not exists) var tableDiv = $("<div>").attr("id", worksheet["worksheetId"] + "TableDiv").addClass("TableDiv"); var table = $("<table>").attr("id", worksheet["worksheetId"]).addClass("WorksheetTable"); tableDiv.append(table); mainDiv.append(tableDiv); // Add the row options var pagerOptionsDiv = $("<div>").addClass("topLevelpagerOptions pager ui-corner-bottom") .attr("id","topLevelpagerOptions" + worksheet["worksheetId"]) .append($("<div>").addClass("rowCountDiv") .append($("<span>") .text("Show: ")) .append($("<a>").addClass("pagerResizeLink") //.attr("id", "pagerResizeLink10"+ worksheet["worksheetId"]) .addClass("pagerSizeSelected") .data("rowCount",10) .data("vWorksheetId", worksheet["worksheetId"]) .attr("href", "JavaScript:void(0);") .text("10 ") .bind("click", handlePagerResize) ) .append($("<a>").addClass("pagerResizeLink") //.attr("id", "pagerResizeLink20"+ worksheet["worksheetId"]) .data("rowCount",20) .data("vWorksheetId", worksheet["worksheetId"]) .attr("href", "JavaScript:void(0);") .text("20 ") .bind("click", handlePagerResize) ) .append($("<a>").addClass("pagerResizeLink") //.attr("id", "pagerResizeLink50"+ worksheet["worksheetId"]) .data("rowCount",50) .data("vWorksheetId", worksheet["worksheetId"]) .attr("href", "JavaScript:void(0);") .text("50 ") .bind("click", handlePagerResize) ) .append($("<span>") .text(" records")) ) .append($("<div>").addClass("prevNextRowsDiv") .append($("<a>").attr("id", "previousLink" + worksheet["worksheetId"]) .attr("href", "JavaScript:void(0);") .data("direction", "showPrevious") .data("vWorksheetId", worksheet["worksheetId"]) .addClass("inactiveLink") .text("Previous ") .bind("click", handlePrevNextLink) ) .append($("<span>").attr("id","previousNextText" + worksheet["worksheetId"]) .addClass("previousNextText") ) .append($("<a>").attr("id", "nextLink" + worksheet["worksheetId"]) .attr("href", "JavaScript:void(0);#") .data("direction", "showNext") .data("vWorksheetId", worksheet["worksheetId"]) .addClass("inactiveLink") .text(" Next") .bind("click", handlePrevNextLink) ) ); mainDiv.append(pagerOptionsDiv); $("#tablesWorkspace").append(mainDiv).append("<br>"); } else { } }); } /* Update the worksheet column headers */ else if(element["updateType"] == "WorksheetHeadersUpdate") { // var table = $("table#" + element["worksheetId"]); // // Check if the table has column header row. if not, then create one. // var theadRow = $("thead tr", table); // if(theadRow.length == 0) { // var thead = $("<thead>").addClass("tableHeader"); // theadRow = $("<tr>").addClass("tableHeaderRow"); // thead.append(theadRow); // table.append(thead); // } // // // Loop for the headers // $.each(element["columns"], function(j, column){ // // Check if the column header with same Id exists // if($("#" + column["path"], table).length == 0) { // theadRow.append( // $("<td>").append( // $("<div>").addClass("tableHeaderDiv") // .append($("<span>").text(column["columnNameFull"]) // ) // ) // .mouseenter(config) // .mouseleave(configOut) // ); // } // // }); } else if(element["updateType"] == "WorksheetHierarchicalHeadersUpdate") { var table = $("table#" + element["worksheetId"]); var thead = $("thead", table); if(thead.length == 0) { thead = $("<thead>").addClass("tableHeader"); table.append(thead); } $("tr.ColumnHeaders", thead).remove(); $.each(element["rows"], function(index, row) { var trTag = $("<tr>").addClass("ColumnHeaders"); $.each(row["cells"], function(index2, cell){ var tdTag = $("<td>"); // Add the background information tdTag.addClass("fill" + cell["fillId"]); // Add the left border tdTag.addClass("leftBorder" + cell["leftBorder"].replace(":", "")); // Add the right border tdTag.addClass("rightBorder" + cell["rightBorder"].replace(":", "")); // Add the top border tdTag.addClass("topBorder" + cell["topBorder"].replace(":", "")); if(cell["cellType"] == "border") { tdTag.addClass("bordertdTags") } else if (cell["cellType"] == "heading") { tdTag.addClass("columnHeadingCell") // Add the colspan tdTag.attr("colspan", cell["colSpan"]); // Store the node ID tdTag.attr("id", cell["contentCell"]["id"]); //Add the name tdTag.append($("<div>").addClass("ColumnHeadingNameDiv") .text(cell["contentCell"]["label"]) //.mouseenter(config) //.mouseleave(configOut) ); // tdTag.text(cell["columnNameFull"]) // .mouseenter(config) // .mouseleave(configOut); } else if(cell["cellType"] == "headingPadding") { // Add the colspan tdTag.attr("colspan", cell["colSpan"]); } tdTag.data("jsonElement", cell).hover(showConsoleInfo); trTag.append(tdTag); }); thead.append(trTag); }); } else if(element["updateType"] == "AlignmentHeadersUpdate") { var table = $("table#" + element["worksheetId"]); table.data("alignmentId", element["alignmentId"]); var thead = $("thead", table); $("tr", thead).remove(); var columnHeaders = $("tr", thead).clone(true); $("tr", thead).remove(); $.each(element["rows"], function(index, row) { var trTag = $("<tr>").addClass("AlignmentRow"); $.each(row["cells"], function(index2, cell){ var tdTag = $("<td>"); // Add the background information tdTag.addClass("fill" + cell["fillId"]); // Add the left border tdTag.addClass("leftBorder" + cell["leftBorder"].replace(":", "")); // Add the right border tdTag.addClass("rightBorder" + cell["rightBorder"].replace(":", "")); // Add the top border tdTag.addClass("topBorder" + cell["topBorder"].replace(":", "")); if(cell["cellType"] == "border") { tdTag.addClass("bordertdTags") } else if (cell["cellType"] == "heading") { tdTag.addClass("columnHeadingCell") // Add the colspan tdTag.attr("colspan", cell["colSpan"]); // Store the node ID //tdTag.attr("id", cell["hNodeId"]); // Add the label var labelDiv = $("<div>").addClass("AlignmentHeadingNameDiv") .text(cell["contentCell"]["label"]); // Add the pencil if(cell["contentCell"]["parentLinkId"] != null) { // Special case for the key attribute which has the link and node named BlankNode if(cell["contentCell"]["parentLinkLabel"] == "BlankNode") { tdTag.append($("<span>").text("key").addClass("KeyAtrributeLabel")); } else { var pencilDiv = $("<div>").addClass("AlignmentLinkConfigDiv") .append($("<img>").attr("src","../images/configure-icon.png")) .append($("<span>").text(cell["contentCell"]["parentLinkLabel"])) .click(showAlternativeParents); tdTag.append(pencilDiv); // Special case for data properties if(cell["contentCell"]["parentLinkLabel"] != cell["contentCell"]["label"]) tdTag.append(labelDiv); } } else { labelDiv.prepend($("<img>").attr("src","../images/configure-icon.png")).click(showAlternativeParents); tdTag.append(labelDiv); } // tdTag.text(cell["columnNameFull"]) // .mouseenter(config) // .mouseleave(configOut); } else if(cell["cellType"] == "headingPadding") { // Add the colspan tdTag.attr("colspan", cell["colSpan"]); } tdTag.data("jsonElement", cell).hover(showConsoleInfo); trTag.append(tdTag); }); thead.append(trTag); }); thead.append(columnHeaders); } else if(element["updateType"] == "WorksheetHierarchicalDataUpdate") { var table = $("table#" + element["worksheetId"]); // Check if the table has tbody for data rows. if not, then create one. var tbody = $("tbody", table); if(tbody.length == 0) { tbody = $("<tbody>"); table.append(tbody); } // Mark the rows that need to be deleted later if($("tr", tbody).length != 0) { $("tr", tbody).addClass("deleteMe"); } $.each(element["rows"], function(index, row) { var trTag = $("<tr>"); trTag.addClass(row["rowType"]); $.each(row["rowCells"], function(index2, cell){ var tdTag = $("<td>"); // Split the attr attribute of the row cell var attr = cell["attr"]; var attrVals = attr.split(":"); var cssClass = attrVals[2]; tdTag.addClass("data"+cssClass); // Populate the td with value if the cell is of content type if(attrVals[0] == "c") { //console.log(cell["value"]); if(cell["value"] == null) console.log("Value not found in a content cell!"); //tdTag.text(cell["value"]); if(cell["value"] != null){ var valueToShow = cell["value"]; // if(cell["value"].length > 25) { // valueToShow = cell["value"].substring(0,25) + "..."; // } else { // valueToShow = cell["value"]; // } tdTag.append($("<div>").addClass("cellValue") .text(valueToShow)) //.mouseenter(showTableCellMenu) //.mouseleave(hideTableCellMenu)) .attr('id', cell["nodeId"]); } } tdTag.addClass(attrVals[0]); // Add the left border if(attrVals[3] != "_") { if(attrVals[3] == "o") { tdTag.addClass("leftBorderouter" + cssClass); } else if (attrVals[3] == "i") { tdTag.addClass("leftBorderinner" + cssClass); } else { console.log("Unknown border type detected!"); } } // Add the right border if(attrVals[4] != "_") { if(attrVals[4] == "o") { tdTag.addClass("rightBorderouter" + cssClass); } else if (attrVals[4] == "i") { tdTag.addClass("rightBorderinner" + cssClass); } else { console.log("Unknown border type detected!"); } } // Add the top border if(attrVals[5] != "_") { if(attrVals[5] == "o") { tdTag.addClass("topBorderouter" + cssClass); } else if (attrVals[5] == "i") { tdTag.addClass("topBorderinner" + cssClass); } else { console.log("Unknown border type detected!"); } } // Add the bottom border if(attrVals[6] != "_") { if(attrVals[6] == "o") { tdTag.addClass("bottomBorderouter" + cssClass); } else if (attrVals[6] == "i") { tdTag.addClass("bottomBorderinner" + cssClass); } else { console.log("Unknown border type detected!"); } } tdTag.data("jsonElement", cell).hover(showConsoleInfo); trTag.append(tdTag); }); table.append(trTag); }); // Delete the old rows $("tr.deleteMe", tbody).remove(); // Bottom anchor for scrolling page if($("div#" + element["worksheetId"] + "bottomAnchor").length == 0) $("div#" + element["worksheetId"]).append($("<div>").attr("id", element["worksheetId"] + "bottomAnchor")); } /* Update the worksheet data */ // if(element["updateType"] == "WorksheetDataUpdate") { // var table = $("table#" + element["worksheetId"]); // // Check if the table has tbody for data rows. if not, then create one. // var tbody = $("tbody", table); // if(tbody.length == 0) { // tbody = $("<tbody>"); // table.append(tbody); // } // // Mark the rows that need to be deleted later // if($("tr", tbody).length != 0) { // $("tr", tbody).addClass("deleteMe"); // } // // // Add the rows // $.each(element["rows"], function(j, row) { // var rowTag = $("<tr>"); // // Adding each cell // $.each(row["cells"], function(k, cell) { // if (!cell["isDummy"]) { // var tdTag = $("<td>").addClass("noLineBelow") // .addClass(cell["tableCssTag"]) // .addClass("editable") // //.text(cell["value"]) // .append($("<div>").addClass("cellValue") // //.text(cell["value"]) // .mouseenter(showTableCellMenu) // .mouseleave(hideTableCellMenu) // ) // .attr('id', cell["nodeId"]) // .attr('path', cell["path"]) // .data('jsonElement', cell) // .hover(showConsoleInfo) // ; // // Mark the edited cells // if(cell["status"] == "E") // $(tdTag).children("div.cellValue").addClass("editedValue") // // if(cell["value"].length > 20) { // var valueToShow = cell["value"].substring(0,20); // $(tdTag).children("div.cellValue").text(valueToShow + "..."); // $(tdTag).data("fullValue", cell["value"]); // $(tdTag).addClass("expandValueCell"); // } else { // $(tdTag).children("div.cellValue").text(cell["value"]); // } // // // Check if the cell has pager associated with it // if(cell["pager"]) { // $(tdTag).append( // $("<div>").addClass("nestedTableLastRow") // .append($("<img>").attr("src","../images/pagerBar.png")) // .mouseenter(showNestedTablePager) // .mouseleave(hideNestedTablePager) // .data("pagerElem", cell["pager"]) // ) // // // Check if the nested table pager has been created already for the existing worksheet. // // We maintain one nested table pager for each worksheet // if($("#nestedTablePager" + element["worksheetId"]).length == 0){ // // Create a nested table pager by cloning the pager object present for the whole table // var nestedTablePager = $("div#topLevelpagerOptions" + element["worksheetId"]).clone(true, true) // .addClass("ui-corner-all").removeClass("topLevelpagerOptions"); // nestedTablePager.addClass("nestedTablePager pager") // .attr("id", "nestedTablePager" + element["worksheetId"]) // .mouseenter(function() { // $(this).show(); // }) // .mouseleave(function(){ // $(this).hide(); // }); // $($("a", nestedTablePager)[3]).data("vWorksheetId", element["worksheetId"]); // $($("a", nestedTablePager)[4]).data("vWorksheetId", element["worksheetId"]); // // Change the row count values to 5, 10, 20 // $($("a.pagerResizeLink", nestedTablePager)[0]).text("5 ") // .data("rowCount", 5).data("vWorksheetId", element["worksheetId"]); // $($("a.pagerResizeLink", nestedTablePager)[1]).text("10 ") // .data("rowCount", 10).data("vWorksheetId", element["worksheetId"]); // $($("a.pagerResizeLink", nestedTablePager)[2]).text("20 ") // .data("rowCount", 20).data("vWorksheetId", element["worksheetId"]); // // //table.append(nestedTablePager); // $("body").append(nestedTablePager); // nestedTablePager.hide(); // } else { // changePagerOptions(cell["pager"], $("#nestedTablePager" + element["worksheetId"])); // } // } // // rowTag.append(tdTag); // } else if (cell["isDummy"]) { // rowTag.append( // $("<td>").addClass("noLineAboveAndBelow") // .addClass(cell["tableCssTag"]) // ); // } else { // }; // }); // tbody.append(rowTag); // }); // // // Delete the old rows // $("tr.deleteMe", tbody).remove(); // // /* Update the pager information */ // changePagerOptions(element["pager"], $("div#topLevelpagerOptions" + element["worksheetId"])); // } // /* Update the commands list */ else if(element["updateType"] == "HistoryAddCommandUpdate") { var commandDiv = $("<div>") .addClass("CommandDiv undo-state " + element.command.commandType) .attr("id", element.command.commandId) .css({"position":"relative"}) .append($("<div>") .text(element.command.title + ": " + element.command.description) ) .append($("<div>") .addClass("iconDiv") .append($("<img>") .attr("src", "../images/edit_undo.png") ) .bind('click', clickUndoButton) ) .hover( // hover in function commandDivHoverIn, // hover out function commandDivHoverOut); if(element.command["commandType"] == "notUndoable") $("div.iconDiv",commandDiv).remove(); var commandHistoryDiv = $("div#commandHistory"); // Remove the commands on redo stack $(".redo-state").remove(); commandHistoryDiv.append(commandDiv); } else if(element["updateType"] == "HistoryUpdate") { $("div#commandHistory div.CommandDiv").remove(); $.each(element["commands"], function(index, command){ var commandDiv = $("<div>") .addClass("CommandDiv " + command.commandType) .attr("id", command.commandId) .css({"position":"relative"}) .append($("<div>") .text(command.title + ": " + command.description) ) .append($("<div>") .addClass("iconDiv") .bind('click', clickUndoButton) ) .hover( // hover in function commandDivHoverIn, // hover out function commandDivHoverOut); if(command["commandType"] == "notUndoable") $("div.iconDiv",commandDiv).remove(); if(command.historyType == "redo") { $(commandDiv).addClass("redo-state"); $("div.iconDiv", commandDiv).append($("<img>") .attr("src", "../images/edit_redo.png")); } else { $(commandDiv).addClass("undo-state"); $("div.iconDiv", commandDiv).append($("<img>") .attr("src", "../images/edit_undo.png")); } $("div#commandHistory").append(commandDiv); }); } /* Update the cell value */ else if(element["updateType"] == "NodeChangedUpdate") { var tdTag = $("td#" + element.nodeId); if(element.newValue.length > 20) { var valueToShow = element.newValue.substring(0,20); $(tdTag).children("div.cellValue").text(valueToShow + "..."); $(tdTag).data("fullValue", element.newValue); $(tdTag).addClass("expandValueCell"); } else { if($(tdTag).hasClass("expandValueCell")){ $(tdTag).removeClass("expandValueCell"); $.removeData($(tdTag), "fullValue"); } $(tdTag).children("div.cellValue").text(element.newValue); } //tdTag.children("div.cellValue").text(element.newValue); if(element.newStatus == "E"){ tdTag.children("div.cellValue").addClass("editedValue"); } else { tdTag.children("div.cellValue").removeClass("editedValue"); } } else if(element["updateType"] == "NewImportDatabaseTableCommandUpdate") { $("#DatabaseImportDiv").data("commandId", element["commandId"]); } else if(element["updateType"] == "SemanticTypesUpdate") { var table = $("table#" + element["worksheetId"]); $.each(element["Types"], function(index, type) { var tdTag = $("td.columnHeadingCell#" + type["HNodeId"], table); // Remove any existing semantic type div $("br", tdTag).remove(); $("div.semanticTypeDiv", tdTag).remove(); var semDiv = $("<div>").addClass("semanticTypeDiv " + type["ConfidenceLevel"]+"ConfidenceLevel"); if(type["FullType"] == ""){ semDiv.text("Unassigned").addClass("LowConfidenceLevel") .data("hNodeId", type["HNodeId"]) .data("fullType", "Unassigned"); if(type["FullCRFModel"] != null) semDiv.data("crfInfo",type["FullCRFModel"]); } else if (type["ConfidenceLevel"] == "Low") { semDiv.text("Unassigned").addClass("LowConfidenceLevel") .data("hNodeId", type["HNodeId"]) .data("fullType", "Unassigned") .data("crfInfo",type["FullCRFModel"]); } else { if(type["Domain"] != null && type["Domain"] != ""){ var typeItalicSpan = $("<span>").addClass("italic").text(type["DisplayLabel"]); // semDiv.text(type["DisplayDomainLabel"] + ":" + type["DisplayLabel"]); semDiv.text(type["DisplayDomainLabel"] + ":").append(typeItalicSpan); } else semDiv.text(type["DisplayLabel"]); semDiv.data("crfInfo",type["FullCRFModel"]) .data("hNodeId", type["HNodeId"]) .data("fullType", type["FullType"]) .data("domain", type["Domain"]) .data("origin", type["Origin"]); } //semDiv.hover(showSemanticTypeInfo, hideSemanticTypeInfo); semDiv.click(changeSemanticType); tdTag.append(semDiv); }); } else if(element["updateType"] == "ImportOntologyCommand") { if(element["Import"]) alert("Ontology successfully imported."); else alert("Ontology import failed! Please try again."); } }); } function showSemanticTypeInfo() { // var crfData = $(this).data("crfInfo"); // var table = $("div#ColumnCRFModelInfoBox table"); // $("tr", table).remove(); // // $.each(crfData["Labels"], function(index, label) { // var trTag = $("<tr>"); // trTag.append($("<td>").text(label["Type"])) // .append($("<td>").text(label["Probability"])); // }); } function hideSemanticTypeInfo() { } function showConsoleInfo() { if (console && console.log) { console.clear(); var elem = $(this).data("jsonElement"); $.each(elem, function(key, value){ if(key == "pager"){ console.log("Pager Information:") $.each(value, function(key2,value2){ console.log(key2 +" : " + value2) }) console.log("Pager Information Finished.") } else console.log(key + " : " + value); }) } } function showNestedTablePager() { // Get the parent table var tableId = $(this).parents("table").attr("id"); var nestedTablePager = $("#nestedTablePager" + tableId); var pagerElem = $(this).data("pagerElem"); changePagerOptions(pagerElem, nestedTablePager); nestedTablePager.css({"position":"absolute", "top":$(this).offset().top + 10, "left": $(this).offset().left + $(this).width()/2 - nestedTablePager.width()/2}).show(); } function changePagerOptions(pagerJSONElement, pagerDOMElement) { // Store the table Id information $(pagerDOMElement).data("tableId", pagerJSONElement["tableId"]); // Change the ___ of ___ rows information var totalRows = pagerJSONElement["numRecordsShown"] + pagerJSONElement["numRecordsBefore"] + pagerJSONElement["numRecordsAfter"]; var currentRowInfo = "" + (pagerJSONElement["numRecordsBefore"] +1) + " - " + (pagerJSONElement["numRecordsShown"] + pagerJSONElement["numRecordsBefore"]); $("span.previousNextText", pagerDOMElement).text(currentRowInfo + " of " + totalRows); // Make the Previous link active/inactive as required if(pagerJSONElement["numRecordsBefore"] != 0) { var previousLink = $("a", pagerDOMElement)[3]; if($(previousLink).hasClass("inactiveLink")) $(previousLink).removeClass("inactiveLink").addClass("activeLink"); } else { if($(previousLink).hasClass("activeLink")) $(previousLink).removeClass("activeLink").addClass("inactiveLink"); } // Make the Next link active/inactive as required if(pagerJSONElement["numRecordsAfter"] != 0){ var nextLink = $("a", pagerDOMElement)[4]; if($(nextLink).hasClass("inactiveLink")) $(nextLink).removeClass("inactiveLink").addClass("activeLink"); } else { if($(nextLink).hasClass("activeLink")) $(nextLink).removeClass("activeLink").addClass("inactiveLink"); } // Select the correct pager resize links $.each($("a.pagerResizeLink", pagerDOMElement), function(index, link) { if($(link).data("rowCount") == pagerJSONElement["desiredNumRecordsShown"]){ $(link).addClass("pagerSizeSelected"); } else { $(link).removeClass("pagerSizeSelected"); } }); return true; } function hideNestedTablePager() { // Get the parent table var table = $(this).parents("table"); var nestedTablePager = $("#nestedTablePager" + table.attr("id")); nestedTablePager.hide(); } function showTableCellMenu() { // Get the parent table $("div#tableCellToolBarMenu").data("parentCellId", $(this).parents("td").attr("id")); if($(this).parents("td").hasClass("expandValueCell")){ $("#viewValueButton").show(); $("#tableCellMenutriangle").css({"margin-left" : "32px"}); $("div#tableCellToolBarMenu").css({"width": "105px"}); } else { $("#viewValueButton").hide(); $("#tableCellMenutriangle").css({"margin-left" : "10px"}); $("div#tableCellToolBarMenu").css({"width": "48px"}); } $("div#tableCellToolBarMenu").css({"position":"absolute", "top":$(this).offset().top + 10, "left": $(this).offset().left + $(this).width()/2 - $("div#tableCellToolBarMenu").width()/2}).show(); } function hideTableCellMenu() { $("div#tableCellToolBarMenu").hide(); } function config(event) { $("#toolBarMenu").data("parent", $(this)); $("#toolBarMenu").css({"position":"absolute","width":"165px", "top":$(this).offset().top + $(this).height(), //"left":event.clientX-150 , "left": $(this).offset().left + $(this).width()/2 - $("#toolBarMenu").width()/2}).show(); //"top": event.clientY-10}).show(); }; function configOut() { $("#toolBarMenu").hide(); };
src/main/webapp/js/ServerResponseObjectParsing.js
/** * @author Shubham Gupta */ function parse(data) { $.workspaceGlobalInformation = { "id" : data["workspaceId"] } $.each(data["elements"], function(i, element){ /* Update the worksheet list */ if(element["updateType"] == "WorksheetListUpdate") { $.each(element["worksheets"], function(j, worksheet){ // If worksheet doesn't exist yet if($("div#" + worksheet["worksheetId"]).length == 0){ var mainDiv = $("<div>").attr("id", worksheet["worksheetId"]).addClass("Worksheet"); mainDiv.data("isCollapsed", worksheet["isCollapsed"]); // Div for adding title of that worksheet var titleDiv = $("<div>").addClass("WorksheetTitleDiv ui-corner-top"); titleDiv.append($("<div>") .text(worksheet["title"]) .addClass("tableTitleTextDiv") ) .append($("<div>") .addClass("WorksheetOptionsButtonDiv") .attr("id", "optionsButton" + worksheet["worksheetId"]) .data("worksheetId", worksheet["worksheetId"]) .click(openWorksheetOptions) ) .append($("<div>") .addClass("showHideWorkSheet") .attr("id", "hideShow"+worksheet["worksheetId"]) .append( $("<img>").addClass("minimizeWorksheetImg") .attr("src", "../images/blue-box-minimize.png") .data("state", "open") ) .click(function() { $("#" + worksheet["worksheetId"] + "TableDiv").toggle(400); $("#topLevelpagerOptions" + worksheet["worksheetId"]).toggle(400); // Change the corners titleDiv.toggleClass("ui-corner-top"); titleDiv.toggleClass("ui-corner-all"); // Change the icon var img = $(this).find("img"); if(img.data("state") == "open") { img.attr("src", "../images/orange-maximize.png") img.data("state", "close") } else { img.attr("src", "../images/blue-box-minimize.png") img.data("state", "open") } }) ); mainDiv.append(titleDiv); $("#optionsButton" + worksheet["worksheetId"], mainDiv).button({ icons: { primary: 'ui-icon-triangle-1-s' }, text: false }); $("#optionsButton" + worksheet["worksheetId"], mainDiv).mouseleave(function(){ $("#WorksheetOptionsDiv").hide(); }); // Add the table (if it does not exists) var tableDiv = $("<div>").attr("id", worksheet["worksheetId"] + "TableDiv").addClass("TableDiv"); var table = $("<table>").attr("id", worksheet["worksheetId"]).addClass("WorksheetTable"); tableDiv.append(table); mainDiv.append(tableDiv); // Add the row options var pagerOptionsDiv = $("<div>").addClass("topLevelpagerOptions pager ui-corner-bottom") .attr("id","topLevelpagerOptions" + worksheet["worksheetId"]) .append($("<div>").addClass("rowCountDiv") .append($("<span>") .text("Show: ")) .append($("<a>").addClass("pagerResizeLink") //.attr("id", "pagerResizeLink10"+ worksheet["worksheetId"]) .addClass("pagerSizeSelected") .data("rowCount",10) .data("vWorksheetId", worksheet["worksheetId"]) .attr("href", "JavaScript:void(0);") .text("10 ") .bind("click", handlePagerResize) ) .append($("<a>").addClass("pagerResizeLink") //.attr("id", "pagerResizeLink20"+ worksheet["worksheetId"]) .data("rowCount",20) .data("vWorksheetId", worksheet["worksheetId"]) .attr("href", "JavaScript:void(0);") .text("20 ") .bind("click", handlePagerResize) ) .append($("<a>").addClass("pagerResizeLink") //.attr("id", "pagerResizeLink50"+ worksheet["worksheetId"]) .data("rowCount",50) .data("vWorksheetId", worksheet["worksheetId"]) .attr("href", "JavaScript:void(0);") .text("50 ") .bind("click", handlePagerResize) ) .append($("<span>") .text(" records")) ) .append($("<div>").addClass("prevNextRowsDiv") .append($("<a>").attr("id", "previousLink" + worksheet["worksheetId"]) .attr("href", "JavaScript:void(0);") .data("direction", "showPrevious") .data("vWorksheetId", worksheet["worksheetId"]) .addClass("inactiveLink") .text("Previous ") .bind("click", handlePrevNextLink) ) .append($("<span>").attr("id","previousNextText" + worksheet["worksheetId"]) .addClass("previousNextText") ) .append($("<a>").attr("id", "nextLink" + worksheet["worksheetId"]) .attr("href", "JavaScript:void(0);#") .data("direction", "showNext") .data("vWorksheetId", worksheet["worksheetId"]) .addClass("inactiveLink") .text(" Next") .bind("click", handlePrevNextLink) ) ); mainDiv.append(pagerOptionsDiv); $("#tablesWorkspace").append(mainDiv).append("<br>"); } else { } }); } /* Update the worksheet column headers */ else if(element["updateType"] == "WorksheetHeadersUpdate") { // var table = $("table#" + element["worksheetId"]); // // Check if the table has column header row. if not, then create one. // var theadRow = $("thead tr", table); // if(theadRow.length == 0) { // var thead = $("<thead>").addClass("tableHeader"); // theadRow = $("<tr>").addClass("tableHeaderRow"); // thead.append(theadRow); // table.append(thead); // } // // // Loop for the headers // $.each(element["columns"], function(j, column){ // // Check if the column header with same Id exists // if($("#" + column["path"], table).length == 0) { // theadRow.append( // $("<td>").append( // $("<div>").addClass("tableHeaderDiv") // .append($("<span>").text(column["columnNameFull"]) // ) // ) // .mouseenter(config) // .mouseleave(configOut) // ); // } // // }); } else if(element["updateType"] == "WorksheetHierarchicalHeadersUpdate") { var table = $("table#" + element["worksheetId"]); var thead = $("thead", table); if(thead.length == 0) { thead = $("<thead>").addClass("tableHeader"); table.append(thead); } $("tr.ColumnHeaders", thead).remove(); $.each(element["rows"], function(index, row) { var trTag = $("<tr>").addClass("ColumnHeaders"); $.each(row["cells"], function(index2, cell){ var tdTag = $("<td>"); // Add the background information tdTag.addClass("fill" + cell["fillId"]); // Add the left border tdTag.addClass("leftBorder" + cell["leftBorder"].replace(":", "")); // Add the right border tdTag.addClass("rightBorder" + cell["rightBorder"].replace(":", "")); // Add the top border tdTag.addClass("topBorder" + cell["topBorder"].replace(":", "")); if(cell["cellType"] == "border") { tdTag.addClass("bordertdTags") } else if (cell["cellType"] == "heading") { tdTag.addClass("columnHeadingCell") // Add the colspan tdTag.attr("colspan", cell["colSpan"]); // Store the node ID tdTag.attr("id", cell["contentCell"]["id"]); //Add the name tdTag.append($("<div>").addClass("ColumnHeadingNameDiv") .text(cell["contentCell"]["label"]) //.mouseenter(config) //.mouseleave(configOut) ); // tdTag.text(cell["columnNameFull"]) // .mouseenter(config) // .mouseleave(configOut); } else if(cell["cellType"] == "headingPadding") { // Add the colspan tdTag.attr("colspan", cell["colSpan"]); } tdTag.data("jsonElement", cell).hover(showConsoleInfo); trTag.append(tdTag); }); thead.append(trTag); }); } else if(element["updateType"] == "AlignmentHeadersUpdate") { var table = $("table#" + element["worksheetId"]); table.data("alignmentId", element["alignmentId"]); var thead = $("thead", table); $("tr", thead).remove(); var columnHeaders = $("tr", thead).clone(true); $("tr", thead).remove(); $.each(element["rows"], function(index, row) { var trTag = $("<tr>").addClass("AlignmentRow"); $.each(row["cells"], function(index2, cell){ var tdTag = $("<td>"); // Add the background information tdTag.addClass("fill" + cell["fillId"]); // Add the left border tdTag.addClass("leftBorder" + cell["leftBorder"].replace(":", "")); // Add the right border tdTag.addClass("rightBorder" + cell["rightBorder"].replace(":", "")); // Add the top border tdTag.addClass("topBorder" + cell["topBorder"].replace(":", "")); if(cell["cellType"] == "border") { tdTag.addClass("bordertdTags") } else if (cell["cellType"] == "heading") { tdTag.addClass("columnHeadingCell") // Add the colspan tdTag.attr("colspan", cell["colSpan"]); // Store the node ID //tdTag.attr("id", cell["hNodeId"]); // Add the label var labelDiv = $("<div>").addClass("AlignmentHeadingNameDiv") .text(cell["contentCell"]["label"]); // Add the pencil if(cell["contentCell"]["parentLinkId"] != null) { // Special case for the key attribute which has the link and node named BlankNode if(cell["contentCell"]["parentLinkLabel"] == "BlankNode") { tdTag.append($("<span>").text("key").addClass("KeyAtrributeLabel")); } else { var pencilDiv = $("<div>").addClass("AlignmentLinkConfigDiv") .append($("<img>").attr("src","../images/configure-icon.png")) .append($("<span>").text(cell["contentCell"]["parentLinkLabel"])) .click(showAlternativeParents); tdTag.append(pencilDiv); // Special case for data properties if(cell["contentCell"]["parentLinkLabel"] != cell["contentCell"]["label"]) tdTag.append(labelDiv); } } else { labelDiv.prepend($("<img>").attr("src","../images/configure-icon.png")).click(showAlternativeParents); tdTag.append(labelDiv); } // tdTag.text(cell["columnNameFull"]) // .mouseenter(config) // .mouseleave(configOut); } else if(cell["cellType"] == "headingPadding") { // Add the colspan tdTag.attr("colspan", cell["colSpan"]); } tdTag.data("jsonElement", cell).hover(showConsoleInfo); trTag.append(tdTag); }); thead.append(trTag); }); thead.append(columnHeaders); } else if(element["updateType"] == "WorksheetHierarchicalDataUpdate") { var table = $("table#" + element["worksheetId"]); // Check if the table has tbody for data rows. if not, then create one. var tbody = $("tbody", table); if(tbody.length == 0) { tbody = $("<tbody>"); table.append(tbody); } // Mark the rows that need to be deleted later if($("tr", tbody).length != 0) { $("tr", tbody).addClass("deleteMe"); } $.each(element["rows"], function(index, row) { var trTag = $("<tr>"); trTag.addClass(row["rowType"]); $.each(row["rowCells"], function(index2, cell){ var tdTag = $("<td>"); // Split the attr attribute of the row cell var attr = cell["attr"]; var attrVals = attr.split(":"); var cssClass = attrVals[2]; tdTag.addClass("data"+cssClass); // Populate the td with value if the cell is of content type if(attrVals[0] == "c") { //console.log(cell["value"]); if(cell["value"] == null) console.log("Value not found in a content cell!"); //tdTag.text(cell["value"]); if(cell["value"] != null){ var valueToShow = ""; if(cell["value"].length > 25) { valueToShow = cell["value"].substring(0,25) + "..."; } else { valueToShow = cell["value"]; } tdTag.append($("<div>").addClass("cellValue") .text(valueToShow)) //.mouseenter(showTableCellMenu) //.mouseleave(hideTableCellMenu)) .attr('id', cell["nodeId"]); } } tdTag.addClass(attrVals[0]); // Add the left border if(attrVals[3] != "_") { if(attrVals[3] == "o") { tdTag.addClass("leftBorderouter" + cssClass); } else if (attrVals[3] == "i") { tdTag.addClass("leftBorderinner" + cssClass); } else { console.log("Unknown border type detected!"); } } // Add the right border if(attrVals[4] != "_") { if(attrVals[4] == "o") { tdTag.addClass("rightBorderouter" + cssClass); } else if (attrVals[4] == "i") { tdTag.addClass("rightBorderinner" + cssClass); } else { console.log("Unknown border type detected!"); } } // Add the top border if(attrVals[5] != "_") { if(attrVals[5] == "o") { tdTag.addClass("topBorderouter" + cssClass); } else if (attrVals[5] == "i") { tdTag.addClass("topBorderinner" + cssClass); } else { console.log("Unknown border type detected!"); } } // Add the bottom border if(attrVals[6] != "_") { if(attrVals[6] == "o") { tdTag.addClass("bottomBorderouter" + cssClass); } else if (attrVals[6] == "i") { tdTag.addClass("bottomBorderinner" + cssClass); } else { console.log("Unknown border type detected!"); } } tdTag.data("jsonElement", cell).hover(showConsoleInfo); trTag.append(tdTag); }); table.append(trTag); }); // Delete the old rows $("tr.deleteMe", tbody).remove(); // Bottom anchor for scrolling page if($("div#" + element["worksheetId"] + "bottomAnchor").length == 0) $("div#" + element["worksheetId"]).append($("<div>").attr("id", element["worksheetId"] + "bottomAnchor")); } /* Update the worksheet data */ // if(element["updateType"] == "WorksheetDataUpdate") { // var table = $("table#" + element["worksheetId"]); // // Check if the table has tbody for data rows. if not, then create one. // var tbody = $("tbody", table); // if(tbody.length == 0) { // tbody = $("<tbody>"); // table.append(tbody); // } // // Mark the rows that need to be deleted later // if($("tr", tbody).length != 0) { // $("tr", tbody).addClass("deleteMe"); // } // // // Add the rows // $.each(element["rows"], function(j, row) { // var rowTag = $("<tr>"); // // Adding each cell // $.each(row["cells"], function(k, cell) { // if (!cell["isDummy"]) { // var tdTag = $("<td>").addClass("noLineBelow") // .addClass(cell["tableCssTag"]) // .addClass("editable") // //.text(cell["value"]) // .append($("<div>").addClass("cellValue") // //.text(cell["value"]) // .mouseenter(showTableCellMenu) // .mouseleave(hideTableCellMenu) // ) // .attr('id', cell["nodeId"]) // .attr('path', cell["path"]) // .data('jsonElement', cell) // .hover(showConsoleInfo) // ; // // Mark the edited cells // if(cell["status"] == "E") // $(tdTag).children("div.cellValue").addClass("editedValue") // // if(cell["value"].length > 20) { // var valueToShow = cell["value"].substring(0,20); // $(tdTag).children("div.cellValue").text(valueToShow + "..."); // $(tdTag).data("fullValue", cell["value"]); // $(tdTag).addClass("expandValueCell"); // } else { // $(tdTag).children("div.cellValue").text(cell["value"]); // } // // // Check if the cell has pager associated with it // if(cell["pager"]) { // $(tdTag).append( // $("<div>").addClass("nestedTableLastRow") // .append($("<img>").attr("src","../images/pagerBar.png")) // .mouseenter(showNestedTablePager) // .mouseleave(hideNestedTablePager) // .data("pagerElem", cell["pager"]) // ) // // // Check if the nested table pager has been created already for the existing worksheet. // // We maintain one nested table pager for each worksheet // if($("#nestedTablePager" + element["worksheetId"]).length == 0){ // // Create a nested table pager by cloning the pager object present for the whole table // var nestedTablePager = $("div#topLevelpagerOptions" + element["worksheetId"]).clone(true, true) // .addClass("ui-corner-all").removeClass("topLevelpagerOptions"); // nestedTablePager.addClass("nestedTablePager pager") // .attr("id", "nestedTablePager" + element["worksheetId"]) // .mouseenter(function() { // $(this).show(); // }) // .mouseleave(function(){ // $(this).hide(); // }); // $($("a", nestedTablePager)[3]).data("vWorksheetId", element["worksheetId"]); // $($("a", nestedTablePager)[4]).data("vWorksheetId", element["worksheetId"]); // // Change the row count values to 5, 10, 20 // $($("a.pagerResizeLink", nestedTablePager)[0]).text("5 ") // .data("rowCount", 5).data("vWorksheetId", element["worksheetId"]); // $($("a.pagerResizeLink", nestedTablePager)[1]).text("10 ") // .data("rowCount", 10).data("vWorksheetId", element["worksheetId"]); // $($("a.pagerResizeLink", nestedTablePager)[2]).text("20 ") // .data("rowCount", 20).data("vWorksheetId", element["worksheetId"]); // // //table.append(nestedTablePager); // $("body").append(nestedTablePager); // nestedTablePager.hide(); // } else { // changePagerOptions(cell["pager"], $("#nestedTablePager" + element["worksheetId"])); // } // } // // rowTag.append(tdTag); // } else if (cell["isDummy"]) { // rowTag.append( // $("<td>").addClass("noLineAboveAndBelow") // .addClass(cell["tableCssTag"]) // ); // } else { // }; // }); // tbody.append(rowTag); // }); // // // Delete the old rows // $("tr.deleteMe", tbody).remove(); // // /* Update the pager information */ // changePagerOptions(element["pager"], $("div#topLevelpagerOptions" + element["worksheetId"])); // } // /* Update the commands list */ else if(element["updateType"] == "HistoryAddCommandUpdate") { var commandDiv = $("<div>") .addClass("CommandDiv undo-state " + element.command.commandType) .attr("id", element.command.commandId) .css({"position":"relative"}) .append($("<div>") .text(element.command.title + ": " + element.command.description) ) .append($("<div>") .addClass("iconDiv") .append($("<img>") .attr("src", "../images/edit_undo.png") ) .bind('click', clickUndoButton) ) .hover( // hover in function commandDivHoverIn, // hover out function commandDivHoverOut); if(element.command["commandType"] == "notUndoable") $("div.iconDiv",commandDiv).remove(); var commandHistoryDiv = $("div#commandHistory"); // Remove the commands on redo stack $(".redo-state").remove(); commandHistoryDiv.append(commandDiv); } else if(element["updateType"] == "HistoryUpdate") { $("div#commandHistory div.CommandDiv").remove(); $.each(element["commands"], function(index, command){ var commandDiv = $("<div>") .addClass("CommandDiv " + command.commandType) .attr("id", command.commandId) .css({"position":"relative"}) .append($("<div>") .text(command.title + ": " + command.description) ) .append($("<div>") .addClass("iconDiv") .bind('click', clickUndoButton) ) .hover( // hover in function commandDivHoverIn, // hover out function commandDivHoverOut); if(command["commandType"] == "notUndoable") $("div.iconDiv",commandDiv).remove(); if(command.historyType == "redo") { $(commandDiv).addClass("redo-state"); $("div.iconDiv", commandDiv).append($("<img>") .attr("src", "../images/edit_redo.png")); } else { $(commandDiv).addClass("undo-state"); $("div.iconDiv", commandDiv).append($("<img>") .attr("src", "../images/edit_undo.png")); } $("div#commandHistory").append(commandDiv); }); } /* Update the cell value */ else if(element["updateType"] == "NodeChangedUpdate") { var tdTag = $("td#" + element.nodeId); if(element.newValue.length > 20) { var valueToShow = element.newValue.substring(0,20); $(tdTag).children("div.cellValue").text(valueToShow + "..."); $(tdTag).data("fullValue", element.newValue); $(tdTag).addClass("expandValueCell"); } else { if($(tdTag).hasClass("expandValueCell")){ $(tdTag).removeClass("expandValueCell"); $.removeData($(tdTag), "fullValue"); } $(tdTag).children("div.cellValue").text(element.newValue); } //tdTag.children("div.cellValue").text(element.newValue); if(element.newStatus == "E"){ tdTag.children("div.cellValue").addClass("editedValue"); } else { tdTag.children("div.cellValue").removeClass("editedValue"); } } else if(element["updateType"] == "NewImportDatabaseTableCommandUpdate") { $("#DatabaseImportDiv").data("commandId", element["commandId"]); } else if(element["updateType"] == "SemanticTypesUpdate") { var table = $("table#" + element["worksheetId"]); $.each(element["Types"], function(index, type) { var tdTag = $("td.columnHeadingCell#" + type["HNodeId"], table); // Remove any existing semantic type div $("br", tdTag).remove(); $("div.semanticTypeDiv", tdTag).remove(); var semDiv = $("<div>").addClass("semanticTypeDiv " + type["ConfidenceLevel"]+"ConfidenceLevel"); if(type["FullType"] == ""){ semDiv.text("Unassigned").addClass("LowConfidenceLevel") .data("hNodeId", type["HNodeId"]) .data("fullType", "Unassigned"); if(type["FullCRFModel"] != null) semDiv.data("crfInfo",type["FullCRFModel"]); } else if (type["ConfidenceLevel"] == "Low") { semDiv.text("Unassigned").addClass("LowConfidenceLevel") .data("hNodeId", type["HNodeId"]) .data("fullType", "Unassigned") .data("crfInfo",type["FullCRFModel"]); } else { if(type["Domain"] != null && type["Domain"] != ""){ var typeItalicSpan = $("<span>").addClass("italic").text(type["DisplayLabel"]); // semDiv.text(type["DisplayDomainLabel"] + ":" + type["DisplayLabel"]); semDiv.text(type["DisplayDomainLabel"] + ":").append(typeItalicSpan); } else semDiv.text(type["DisplayLabel"]); semDiv.data("crfInfo",type["FullCRFModel"]) .data("hNodeId", type["HNodeId"]) .data("fullType", type["FullType"]) .data("domain", type["Domain"]) .data("origin", type["Origin"]); } //semDiv.hover(showSemanticTypeInfo, hideSemanticTypeInfo); semDiv.click(changeSemanticType); tdTag.append(semDiv); }); } else if(element["updateType"] == "ImportOntologyCommand") { if(element["Import"]) alert("Ontology successfully imported."); else alert("Ontology import failed! Please try again."); } }); } function showSemanticTypeInfo() { // var crfData = $(this).data("crfInfo"); // var table = $("div#ColumnCRFModelInfoBox table"); // $("tr", table).remove(); // // $.each(crfData["Labels"], function(index, label) { // var trTag = $("<tr>"); // trTag.append($("<td>").text(label["Type"])) // .append($("<td>").text(label["Probability"])); // }); } function hideSemanticTypeInfo() { } function showConsoleInfo() { if (console && console.log) { console.clear(); var elem = $(this).data("jsonElement"); $.each(elem, function(key, value){ if(key == "pager"){ console.log("Pager Information:") $.each(value, function(key2,value2){ console.log(key2 +" : " + value2) }) console.log("Pager Information Finished.") } else console.log(key + " : " + value); }) } } function showNestedTablePager() { // Get the parent table var tableId = $(this).parents("table").attr("id"); var nestedTablePager = $("#nestedTablePager" + tableId); var pagerElem = $(this).data("pagerElem"); changePagerOptions(pagerElem, nestedTablePager); nestedTablePager.css({"position":"absolute", "top":$(this).offset().top + 10, "left": $(this).offset().left + $(this).width()/2 - nestedTablePager.width()/2}).show(); } function changePagerOptions(pagerJSONElement, pagerDOMElement) { // Store the table Id information $(pagerDOMElement).data("tableId", pagerJSONElement["tableId"]); // Change the ___ of ___ rows information var totalRows = pagerJSONElement["numRecordsShown"] + pagerJSONElement["numRecordsBefore"] + pagerJSONElement["numRecordsAfter"]; var currentRowInfo = "" + (pagerJSONElement["numRecordsBefore"] +1) + " - " + (pagerJSONElement["numRecordsShown"] + pagerJSONElement["numRecordsBefore"]); $("span.previousNextText", pagerDOMElement).text(currentRowInfo + " of " + totalRows); // Make the Previous link active/inactive as required if(pagerJSONElement["numRecordsBefore"] != 0) { var previousLink = $("a", pagerDOMElement)[3]; if($(previousLink).hasClass("inactiveLink")) $(previousLink).removeClass("inactiveLink").addClass("activeLink"); } else { if($(previousLink).hasClass("activeLink")) $(previousLink).removeClass("activeLink").addClass("inactiveLink"); } // Make the Next link active/inactive as required if(pagerJSONElement["numRecordsAfter"] != 0){ var nextLink = $("a", pagerDOMElement)[4]; if($(nextLink).hasClass("inactiveLink")) $(nextLink).removeClass("inactiveLink").addClass("activeLink"); } else { if($(nextLink).hasClass("activeLink")) $(nextLink).removeClass("activeLink").addClass("inactiveLink"); } // Select the correct pager resize links $.each($("a.pagerResizeLink", pagerDOMElement), function(index, link) { if($(link).data("rowCount") == pagerJSONElement["desiredNumRecordsShown"]){ $(link).addClass("pagerSizeSelected"); } else { $(link).removeClass("pagerSizeSelected"); } }); return true; } function hideNestedTablePager() { // Get the parent table var table = $(this).parents("table"); var nestedTablePager = $("#nestedTablePager" + table.attr("id")); nestedTablePager.hide(); } function showTableCellMenu() { // Get the parent table $("div#tableCellToolBarMenu").data("parentCellId", $(this).parents("td").attr("id")); if($(this).parents("td").hasClass("expandValueCell")){ $("#viewValueButton").show(); $("#tableCellMenutriangle").css({"margin-left" : "32px"}); $("div#tableCellToolBarMenu").css({"width": "105px"}); } else { $("#viewValueButton").hide(); $("#tableCellMenutriangle").css({"margin-left" : "10px"}); $("div#tableCellToolBarMenu").css({"width": "48px"}); } $("div#tableCellToolBarMenu").css({"position":"absolute", "top":$(this).offset().top + 10, "left": $(this).offset().left + $(this).width()/2 - $("div#tableCellToolBarMenu").width()/2}).show(); } function hideTableCellMenu() { $("div#tableCellToolBarMenu").hide(); } function config(event) { $("#toolBarMenu").data("parent", $(this)); $("#toolBarMenu").css({"position":"absolute","width":"165px", "top":$(this).offset().top + $(this).height(), //"left":event.clientX-150 , "left": $(this).offset().left + $(this).width()/2 - $("#toolBarMenu").width()/2}).show(); //"top": event.clientY-10}).show(); }; function configOut() { $("#toolBarMenu").hide(); };
Table shows the full value in the cell
src/main/webapp/js/ServerResponseObjectParsing.js
Table shows the full value in the cell
<ide><path>rc/main/webapp/js/ServerResponseObjectParsing.js <ide> console.log("Value not found in a content cell!"); <ide> //tdTag.text(cell["value"]); <ide> if(cell["value"] != null){ <del> var valueToShow = ""; <del> if(cell["value"].length > 25) { <del> valueToShow = cell["value"].substring(0,25) + "..."; <del> } else { <del> valueToShow = cell["value"]; <del> } <add> var valueToShow = cell["value"]; <add> // if(cell["value"].length > 25) { <add> // valueToShow = cell["value"].substring(0,25) + "..."; <add> // } else { <add> // valueToShow = cell["value"]; <add> // } <ide> <ide> tdTag.append($("<div>").addClass("cellValue") <ide> .text(valueToShow))
Java
apache-2.0
4a418acdb0bb0743dc840d172071b461173fc985
0
kantega/Flyt-cms,kantega/Flyt-cms,kantega/Flyt-cms
/* * Copyright 2009 Kantega AS * * 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. */ package no.kantega.commons.util; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static org.apache.commons.lang.StringUtils.isNotBlank; public class URLHelper { public static String getRootURL(HttpServletRequest request) { return getServerURL(request) + request.getContextPath() + "/"; } public static String getCurrentUrl(HttpServletRequest request) { String url = request.getRequestURI(); String originalUri = (String)request.getAttribute("javax.servlet.error.request_uri"); if (originalUri != null) { // Call via 404 url = originalUri; } return url; } public static String getServerURL(HttpServletRequest request){ int port = request.getServerPort(); String portStr = ""; if (port != 80 && port != 443) { portStr = ":" + port; } return request.getScheme() + "://" + request.getServerName() + portStr; } public static String getUrlWithHttps(HttpServletRequest request){ StringBuilder sb = new StringBuilder(getServerURL(request).replaceFirst("http:", "https:")); sb.append(request.getRequestURI()); String queryString = request.getQueryString(); if(isNotBlank(queryString)){ sb.append("?").append(queryString); } return sb.toString(); } /** * Returns the actual URL requested by the client * @param request * @return String URL requested by client */ public static String getRequestedUrl(HttpServletRequest request){ StringBuilder urlBuilder = new StringBuilder(); // protocol urlBuilder.append(request.getScheme()); urlBuilder.append("://"); // server/domain urlBuilder.append(request.getServerName()); int serverPort = request.getServerPort(); // Ports if(serverPort != 80 && serverPort != 443){ urlBuilder.append(":"); urlBuilder.append(serverPort); } // URI urlBuilder.append(request.getAttribute("javax.servlet.forward.request_uri")); // Query params if (request.getQueryString() != null && !request.getQueryString().isEmpty()){ urlBuilder.append("?").append(request.getQueryString()); } return urlBuilder.toString(); } }
modules/commons/src/java/no/kantega/commons/util/URLHelper.java
/* * Copyright 2009 Kantega AS * * 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. */ package no.kantega.commons.util; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static org.apache.commons.lang.StringUtils.isNotBlank; public class URLHelper { public static String getRootURL(HttpServletRequest request) { return getServerURL(request) + request.getContextPath() + "/"; } public static String getCurrentUrl(HttpServletRequest request) { String url = request.getRequestURI(); String originalUri = (String)request.getAttribute("javax.servlet.error.request_uri"); if (originalUri != null) { // Call via 404 url = originalUri; } return url; } public static String getServerURL(HttpServletRequest request){ int port = request.getServerPort(); String portStr = ""; if (port != 80 && port != 443) { portStr = ":" + port; } return request.getScheme() + "://" + request.getServerName() + portStr; } public static String getUrlWithHttps(HttpServletRequest request){ StringBuilder sb = new StringBuilder(getServerURL(request).replaceFirst("http:", "https:")); sb.append(request.getRequestURI()); String queryString = request.getQueryString(); if(isNotBlank(queryString)){ sb.append("?").append(queryString); } return sb.toString(); } public static String getRequestedUrl(HttpServletRequest request){ StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(request.getScheme()); urlBuilder.append("://"); urlBuilder.append(request.getServerName()); int serverPort = request.getServerPort(); if(serverPort != 80 && serverPort != 443){ urlBuilder.append(":"); urlBuilder.append(serverPort); } urlBuilder.append(request.getAttribute("javax.servlet.forward.request_uri")); if (request.getQueryString() != null && !request.getQueryString().isEmpty()){ urlBuilder.append("?").append(request.getQueryString()); } return urlBuilder.toString(); } }
AP-1915 :: URLHelper should return actual client requested URL git-svn-id: 8def386c603904b39326d3fc08add479b8279298@5795 fd808399-8219-4f14-9d4c-37719d9ec93d
modules/commons/src/java/no/kantega/commons/util/URLHelper.java
AP-1915 :: URLHelper should return actual client requested URL
<ide><path>odules/commons/src/java/no/kantega/commons/util/URLHelper.java <ide> return sb.toString(); <ide> } <ide> <add> /** <add> * Returns the actual URL requested by the client <add> * @param request <add> * @return String URL requested by client <add> */ <ide> public static String getRequestedUrl(HttpServletRequest request){ <ide> StringBuilder urlBuilder = new StringBuilder(); <add> <add> // protocol <ide> urlBuilder.append(request.getScheme()); <ide> urlBuilder.append("://"); <add> <add> // server/domain <ide> urlBuilder.append(request.getServerName()); <ide> int serverPort = request.getServerPort(); <add> <add> // Ports <ide> if(serverPort != 80 && serverPort != 443){ <ide> urlBuilder.append(":"); <ide> urlBuilder.append(serverPort); <ide> } <add> <add> // URI <ide> urlBuilder.append(request.getAttribute("javax.servlet.forward.request_uri")); <add> <add> // Query params <ide> if (request.getQueryString() != null && !request.getQueryString().isEmpty()){ <ide> urlBuilder.append("?").append(request.getQueryString()); <ide> } <ide> <del> <ide> return urlBuilder.toString(); <ide> } <ide> }
Java
mit
ff629f7243998484c88b9b08fd0d955cf8af6673
0
SmyDev/OSBot-FlaxSpinner
package com.smy.flax.tasks; import com.smy.flax.Task; import org.osbot.rs07.api.model.Player; import org.osbot.rs07.api.model.RS2Object; import org.osbot.rs07.script.MethodProvider; import java.util.List; public class AntiBanTask extends Task { private long lastOutOfScreen; public AntiBanTask(MethodProvider api) { super(api); } @Override public boolean canProcess() { return true; } @Override public void process() throws InterruptedException { int rnd = MethodProvider.random(0,2); int luck = MethodProvider.random(0, 100); if(luck < 5){ switch(rnd){ case 0: /*Move mouse out of screen*/ api.mouse.moveOutsideScreen(); break; case 1: /*Hovers and right clicks on random players*/ List<RS2Object> objectList = api.objects.getAll(); int right = MethodProvider.random(0,objectList.size()); RS2Object obj = objectList.get(right); if(obj != null){ if(obj.isVisible()){ obj.interact("Examine"); } else { api.getCamera().toEntity(obj); obj.hover(); MethodProvider.sleep(MethodProvider.random(400,900)); api.getMouse().click(true); MethodProvider.sleep(MethodProvider.random(1000,2000)); if(MethodProvider.random(0, 100) < 25){ int rx = MethodProvider.random(1, api.getBot().getCanvas().getX()); int ry = MethodProvider.random(1, api.getBot().getCanvas().getY()); api.mouse.move(rx, ry); } } } break; case 2: /*Crafting skill check*/ break; } } } }
src/com/smy/flax/tasks/AntiBanTask.java
package com.smy.flax.tasks; import com.smy.flax.Task; import org.osbot.rs07.api.model.Player; import org.osbot.rs07.script.MethodProvider; import java.util.List; public class AntiBanTask extends Task { private long lastOutOfScreen; public AntiBanTask(MethodProvider api) { super(api); } @Override public boolean canProcess() { return true; } @Override public void process() throws InterruptedException { int rnd = MethodProvider.random(0,2); int luck = MethodProvider.random(0, 100); if(luck < 25){ switch(rnd){ case 0: /*Move mouse out of screen*/ api.mouse.moveOutsideScreen(); break; case 1: /*Hovers and right clicks on random players*/ List<Player> playerList = api.players.getAll(); int right = MethodProvider.random(0,playerList.size()); Player p = playerList.get(right); if(p != null){ if(p.isVisible()){ api.getMouse().click(p.getX(),p.getY(), true); } else { api.getCamera().toEntity(p); api.getMouse().click(p.getX(),p.getY(), true); } } break; } } } }
Changed left click anti pattern, it will scan for objects.
src/com/smy/flax/tasks/AntiBanTask.java
Changed left click anti pattern, it will scan for objects.
<ide><path>rc/com/smy/flax/tasks/AntiBanTask.java <ide> <ide> import com.smy.flax.Task; <ide> import org.osbot.rs07.api.model.Player; <add>import org.osbot.rs07.api.model.RS2Object; <ide> import org.osbot.rs07.script.MethodProvider; <ide> <ide> import java.util.List; <ide> int rnd = MethodProvider.random(0,2); <ide> int luck = MethodProvider.random(0, 100); <ide> <del> if(luck < 25){ <add> if(luck < 5){ <ide> switch(rnd){ <ide> case 0: /*Move mouse out of screen*/ <ide> api.mouse.moveOutsideScreen(); <ide> break; <ide> case 1: /*Hovers and right clicks on random players*/ <del> List<Player> playerList = api.players.getAll(); <del> int right = MethodProvider.random(0,playerList.size()); <add> List<RS2Object> objectList = api.objects.getAll(); <add> int right = MethodProvider.random(0,objectList.size()); <ide> <del> Player p = playerList.get(right); <add> RS2Object obj = objectList.get(right); <ide> <del> if(p != null){ <del> if(p.isVisible()){ <del> api.getMouse().click(p.getX(),p.getY(), true); <add> if(obj != null){ <add> if(obj.isVisible()){ <add> obj.interact("Examine"); <ide> } else { <del> api.getCamera().toEntity(p); <add> api.getCamera().toEntity(obj); <ide> <del> api.getMouse().click(p.getX(),p.getY(), true); <add> obj.hover(); <add> <add> MethodProvider.sleep(MethodProvider.random(400,900)); <add> <add> api.getMouse().click(true); <add> <add> MethodProvider.sleep(MethodProvider.random(1000,2000)); <add> <add> if(MethodProvider.random(0, 100) < 25){ <add> int rx = MethodProvider.random(1, api.getBot().getCanvas().getX()); <add> int ry = MethodProvider.random(1, api.getBot().getCanvas().getY()); <add> api.mouse.move(rx, ry); <add> } <ide> } <ide> } <add> break; <add> case 2: /*Crafting skill check*/ <add> <ide> break; <ide> } <ide> }
Java
mit
4a390fead5f35d12e4178185f63c8b2cfa53e25a
0
AmadouSallah/Programming-Interview-Questions,AmadouSallah/Programming-Interview-Questions
public class QuickSort { public static int[] quickSort(int[] arr) { quickSort(arr, 0, arr.length - 1); return arr; } private static void quickSort(int[] arr, int start, int end) { if (start >= end) { return; } int pivotIndex = partition(arr, start, end); quickSort(arr, start, pivotIndex - 1); quickSort(arr, pivotIndex + 1, end); } private static int partition(int[] arr, int start, int end) { int pivotElement = arr[end], i = start - 1; for (int j = start; j < end; j++) { if (arr[j] < pivotElement) { i++; swap(arr, i, j); } } i++; swap(arr, i, end); return i; } private static void swap(int[] arr, int i, int j) { if (i == j) { return; } int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } private static String print(int[] arr) { String result = "["; int n = arr.length; for (int i = 0; i < n-1; i++) { result += arr[i] + ", "; } if (n > 0) { result += arr[n-1]; } result += "]"; return result; } public static void main(String[] args) { int[] arr = new int[] {7, 3, -2, 8, 2, -1, 0}; System.out.println("Before sorting, arr = " + print(arr)); System.out.println("After sorting, arr = " + print(quickSort(arr))); } }
Data_Structures_And_Algorithms/SortingAndSearch/QuickSort.java
public class QuickSort { public static int[] quickSort(int[] arr) { quickSort(arr, 0, arr.length - 1); return arr; } private static void quickSort(int[] arr, int start, int end) { if (start >= end) { return; } int pivotIndex = partition(arr, start, end); quickSort(arr, start, pivotIndex - 1); quickSort(arr, pivotIndex + 1, end); } public static int partition(int[] arr, int start, int end) { int pivotElement = arr[end], i = start - 1; for (int j = start; j < end; j++) { if (arr[j] < pivotElement) { i++; swap(arr, i, j); } } i++; swap(arr, i, end); return i; } public static void swap(int[] arr, int i, int j) { if (i == j) { return; } int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static String print(int[] arr) { String result = "["; int n = arr.length; for (int i = 0; i < n-1; i++) { result += arr[i] + ", "; } if (n > 0) { result += arr[n-1]; } result += "]"; return result; } public static void main(String[] args) { int[] arr = new int[] {7, 3, -2, 8, 2, -1, 0}; System.out.println("Before sorting, arr = " + print(arr)); System.out.println("After sorting, arr = " + print(quickSort(arr))); } }
Updated helper methods to private for QuickSort.java
Data_Structures_And_Algorithms/SortingAndSearch/QuickSort.java
Updated helper methods to private for QuickSort.java
<ide><path>ata_Structures_And_Algorithms/SortingAndSearch/QuickSort.java <ide> quickSort(arr, pivotIndex + 1, end); <ide> } <ide> <del> public static int partition(int[] arr, int start, int end) { <add> private static int partition(int[] arr, int start, int end) { <ide> int pivotElement = arr[end], i = start - 1; <ide> for (int j = start; j < end; j++) { <ide> if (arr[j] < pivotElement) { <ide> return i; <ide> } <ide> <del> public static void swap(int[] arr, int i, int j) { <add> private static void swap(int[] arr, int i, int j) { <ide> if (i == j) { <ide> return; <ide> } <ide> arr[j] = temp; <ide> } <ide> <del> public static String print(int[] arr) { <add> private static String print(int[] arr) { <ide> String result = "["; <ide> int n = arr.length; <ide> for (int i = 0; i < n-1; i++) {
Java
apache-2.0
9bd53518d52ea720bb902a261904e910dd398903
0
valfirst/selenium,juangj/selenium,asashour/selenium,markodolancic/selenium,dibagga/selenium,HtmlUnit/selenium,SeleniumHQ/selenium,valfirst/selenium,joshmgrant/selenium,krmahadevan/selenium,markodolancic/selenium,davehunt/selenium,valfirst/selenium,Dude-X/selenium,joshmgrant/selenium,bayandin/selenium,titusfortner/selenium,bayandin/selenium,juangj/selenium,Tom-Trumper/selenium,asolntsev/selenium,jsakamoto/selenium,Dude-X/selenium,davehunt/selenium,jsakamoto/selenium,krmahadevan/selenium,Dude-X/selenium,chrisblock/selenium,asolntsev/selenium,lmtierney/selenium,5hawnknight/selenium,Ardesco/selenium,joshmgrant/selenium,dibagga/selenium,SeleniumHQ/selenium,twalpole/selenium,twalpole/selenium,asolntsev/selenium,mach6/selenium,titusfortner/selenium,lmtierney/selenium,jabbrwcky/selenium,jabbrwcky/selenium,HtmlUnit/selenium,bayandin/selenium,juangj/selenium,titusfortner/selenium,xmhubj/selenium,asashour/selenium,juangj/selenium,Dude-X/selenium,valfirst/selenium,GorK-ChO/selenium,xmhubj/selenium,Ardesco/selenium,oddui/selenium,twalpole/selenium,GorK-ChO/selenium,asashour/selenium,krmahadevan/selenium,jsakamoto/selenium,davehunt/selenium,chrisblock/selenium,juangj/selenium,jabbrwcky/selenium,oddui/selenium,joshmgrant/selenium,bayandin/selenium,twalpole/selenium,valfirst/selenium,joshmgrant/selenium,jsakamoto/selenium,xmhubj/selenium,xmhubj/selenium,joshmgrant/selenium,SeleniumHQ/selenium,asashour/selenium,Tom-Trumper/selenium,oddui/selenium,asashour/selenium,GorK-ChO/selenium,bayandin/selenium,juangj/selenium,jabbrwcky/selenium,dibagga/selenium,jabbrwcky/selenium,valfirst/selenium,Ardesco/selenium,bayandin/selenium,mach6/selenium,5hawnknight/selenium,krmahadevan/selenium,oddui/selenium,GorK-ChO/selenium,bayandin/selenium,chrisblock/selenium,lmtierney/selenium,valfirst/selenium,GorK-ChO/selenium,5hawnknight/selenium,twalpole/selenium,mach6/selenium,krmahadevan/selenium,krmahadevan/selenium,mach6/selenium,xmhubj/selenium,asashour/selenium,GorK-ChO/selenium,davehunt/selenium,chrisblock/selenium,Ardesco/selenium,markodolancic/selenium,juangj/selenium,markodolancic/selenium,HtmlUnit/selenium,chrisblock/selenium,titusfortner/selenium,juangj/selenium,Ardesco/selenium,titusfortner/selenium,jsakamoto/selenium,joshmgrant/selenium,dibagga/selenium,lmtierney/selenium,markodolancic/selenium,5hawnknight/selenium,mach6/selenium,joshmgrant/selenium,joshbruning/selenium,mach6/selenium,xmhubj/selenium,jsakamoto/selenium,markodolancic/selenium,asolntsev/selenium,markodolancic/selenium,twalpole/selenium,Ardesco/selenium,bayandin/selenium,jsakamoto/selenium,HtmlUnit/selenium,chrisblock/selenium,Tom-Trumper/selenium,joshbruning/selenium,Tom-Trumper/selenium,HtmlUnit/selenium,Ardesco/selenium,titusfortner/selenium,SeleniumHQ/selenium,SeleniumHQ/selenium,5hawnknight/selenium,asashour/selenium,titusfortner/selenium,davehunt/selenium,asolntsev/selenium,5hawnknight/selenium,Dude-X/selenium,xmhubj/selenium,jsakamoto/selenium,davehunt/selenium,oddui/selenium,asolntsev/selenium,HtmlUnit/selenium,oddui/selenium,krmahadevan/selenium,joshmgrant/selenium,twalpole/selenium,GorK-ChO/selenium,SeleniumHQ/selenium,joshmgrant/selenium,krmahadevan/selenium,joshbruning/selenium,5hawnknight/selenium,asolntsev/selenium,Tom-Trumper/selenium,markodolancic/selenium,xmhubj/selenium,joshbruning/selenium,Tom-Trumper/selenium,markodolancic/selenium,mach6/selenium,oddui/selenium,HtmlUnit/selenium,SeleniumHQ/selenium,joshmgrant/selenium,Tom-Trumper/selenium,titusfortner/selenium,titusfortner/selenium,valfirst/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,krmahadevan/selenium,dibagga/selenium,jabbrwcky/selenium,valfirst/selenium,lmtierney/selenium,GorK-ChO/selenium,dibagga/selenium,jabbrwcky/selenium,oddui/selenium,lmtierney/selenium,valfirst/selenium,SeleniumHQ/selenium,oddui/selenium,dibagga/selenium,lmtierney/selenium,asolntsev/selenium,Dude-X/selenium,juangj/selenium,bayandin/selenium,jabbrwcky/selenium,twalpole/selenium,HtmlUnit/selenium,xmhubj/selenium,chrisblock/selenium,joshbruning/selenium,davehunt/selenium,Ardesco/selenium,lmtierney/selenium,Dude-X/selenium,mach6/selenium,Dude-X/selenium,valfirst/selenium,titusfortner/selenium,jsakamoto/selenium,chrisblock/selenium,joshbruning/selenium,asashour/selenium,joshbruning/selenium,davehunt/selenium,SeleniumHQ/selenium,mach6/selenium,lmtierney/selenium,asolntsev/selenium,HtmlUnit/selenium,Tom-Trumper/selenium,chrisblock/selenium,GorK-ChO/selenium,asashour/selenium,titusfortner/selenium,5hawnknight/selenium,dibagga/selenium,SeleniumHQ/selenium,davehunt/selenium,jabbrwcky/selenium,joshbruning/selenium,Ardesco/selenium,Dude-X/selenium,Tom-Trumper/selenium,5hawnknight/selenium,twalpole/selenium,joshbruning/selenium,dibagga/selenium
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you 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. package org.openqa.selenium.server.htmlrunner; import static java.util.concurrent.TimeUnit.SECONDS; import static org.openqa.selenium.firefox.FirefoxDriver.MARIONETTE; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.thoughtworks.selenium.Selenium; import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.internal.SocketLock; import org.openqa.selenium.net.PortProber; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.safari.SafariDriver; import org.seleniumhq.jetty9.server.Connector; import org.seleniumhq.jetty9.server.HttpConfiguration; import org.seleniumhq.jetty9.server.HttpConnectionFactory; import org.seleniumhq.jetty9.server.Server; import org.seleniumhq.jetty9.server.ServerConnector; import org.seleniumhq.jetty9.server.handler.ContextHandler; import org.seleniumhq.jetty9.server.handler.ResourceHandler; import org.seleniumhq.jetty9.util.resource.PathResource; import java.io.File; import java.io.IOException; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Runs HTML Selenium test suites. */ public class HTMLLauncher { // java -jar selenium-server-standalone-<version-number>.jar -htmlSuite "*firefox" // "http://www.google.com" "c:\absolute\path\to\my\HTMLSuite.html" // "c:\absolute\path\to\my\results.html" private static Logger log = Logger.getLogger(HTMLLauncher.class.getName()); private Server server; /** * Launches a single HTML Selenium test suite. * * @param browser - the browserString ("*firefox", "*iexplore" or an executable path) * @param startURL - the start URL for the browser * @param suiteURL - the relative URL to the HTML suite * @param outputFile - The file to which we'll output the HTML results * @param timeoutInSeconds - the amount of time (in seconds) to wait for the browser to finish * @return PASS or FAIL * @throws IOException if we can't write the output file */ public String runHTMLSuite( String browser, String startURL, String suiteURL, File outputFile, long timeoutInSeconds, String userExtensions) throws IOException { File parent = outputFile.getParentFile(); if (parent != null && !parent.exists()) { parent.mkdirs(); } if (outputFile.exists() && !outputFile.canWrite()) { throw new IOException("Can't write to outputFile: " + outputFile.getAbsolutePath()); } long timeoutInMs = 1000L * timeoutInSeconds; if (timeoutInMs < 0) { log.warning("Looks like the timeout overflowed, so resetting it to the maximum."); timeoutInMs = Long.MAX_VALUE; } WebDriver driver = null; try { driver = createDriver(browser); URL suiteUrl = determineSuiteUrl(startURL, suiteURL); driver.get(suiteUrl.toString()); Selenium selenium = new WebDriverBackedSelenium(driver, startURL); selenium.setTimeout(String.valueOf(timeoutInMs)); if (userExtensions != null) { selenium.setExtensionJs(userExtensions); } List<WebElement> allTables = driver.findElements(By.id("suiteTable")); if (allTables.isEmpty()) { throw new RuntimeException("Unable to find suite table: " + driver.getPageSource()); } Results results = new CoreTestSuite(suiteUrl.toString()).run(driver, selenium, new URL(startURL)); HTMLTestResults htmlResults = results.toSuiteResult(); try (Writer writer = Files.newBufferedWriter(outputFile.toPath())) { htmlResults.write(writer); } return results.isSuccessful() ? "PASSED" : "FAILED"; } finally { if (server != null) { try { server.stop(); } catch (Exception e) { // Nothing sane to do. Log the error and carry on log.log(Level.INFO, "Exception shutting down server. You may ignore this.", e); } } if (driver != null) { driver.quit(); } } } private URL determineSuiteUrl(String startURL, String suiteURL) throws IOException { if (suiteURL.startsWith("https://") || suiteURL.startsWith("http://")) { return verifySuiteUrl(new URL(suiteURL)); } // Is the suiteURL a file? Path path = Paths.get(suiteURL).toAbsolutePath(); if (Files.exists(path)) { // Not all drivers can read files from the disk, so we need to host the suite somewhere. try (SocketLock lock = new SocketLock()) { server = new Server(); HttpConfiguration httpConfig = new HttpConfiguration(); ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); int port = PortProber.findFreePort(); http.setPort(port); http.setIdleTimeout(500000); server.setConnectors(new Connector[]{http}); ResourceHandler handler = new ResourceHandler(); handler.setDirectoriesListed(true); handler.setWelcomeFiles(new String[]{path.getFileName().toString(), "index.html"}); handler.setBaseResource(new PathResource(path.toFile().getParentFile().toPath().toRealPath())); ContextHandler context = new ContextHandler("/tests"); context.setHandler(handler); server.setHandler(context); server.start(); PortProber.waitForPortUp(port, 15, SECONDS); URL serverUrl = server.getURI().toURL(); return new URL(serverUrl.getProtocol(), serverUrl.getHost(), serverUrl.getPort(), "/tests/"); } catch (Exception e) { throw new IOException(e); } } // Well then, it must be a URL relative to whatever the browserUrl. Probe and find out. URL browser = new URL(startURL); return verifySuiteUrl(new URL(browser, suiteURL)); } private URL verifySuiteUrl(URL url) throws IOException { // Now probe. URLConnection connection = url.openConnection(); if (!(connection instanceof HttpURLConnection)) { throw new IOException("The HTMLLauncher only supports relative HTTP URLs"); } HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setInstanceFollowRedirects(true); httpConnection.setRequestMethod("HEAD"); int responseCode = httpConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { throw new IOException("Invalid suite URL: " + url); } return url; } public static int mainInt(String... args) throws Exception { Args processed = new Args(); JCommander jCommander = new JCommander(processed); jCommander.setCaseSensitiveOptions(false); jCommander.parse(args); if (processed.help) { StringBuilder help = new StringBuilder(); jCommander.usage(help); System.err.print(help); return 0; } if (!validateArgs(processed)) { return -1; } Path resultsPath = Paths.get(processed.htmlSuite.get(3)); Files.createDirectories(resultsPath); String suite = processed.htmlSuite.get(2); String startURL = processed.htmlSuite.get(1); String[] browsers = new String[] {processed.htmlSuite.get(0)}; HTMLLauncher launcher = new HTMLLauncher(); boolean passed = true; for (String browser : browsers) { // Turns out that Windows doesn't like "*" in a path name String reportFileName = browser.contains(" ") ? browser.substring(0, browser.indexOf(' ')) : browser; File results = resultsPath.resolve(reportFileName.substring(1) + ".results.html").toFile(); String result = "FAILED"; try { long timeout; try { timeout = Long.parseLong(processed.timeout); } catch (NumberFormatException e) { System.err.println("Timeout does not appear to be a number: " + processed.timeout); return -2; } result = launcher.runHTMLSuite(browser, startURL, suite, results, timeout, processed.userExtensions); passed &= "PASSED".equals(result); } catch (Throwable e) { log.log(Level.WARNING, "Test of browser failed: " + browser, e); passed = false; } } return passed ? 1 : 0; } private static boolean validateArgs(Args processed) { if (processed.multiWindow) { System.err.println("Multi-window mode is longer used as an option and will be ignored."); } if (processed.port != 0) { System.err.println("Port is longer used as an option and will be ignored."); } if (processed.trustAllSSLCertificates) { System.err.println("Trusting all ssl certificates is no longer a user-settable option."); } return true; } public static void main(String[] args) throws Exception { System.exit(mainInt(args)); } private WebDriver createDriver(String browser) { String[] parts = browser.split(" ", 2); browser = parts[0]; switch (browser) { case "*chrome": case "*firefox": case "*firefoxproxy": case "*firefoxchrome": case "*pifirefox": FirefoxOptions options = new FirefoxOptions().setLegacy(false); if (parts.length > 1) { options.setBinary(parts[1]); } return new FirefoxDriver(options); case "*iehta": case "*iexplore": case "*iexploreproxy": case "*piiexplore": return new InternetExplorerDriver(); case "*googlechrome": return new ChromeDriver(); case "*MicrosoftEdge": return new EdgeDriver(); case "*opera": case "*operablink": return new OperaDriver(); case "*safari": case "*safariproxy": return new SafariDriver(); default: throw new RuntimeException("Unrecognized browser: " + browser); } } public static class Args { @Parameter( names = "-htmlSuite", required = true, arity = 4, description = "Run an HTML Suite: \"*browser\" \"http://baseUrl.com\" \"path\\to\\HTMLSuite.html\" \"path\\to\\report\\dir\"") private List<String> htmlSuite; @Parameter( names = "-timeout", description = "Timeout to use in seconds") private String timeout = "30"; @Parameter( names = "-userExtensions", description = "User extensions to attempt to use." ) private String userExtensions; @Parameter( names = "-multiwindow", hidden = true) private boolean multiWindow = true; @Parameter( names = "-port", hidden = true) private Integer port = 0; @Parameter( names = "-trustAllSSLCertificates", hidden = true) private boolean trustAllSSLCertificates; @Parameter( names = {"-help", "--help", "-h"}, description = "This help message", help = true) private boolean help; } }
java/server/src/org/openqa/selenium/server/htmlrunner/HTMLLauncher.java
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you 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. package org.openqa.selenium.server.htmlrunner; import static java.util.concurrent.TimeUnit.SECONDS; import static org.openqa.selenium.firefox.FirefoxDriver.MARIONETTE; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.thoughtworks.selenium.Selenium; import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.internal.SocketLock; import org.openqa.selenium.net.PortProber; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.safari.SafariDriver; import org.seleniumhq.jetty9.server.Connector; import org.seleniumhq.jetty9.server.HttpConfiguration; import org.seleniumhq.jetty9.server.HttpConnectionFactory; import org.seleniumhq.jetty9.server.Server; import org.seleniumhq.jetty9.server.ServerConnector; import org.seleniumhq.jetty9.server.handler.ContextHandler; import org.seleniumhq.jetty9.server.handler.ResourceHandler; import org.seleniumhq.jetty9.util.resource.PathResource; import java.io.File; import java.io.IOException; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Runs HTML Selenium test suites. */ public class HTMLLauncher { // java -jar selenium-server-standalone-<version-number>.jar -htmlSuite "*firefox" // "http://www.google.com" "c:\absolute\path\to\my\HTMLSuite.html" // "c:\absolute\path\to\my\results.html" private static Logger log = Logger.getLogger(HTMLLauncher.class.getName()); private Server server; /** * Launches a single HTML Selenium test suite. * * @param browser - the browserString ("*firefox", "*iexplore" or an executable path) * @param startURL - the start URL for the browser * @param suiteURL - the relative URL to the HTML suite * @param outputFile - The file to which we'll output the HTML results * @param timeoutInSeconds - the amount of time (in seconds) to wait for the browser to finish * @return PASS or FAIL * @throws IOException if we can't write the output file */ public String runHTMLSuite( String browser, String startURL, String suiteURL, File outputFile, long timeoutInSeconds, String userExtensions) throws IOException { File parent = outputFile.getParentFile(); if (parent != null && !parent.exists()) { parent.mkdirs(); } if (outputFile.exists() && !outputFile.canWrite()) { throw new IOException("Can't write to outputFile: " + outputFile.getAbsolutePath()); } long timeoutInMs = 1000L * timeoutInSeconds; if (timeoutInMs < 0) { log.warning("Looks like the timeout overflowed, so resetting it to the maximum."); timeoutInMs = Long.MAX_VALUE; } WebDriver driver = null; try { driver = createDriver(browser); URL suiteUrl = determineSuiteUrl(startURL, suiteURL); driver.get(suiteUrl.toString()); Selenium selenium = new WebDriverBackedSelenium(driver, startURL); selenium.setTimeout(String.valueOf(timeoutInMs)); if (userExtensions != null) { selenium.setExtensionJs(userExtensions); } List<WebElement> allTables = driver.findElements(By.id("suiteTable")); if (allTables.isEmpty()) { throw new RuntimeException("Unable to find suite table: " + driver.getPageSource()); } Results results = new CoreTestSuite(suiteUrl.toString()).run(driver, selenium, new URL(startURL)); HTMLTestResults htmlResults = results.toSuiteResult(); try (Writer writer = Files.newBufferedWriter(outputFile.toPath())) { htmlResults.write(writer); } return results.isSuccessful() ? "PASSED" : "FAILED"; } finally { if (server != null) { try { server.stop(); } catch (Exception e) { // Nothing sane to do. Log the error and carry on log.log(Level.INFO, "Exception shutting down server. You may ignore this.", e); } } if (driver != null) { driver.quit(); } } } private URL determineSuiteUrl(String startURL, String suiteURL) throws IOException { if (suiteURL.startsWith("https://") || suiteURL.startsWith("http://")) { return verifySuiteUrl(new URL(suiteURL)); } // Is the suiteURL a file? Path path = Paths.get(suiteURL).toAbsolutePath(); if (Files.exists(path)) { // Not all drivers can read files from the disk, so we need to host the suite somewhere. try (SocketLock lock = new SocketLock()) { server = new Server(); HttpConfiguration httpConfig = new HttpConfiguration(); ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); int port = PortProber.findFreePort(); http.setPort(port); http.setIdleTimeout(500000); server.setConnectors(new Connector[]{http}); ResourceHandler handler = new ResourceHandler(); handler.setDirectoriesListed(true); handler.setWelcomeFiles(new String[]{path.getFileName().toString(), "index.html"}); handler.setBaseResource(new PathResource(path.toFile().getParentFile().toPath().toRealPath())); ContextHandler context = new ContextHandler("/tests"); context.setHandler(handler); server.setHandler(context); server.start(); PortProber.waitForPortUp(port, 15, SECONDS); URL serverUrl = server.getURI().toURL(); return new URL(serverUrl.getProtocol(), serverUrl.getHost(), serverUrl.getPort(), "/tests/"); } catch (Exception e) { throw new IOException(e); } } // Well then, it must be a URL relative to whatever the browserUrl. Probe and find out. URL browser = new URL(startURL); return verifySuiteUrl(new URL(browser, suiteURL)); } private URL verifySuiteUrl(URL url) throws IOException { // Now probe. URLConnection connection = url.openConnection(); if (!(connection instanceof HttpURLConnection)) { throw new IOException("The HTMLLauncher only supports relative HTTP URLs"); } HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setInstanceFollowRedirects(true); httpConnection.setRequestMethod("HEAD"); int responseCode = httpConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { throw new IOException("Invalid suite URL: " + url); } return url; } public static int mainInt(String... args) throws Exception { Args processed = new Args(); JCommander jCommander = new JCommander(processed); jCommander.setCaseSensitiveOptions(false); jCommander.parse(args); if (processed.help) { StringBuilder help = new StringBuilder(); jCommander.usage(help); System.err.print(help); return 0; } if (!validateArgs(processed)) { return -1; } Path resultsPath = Paths.get(processed.htmlSuite.get(3)); Files.createDirectories(resultsPath); String suite = processed.htmlSuite.get(2); String startURL = processed.htmlSuite.get(1); String[] browsers = new String[] {processed.htmlSuite.get(0)}; HTMLLauncher launcher = new HTMLLauncher(); boolean passed = true; for (String browser : browsers) { // Turns out that Windows doesn't like "*" in a path name File results = resultsPath.resolve(browser.substring(1) + ".results.html").toFile(); String result = "FAILED"; try { long timeout; try { timeout = Long.parseLong(processed.timeout); } catch (NumberFormatException e) { System.err.println("Timeout does not appear to be a number: " + processed.timeout); return -2; } result = launcher.runHTMLSuite(browser, startURL, suite, results, timeout, processed.userExtensions); passed &= "PASSED".equals(result); } catch (Throwable e) { log.log(Level.WARNING, "Test of browser failed: " + browser, e); passed = false; } } return passed ? 1 : 0; } private static boolean validateArgs(Args processed) { if (processed.multiWindow) { System.err.println("Multi-window mode is longer used as an option and will be ignored."); } if (processed.port != 0) { System.err.println("Port is longer used as an option and will be ignored."); } if (processed.trustAllSSLCertificates) { System.err.println("Trusting all ssl certificates is no longer a user-settable option."); } return true; } public static void main(String[] args) throws Exception { System.exit(mainInt(args)); } private WebDriver createDriver(String browser) { switch (browser) { case "*chrome": case "*firefox": case "*firefoxproxy": case "*firefoxchrome": case "*pifirefox": DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability(MARIONETTE, true); return new FirefoxDriver(caps); case "*iehta": case "*iexplore": case "*iexploreproxy": case "*piiexplore": return new InternetExplorerDriver(); case "*googlechrome": return new ChromeDriver(); case "*MicrosoftEdge": return new EdgeDriver(); case "*opera": case "*operablink": return new OperaDriver(); case "*safari": case "*safariproxy": return new SafariDriver(); default: throw new RuntimeException("Unrecognized browser: " + browser); } } public static class Args { @Parameter( names = "-htmlSuite", required = true, arity = 4, description = "Run an HTML Suite: '*browser' 'http://baseUrl.com' 'path\\to\\HTMLSuite.html' 'c:\\absolute\\path\\to\\my\\results.html'") private List<String> htmlSuite; @Parameter( names = "-timeout", description = "Timeout to use in seconds") private String timeout = "30"; @Parameter( names = "-userExtensions", description = "User extensions to attempt to use." ) private String userExtensions; @Parameter( names = "-multiwindow", hidden = true) private boolean multiWindow = true; @Parameter( names = "-port", hidden = true) private Integer port = 0; @Parameter( names = "-trustAllSSLCertificates", hidden = true) private boolean trustAllSSLCertificates; @Parameter( names = {"-help", "--help", "-h"}, description = "This help message", help = true) private boolean help; } }
[htmlrunner] Implementing ability to specify path to the browser in CLI
java/server/src/org/openqa/selenium/server/htmlrunner/HTMLLauncher.java
[htmlrunner] Implementing ability to specify path to the browser in CLI
<ide><path>ava/server/src/org/openqa/selenium/server/htmlrunner/HTMLLauncher.java <ide> import org.openqa.selenium.chrome.ChromeDriver; <ide> import org.openqa.selenium.edge.EdgeDriver; <ide> import org.openqa.selenium.firefox.FirefoxDriver; <add>import org.openqa.selenium.firefox.FirefoxOptions; <ide> import org.openqa.selenium.ie.InternetExplorerDriver; <ide> import org.openqa.selenium.internal.SocketLock; <ide> import org.openqa.selenium.net.PortProber; <ide> boolean passed = true; <ide> for (String browser : browsers) { <ide> // Turns out that Windows doesn't like "*" in a path name <del> File results = resultsPath.resolve(browser.substring(1) + ".results.html").toFile(); <add> String reportFileName = browser.contains(" ") ? browser.substring(0, browser.indexOf(' ')) : browser; <add> File results = resultsPath.resolve(reportFileName.substring(1) + ".results.html").toFile(); <ide> String result = "FAILED"; <ide> <ide> try { <ide> } <ide> <ide> private WebDriver createDriver(String browser) { <add> String[] parts = browser.split(" ", 2); <add> browser = parts[0]; <ide> switch (browser) { <ide> case "*chrome": <ide> case "*firefox": <ide> case "*firefoxproxy": <ide> case "*firefoxchrome": <ide> case "*pifirefox": <del> DesiredCapabilities caps = new DesiredCapabilities(); <del> caps.setCapability(MARIONETTE, true); <del> return new FirefoxDriver(caps); <add> FirefoxOptions options = new FirefoxOptions().setLegacy(false); <add> if (parts.length > 1) { <add> options.setBinary(parts[1]); <add> } <add> return new FirefoxDriver(options); <ide> <ide> case "*iehta": <ide> case "*iexplore": <ide> names = "-htmlSuite", <ide> required = true, <ide> arity = 4, <del> description = "Run an HTML Suite: '*browser' 'http://baseUrl.com' 'path\\to\\HTMLSuite.html' 'c:\\absolute\\path\\to\\my\\results.html'") <add> description = "Run an HTML Suite: \"*browser\" \"http://baseUrl.com\" \"path\\to\\HTMLSuite.html\" \"path\\to\\report\\dir\"") <ide> private List<String> htmlSuite; <ide> <ide> @Parameter(
JavaScript
isc
375bdc64793c4d73f1851c60cb23b88d24a64bc2
0
moebooru/moebooru,euank/moebooru-thin,nanaya/moebooru,moebooru/moebooru,nanaya/moebooru,moebooru/moebooru,nanaya/moebooru,euank/moebooru-thin,nanaya/moebooru,euank/moebooru-thin,euank/moebooru-thin,moebooru/moebooru,nanaya/moebooru,moebooru/moebooru,euank/moebooru-thin
var DANBOORU_VERSION = { major: 1, minor: 13, build: 0 } /* If initial is true, this is a notice set by the notice cookie and not a * realtime notice from user interaction. */ function notice(msg, initial) { /* If this is an initial notice, and this screen has a dedicated notice * container other than the floating notice, use that and don't disappear * it. */ if(initial) { var static_notice = $("static_notice"); if(static_notice) { static_notice.update(msg); static_notice.show(); return; } } start_notice_timer(); $('notice').update(msg); $('notice-container').show(); } function number_to_human_size(size, precision) { if(precision == null) precision = 1; size = Number(size); if(size.toFixed(0) == 1) text = "1 Byte"; else if(size < 1024) text = size.toFixed(0) + " Bytes"; else if(size < 1024*1024) text = (size / 1024).toFixed(precision) + " KB"; else if(size < 1024*1024*1024) text = (size / (1024*1024)).toFixed(precision) + " MB"; else if(size < 1024*1024*1024*1024) text = (size / (1024*1024*1024)).toFixed(precision) + " GB"; else text = (size / (1024*1024*1024*1024)).toFixed(precision) + " TB"; text = text.gsub(/([0-9]\.\d*?)0+ /, '#{1} ' ).gsub(/\. /,' '); return text; } var ClearNoticeTimer; function start_notice_timer() { if(ClearNoticeTimer) window.clearTimeout(ClearNoticeTimer); ClearNoticeTimer = window.setTimeout(function() { $('notice-container').hide(); }, 5000); } var ClipRange = Class.create({ initialize: function(min, max) { if (min > max) { throw "paramError" } this.min = min this.max = max }, clip: function(x) { if (x < this.min) { return this.min } if (x > this.max) { return this.max } return x } }) Object.extend(Element, { appendChildBase: Element.appendChild, appendChild: function(e) { this.appendChildBase(e) return e } }); Object.extend(Element.Methods, { showBase: Element.show, show: function(element, visible) { if (visible || visible == null) return $(element).showBase(); else return $(element).hide(); }, isParentNode: function(element, parentNode) { while(element) { if(element == parentNode) return true; element = element.parentNode; } return false; }, setTextContent: function(element, text) { if(element.innerText) element.innerText = text; else element.textContent = text; return element; } }); Element.addMethods() var KeysDown = new Hash(); /* Many browsers eat keyup events if focus is lost while the button * is pressed. */ document.observe("blur", function(e) { KeysDown = new Hash(); }) function OnKeyCharCode(key, f, element) { if(window.opera) return; if(!element) element = document; element.observe("keyup", function(e) { if (e.keyCode != key) return; KeysDown.set(KeysDown[e.keyCode], false); }); element.observe("keypress", function(e) { if (e.charCode != key) return; if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) return; if(KeysDown.get(KeysDown[e.keyCode])) return; KeysDown.set(KeysDown[e.keyCode], true); var target = e.target; if(target.tagName == "INPUT" || target.tagName == "TEXTAREA") return; f(e); e.stop(); e.preventDefault(); }); } function OnKey(key, options, press, release) { if(!options) options = {}; var element = options["Element"] if(!element) element = document; if(element == document && window.opera && !options.AlwaysAllowOpera) return; element.observe("keyup", function(e) { if (e.keyCode != key) return; KeysDown[e.keyCode] = false if(release) release(e); }); element.observe("keydown", function(e) { if (e.keyCode != key) return; if (e.metaKey) return; if (e.shiftKey != !!options.shiftKey) return; if (e.altKey != !!options.altKey) return; if (e.ctrlKey != !!options.ctrlKey) return; if(KeysDown[e.keyCode]) return; KeysDown[e.keyCode] = true var target = e.target; if(!options.AllowTextAreaFields && target.tagName == "TEXTAREA") return; if(!options.AllowInputFields && target.tagName == "INPUT") return; if(press && !press(e)) return; e.stop(); e.preventDefault(); }); } function InitTextAreas() { $$("TEXTAREA").each(function(elem) { var form = elem.up("FORM"); if(!form) return; if(elem.set_login_handler) return; elem.set_login_handler = true; OnKey(13, { ctrlKey: true, AllowInputFields: true, AllowTextAreaFields: true, Element: elem}, function(f) { $(form).submitWithLogin(); }); }); } function InitAdvancedEditing() { if(Cookie.get("show_advanced_editing") != "1") return; document.documentElement.removeClassName("hide-advanced-editing"); } /* When we resume a user submit after logging in, we want to run submit events, as * if the submit had happened normally again, but submit() doesn't do this. Run * a submit event manually. */ Element.addMethods("FORM", { simulate_submit: function(form) { form = $(form); if(document.createEvent) { var e = document.createEvent("HTMLEvents"); e.initEvent("submit", true, true); form.dispatchEvent(e); if(!e.stopped) form.submit(); } else { if(form.fireEvent("onsubmit")) form.submit(); } } }); Element.addMethods({ simulate_anchor_click: function(a, ev) { a = $(a); if(document.dispatchEvent) { if(a.dispatchEvent(ev) && !ev.stopped) window.location.href = a.href; } else { if(a.fireEvent("onclick", ev)) window.location.href = a.href; } } }); clone_event = function(orig) { if(document.dispatchEvent) { var e = document.createEvent("MouseEvent"); e.initMouseEvent(orig.type, orig.canBubble, orig.cancelable, orig.view, orig.detail, orig.screenX, orig.screenY, orig.clientX, orig.clientY, orig.ctrlKey, orig.altKey, orig.shiftKey, orig.metaKey, orig.button, orig.relatedTarget); return Event.extend(e); } else { var e = document.createEventObject(orig); return Event.extend(e); } }
public/javascripts/common.js
var DANBOORU_VERSION = { major: 1, minor: 13, build: 0 } /* If initial is true, this is a notice set by the notice cookie and not a * realtime notice from user interaction. */ function notice(msg, initial) { /* If this is an initial notice, and this screen has a dedicated notice * container other than the floating notice, use that and don't disappear * it. */ if(initial) { var static_notice = $("static_notice"); if(static_notice) { static_notice.update(msg); static_notice.show(); return; } } start_notice_timer(); $('notice').update(msg); $('notice-container').show(); } function number_to_human_size(size, precision) { if(precision == null) precision = 1; size = Number(size); if(size.toFixed(0) == 1) text = "1 Byte"; else if(size < 1024) text = size.toFixed(0) + " Bytes"; else if(size < 1024*1024) text = (size / 1024).toFixed(precision) + " KB"; else if(size < 1024*1024*1024) text = (size / (1024*1024)).toFixed(precision) + " MB"; else if(size < 1024*1024*1024*1024) text = (size / (1024*1024*1024)).toFixed(precision) + " GB"; else text = (size / (1024*1024*1024*1024)).toFixed(precision) + " TB"; text = text.gsub(/([0-9]\.\d*?)0+ /, '#{1} ' ).gsub(/\. /,' '); return text; } var ClearNoticeTimer; function start_notice_timer() { if(ClearNoticeTimer) window.clearTimeout(ClearNoticeTimer); ClearNoticeTimer = window.setTimeout(function() { $('notice-container').hide(); }, 5000); } var ClipRange = Class.create({ initialize: function(min, max) { if (min > max) { throw "paramError" } this.min = min this.max = max }, clip: function(x) { if (x < this.min) { return this.min } if (x > this.max) { return this.max } return x } }) Object.extend(Element, { appendChildBase: Element.appendChild, appendChild: function(e) { this.appendChildBase(e) return e } }); Object.extend(Element.Methods, { showBase: Element.show, show: function(element, visible) { if (visible || visible == null) return $(element).showBase(); else return $(element).hide(); }, isParentNode: function(element, parentNode) { while(element) { if(element == parentNode) return true; element = element.parentNode; } return false; }, setTextContent: function(element, text) { if(element.innerText) element.innerText = text; else element.textContent = text; return element; } }); Element.addMethods() var KeysDown = new Hash(); /* Many browsers eat keyup events if focus is lost while the button * is pressed. */ document.observe("blur", function(e) { KeysDown = new Hash(); }) function OnKeyCharCode(key, f, element) { if(window.opera) return; if(!element) element = document; element.observe("keyup", function(e) { if (e.keyCode != key) return; KeysDown.set(KeysDown[e.keyCode], false); }); element.observe("keypress", function(e) { if (e.charCode != key) return; if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) return; if(KeysDown.get(KeysDown[e.keyCode])) return; KeysDown.set(KeysDown[e.keyCode], true); var target = e.target; if(target.tagName == "INPUT" || target.tagName == "TEXTAREA") return; f(e); e.stop(); e.preventDefault(); }); } function OnKey(key, options, press, release) { if(!options) options = {}; var element = options["Element"] if(!element) element = document; if(element == document && window.opera && !options.AlwaysAllowOpera) return; element.observe("keyup", function(e) { if (e.keyCode != key) return; KeysDown[e.keyCode] = false if(release) release(e); }); element.observe("keydown", function(e) { if (e.keyCode != key) return; if (e.metaKey) return; if (e.shiftKey != !!options.shiftKey) return; if (e.altKey != !!options.altKey) return; if (e.ctrlKey != !!options.ctrlKey) return; if(KeysDown[e.keyCode]) return; KeysDown[e.keyCode] = true var target = e.target; if(!options.AllowTextAreaFields && target.tagName == "TEXTAREA") return; if(!options.AllowInputFields && target.tagName == "INPUT") return; if(press && !press(e)) return; e.stop(); e.preventDefault(); }); } function InitTextAreas() { $$("TEXTAREA").each(function(elem) { var form = elem.up("FORM"); if(!form) return; if(form.set_login_handler) return; form.set_login_handler = true; OnKey(13, { ctrlKey: true, AllowInputFields: true, AllowTextAreaFields: true, Element: elem}, function(f) { $(form).submitWithLogin(); }); }); } function InitAdvancedEditing() { if(Cookie.get("show_advanced_editing") != "1") return; document.documentElement.removeClassName("hide-advanced-editing"); } /* When we resume a user submit after logging in, we want to run submit events, as * if the submit had happened normally again, but submit() doesn't do this. Run * a submit event manually. */ Element.addMethods("FORM", { simulate_submit: function(form) { form = $(form); if(document.createEvent) { var e = document.createEvent("HTMLEvents"); e.initEvent("submit", true, true); form.dispatchEvent(e); if(!e.stopped) form.submit(); } else { if(form.fireEvent("onsubmit")) form.submit(); } } }); Element.addMethods({ simulate_anchor_click: function(a, ev) { a = $(a); if(document.dispatchEvent) { if(a.dispatchEvent(ev) && !ev.stopped) window.location.href = a.href; } else { if(a.fireEvent("onclick", ev)) window.location.href = a.href; } } }); clone_event = function(orig) { if(document.dispatchEvent) { var e = document.createEvent("MouseEvent"); e.initMouseEvent(orig.type, orig.canBubble, orig.cancelable, orig.view, orig.detail, orig.screenX, orig.screenY, orig.clientX, orig.clientY, orig.ctrlKey, orig.altKey, orig.shiftKey, orig.metaKey, orig.button, orig.relatedTarget); return Event.extend(e); } else { var e = document.createEventObject(orig); return Event.extend(e); } }
mark set_login_handler on each element, not on the containing form --HG-- branch : moe extra : convert_revision : svn%3A2d28d66d-8d94-df11-8c86-00306ef368cb/trunk/moe%40421
public/javascripts/common.js
mark set_login_handler on each element, not on the containing form
<ide><path>ublic/javascripts/common.js <ide> if(!form) <ide> return; <ide> <del> if(form.set_login_handler) <del> return; <del> form.set_login_handler = true; <add> if(elem.set_login_handler) <add> return; <add> elem.set_login_handler = true; <ide> <ide> OnKey(13, { ctrlKey: true, AllowInputFields: true, AllowTextAreaFields: true, Element: elem}, function(f) { <ide> $(form).submitWithLogin();
Java
bsd-3-clause
ce91300ca48f99d3fdac7959dd69128403916ac0
0
Beachbot330/Beachbot2014Java
// RobotBuilder Version: 1.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc330.Beachbot2014Java.commands; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import org.usfirst.frc330.Beachbot2014Java.Robot; /** * */ public class KillAllCommands extends Command { public KillAllCommands() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { Scheduler.getInstance().removeAll(); Robot.chassis.stopDrive(); Robot.arm.stopArm(); Robot.pickup.setPickupMotorOff(); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return true; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
src/org/usfirst/frc330/Beachbot2014Java/commands/KillAllCommands.java
// RobotBuilder Version: 1.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc330.Beachbot2014Java.commands; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import org.usfirst.frc330.Beachbot2014Java.Robot; /** * */ public class KillAllCommands extends Command { public KillAllCommands() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { Scheduler.getInstance().removeAll(); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return true; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
Disable all PID also
src/org/usfirst/frc330/Beachbot2014Java/commands/KillAllCommands.java
Disable all PID also
<ide><path>rc/org/usfirst/frc330/Beachbot2014Java/commands/KillAllCommands.java <ide> // Called repeatedly when this Command is scheduled to run <ide> protected void execute() { <ide> Scheduler.getInstance().removeAll(); <add> Robot.chassis.stopDrive(); <add> Robot.arm.stopArm(); <add> Robot.pickup.setPickupMotorOff(); <ide> } <ide> // Make this return true when this Command no longer needs to run execute() <ide> protected boolean isFinished() {
Java
mit
38ecdaf575a389f2a17586e4a6ba690159fc8ed8
0
CS2103AUG2016-F10-C1/main,CS2103AUG2016-F10-C1/main,CS2103AUG2016-F10-C1/main
package tars.logic.parser; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeMap; /** * Tokenizes arguments string of the form: {@code preamble <prefix>value <prefix>value ...}<br> * e.g. {@code some preamble text /dt today at 3pm /t tag1 /t tag2 /ls} where prefixes are {@code /dt /t}.<br> * 1. An argument's value can be an empty string e.g. the value of {@code /ls} in the above example.<br> * 2. Leading and trailing whitespaces of an argument value will be discarded.<br> * 3. A prefix need to have leading and trailing spaces e.g. the {@code /d today at 3pm /t tag1} in the above example<br> * 4. An argument may be repeated and all its values will be accumulated e.g. the value of {@code /t} in the above example.<br> */ public class ArgumentTokenizer { private static final int INVALID_POS = -1; private static final int START_INDEX_POS = -1; private static final String EMPTY_SPACE_ONE = " "; private static final String EMPTY_STRING = ""; private final Prefix[] prefixes; private HashMap<Prefix, String> prefixValueMap; private TreeMap<Integer, Prefix> prefixPosMap; private String args; public ArgumentTokenizer(Prefix... prefixes) { this.prefixes = prefixes; init(); } public void tokenize(String args) { resetExtractorState(); this.args = args; this.prefixPosMap = getPrefixPositon(); extractArguments(); } private void init() { this.args = EMPTY_STRING; this.prefixValueMap = new HashMap<Prefix, String>(); this.prefixPosMap = new TreeMap<Integer, Prefix>(); } private void resetExtractorState() { this.prefixValueMap.clear(); } /** * Gets all prefix positions from arguments string */ private TreeMap<Integer, Prefix> getPrefixPositon() { prefixPosMap = new TreeMap<Integer, Prefix>(); for (int i = 0; i < prefixes.length; i++) { int curIndexPos = START_INDEX_POS; do { curIndexPos = args.indexOf(EMPTY_SPACE_ONE + prefixes[i].prefix, curIndexPos + 1); if (curIndexPos >= 0) { prefixPosMap.put(curIndexPos, prefixes[i]); } } while (curIndexPos >= 0); } return prefixPosMap; } /** * Extracts the option's prefix and arg from arguments string. */ private HashMap<Prefix, String> extractArguments() { prefixValueMap = new HashMap<Prefix, String>(); int endPos = args.length(); for (Map.Entry<Integer, Prefix> entry : prefixPosMap.descendingMap().entrySet()) { Prefix prefix = entry.getValue(); Integer pos = entry.getKey(); if (pos == INVALID_POS) { continue; } String arg = args.substring(pos, endPos).trim(); endPos = pos; if (prefixValueMap.containsKey(prefix)) { prefixValueMap.put(prefix, prefixValueMap.get(prefix).concat(EMPTY_SPACE_ONE).concat(arg)); } else { prefixValueMap.put(prefix, arg); } } return prefixValueMap; } public Optional<String> getValue(Prefix prefix) { if (!prefixValueMap.containsKey(prefix)) { return Optional.empty(); } return Optional.of(getMultipleValues(prefix).get().iterator().next().trim()); } public Optional<Set<String>> getMultipleValues(Prefix prefix) { if (!prefixValueMap.containsKey(prefix)) { return Optional.empty(); } return Optional.of(getMultipleFromArgs(prefixValueMap.get(prefix), prefix)); } public Optional<String> getMultipleRawValues(Prefix prefix) { if (!prefixValueMap.containsKey(prefix)) { return Optional.empty(); } return Optional.of(prefixValueMap.get(prefix).replaceAll(prefix.prefix + EMPTY_SPACE_ONE, EMPTY_STRING)); } public int numPrefixFound() { return prefixPosMap.size(); } public Optional<String> getPreamble() { if (args.trim().length() == 0) { return Optional.empty(); } if (prefixPosMap.size() == 0) { return Optional.of(args.trim()); } else if (prefixPosMap.firstKey() == 0) { return Optional.empty(); } return Optional.of(args.substring(0, prefixPosMap.firstKey()).trim()); } private Set<String> getMultipleFromArgs(String tagArguments, Prefix prefix) { // no tagArguments if (tagArguments.isEmpty()) { return Collections.emptySet(); } tagArguments = tagArguments.trim(); // replace first delimiter prefix, then split List<String> multipleArgList = Arrays .asList(tagArguments.replaceFirst(prefix.prefix + EMPTY_SPACE_ONE, EMPTY_STRING) .split(EMPTY_SPACE_ONE + prefix.prefix + EMPTY_SPACE_ONE)); for(int i = 0; i < multipleArgList.size(); i++) { multipleArgList.set(i, multipleArgList.get(i).trim()); } return new HashSet<>(multipleArgList); } }
src/main/java/tars/logic/parser/ArgumentTokenizer.java
package tars.logic.parser; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeMap; /** * Tokenizes arguments string of the form: {@code preamble <prefix>value <prefix>value ...}<br> * e.g. {@code some preamble text /dt today at 3pm /t tag1 /t tag2 /ls} where prefixes are {@code /dt /t}.<br> * 1. An argument's value can be an empty string e.g. the value of {@code /ls} in the above example.<br> * 2. Leading and trailing whitespaces of an argument value will be discarded.<br> * 3. A prefix need to have leading and trailing spaces e.g. the {@code /d today at 3pm /t tag1} in the above example<br> * 4. An argument may be repeated and all its values will be accumulated e.g. the value of {@code /t} in the above example.<br> */ public class ArgumentTokenizer { private static final int INVALID_POS = -1; private static final int START_INDEX_POS = -1; private static final String EMPTY_SPACE_ONE = " "; private static final String EMPTY_STRING = ""; private final Prefix[] prefixes; private HashMap<Prefix, String> prefixValueMap; private TreeMap<Integer, Prefix> prefixPosMap; private String args; public ArgumentTokenizer(Prefix... prefixes) { this.prefixes = prefixes; init(); } public void tokenize(String args) { resetExtractorState(); this.args = args; this.prefixPosMap = getPrefixPositon(); extractArguments(); } private void init() { this.args = EMPTY_STRING; this.prefixValueMap = new HashMap<Prefix, String>(); this.prefixPosMap = new TreeMap<Integer, Prefix>(); } private void resetExtractorState() { this.prefixValueMap.clear(); } /** * Gets all prefix positions from arguments string */ private TreeMap<Integer, Prefix> getPrefixPositon() { prefixPosMap = new TreeMap<Integer, Prefix>(); for (int i = 0; i < prefixes.length; i++) { int curIndexPos = START_INDEX_POS; do { curIndexPos = args.indexOf(EMPTY_SPACE_ONE + prefixes[i].prefix, curIndexPos + 1); if (curIndexPos >= 0) { prefixPosMap.put(curIndexPos, prefixes[i]); } } while (curIndexPos >= 0); } return prefixPosMap; } /** * Extracts the option's prefix and arg from arguments string. */ private HashMap<Prefix, String> extractArguments() { prefixValueMap = new HashMap<Prefix, String>(); int endPos = args.length(); for (Map.Entry<Integer, Prefix> entry : prefixPosMap.descendingMap().entrySet()) { Prefix prefix = entry.getValue(); Integer pos = entry.getKey(); if (pos == INVALID_POS) { continue; } String arg = args.substring(pos, endPos).trim(); endPos = pos; if (prefixValueMap.containsKey(prefix)) { prefixValueMap.put(prefix, prefixValueMap.get(prefix).concat(EMPTY_SPACE_ONE).concat(arg)); } else { prefixValueMap.put(prefix, arg); } } return prefixValueMap; } public Optional<String> getValue(Prefix prefix) { if (!prefixValueMap.containsKey(prefix)) { return Optional.empty(); } return Optional.of(getMultipleValues(prefix).get().iterator().next().trim()); } public Optional<Set<String>> getMultipleValues(Prefix prefix) { if (!prefixValueMap.containsKey(prefix)) { return Optional.empty(); } return Optional.of(getMultipleFromArgs(prefixValueMap.get(prefix), prefix)); } public Optional<String> getMultipleRawValues(Prefix prefix) { if (!prefixValueMap.containsKey(prefix)) { return Optional.empty(); } return Optional.of(prefixValueMap.get(prefix).replaceAll(prefix.prefix + EMPTY_SPACE_ONE, EMPTY_STRING)); } public int numPrefixFound() { return prefixPosMap.size(); } public Optional<String> getPreamble() { if (args.trim().length() == 0) { return Optional.empty(); } if (prefixPosMap.size() == 0) { return Optional.of(args.trim()); } else if (prefixPosMap.firstKey() == 0) { return Optional.empty(); } return Optional.of(args.substring(0, prefixPosMap.firstKey()).trim()); } private Set<String> getMultipleFromArgs(String tagArguments, Prefix prefix) { // no tagArguments if (tagArguments.isEmpty()) { return Collections.emptySet(); } tagArguments = tagArguments.trim(); // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(prefix.prefix + EMPTY_SPACE_ONE, EMPTY_STRING) .split(EMPTY_SPACE_ONE + prefix.prefix + EMPTY_SPACE_ONE)); return new HashSet<>(tagStrings); } }
Fix bug Leading and trailing whitespaces of each argument value should be discarded.
src/main/java/tars/logic/parser/ArgumentTokenizer.java
Fix bug Leading and trailing whitespaces of each argument value should be discarded.
<ide><path>rc/main/java/tars/logic/parser/ArgumentTokenizer.java <ide> package tars.logic.parser; <ide> <ide> import java.util.Arrays; <del>import java.util.Collection; <ide> import java.util.Collections; <ide> import java.util.HashMap; <ide> import java.util.HashSet; <add>import java.util.List; <ide> import java.util.Map; <ide> import java.util.Optional; <ide> import java.util.Set; <ide> } <ide> <ide> tagArguments = tagArguments.trim(); <add> <ide> // replace first delimiter prefix, then split <del> final Collection<String> tagStrings = <del> Arrays.asList(tagArguments.replaceFirst(prefix.prefix + EMPTY_SPACE_ONE, EMPTY_STRING) <add> List<String> multipleArgList = Arrays <add> .asList(tagArguments.replaceFirst(prefix.prefix + EMPTY_SPACE_ONE, EMPTY_STRING) <ide> .split(EMPTY_SPACE_ONE + prefix.prefix + EMPTY_SPACE_ONE)); <del> return new HashSet<>(tagStrings); <add> <add> for(int i = 0; i < multipleArgList.size(); i++) { <add> multipleArgList.set(i, multipleArgList.get(i).trim()); <add> } <add> <add> return new HashSet<>(multipleArgList); <ide> } <ide> <ide> }
Java
mit
f779cf2221ddd436b43db985dd160bc23778568a
0
isi-nlp/tac-kbp-eal,BBN-E/tac-kbp-eal,isi-nlp/tac-kbp-eal,rgabbard-bbn/kbp-2014-event-arguments,rgabbard-bbn/kbp-2014-event-arguments,BBN-E/tac-kbp-eal
package com.bbn.kbp.events; import com.bbn.bue.common.Finishable; import com.bbn.bue.common.HasDocID; import com.bbn.bue.common.evaluation.AggregateBinaryFScoresInspector; import com.bbn.bue.common.evaluation.BinaryErrorLogger; import com.bbn.bue.common.evaluation.BinaryFScoreBootstrapStrategy; import com.bbn.bue.common.evaluation.BootstrapInspector; import com.bbn.bue.common.evaluation.EquivalenceBasedProvenancedAligner; import com.bbn.bue.common.evaluation.EvalPair; import com.bbn.bue.common.evaluation.InspectionNode; import com.bbn.bue.common.evaluation.InspectorTreeDSL; import com.bbn.bue.common.evaluation.InspectorTreeNode; import com.bbn.bue.common.evaluation.ProvenancedAlignment; import com.bbn.bue.common.files.FileUtils; import com.bbn.bue.common.parameters.Parameters; import com.bbn.bue.common.strings.offsets.CharOffset; import com.bbn.bue.common.strings.offsets.OffsetRange; import com.bbn.bue.common.symbols.Symbol; import com.bbn.bue.common.symbols.SymbolUtils; import com.bbn.kbp.events.ontology.EREToKBPEventOntologyMapper; import com.bbn.kbp.events.ontology.SimpleEventOntologyMapper; import com.bbn.kbp.events2014.AnswerKey; import com.bbn.kbp.events2014.AssessedResponse; import com.bbn.kbp.events2014.Response; import com.bbn.kbp.events2014.io.AnnotationStore; import com.bbn.kbp.events2014.io.AssessmentSpecFormats; import com.bbn.nlp.corenlp.CoreNLPConstituencyParse; import com.bbn.nlp.corenlp.CoreNLPDocument; import com.bbn.nlp.corenlp.CoreNLPParseNode; import com.bbn.nlp.corenlp.CoreNLPSentence; import com.bbn.nlp.corenlp.CoreNLPXMLLoader; import com.bbn.nlp.corpora.ere.EREArgument; import com.bbn.nlp.corpora.ere.EREDocument; import com.bbn.nlp.corpora.ere.EREEntity; import com.bbn.nlp.corpora.ere.EREEntityArgument; import com.bbn.nlp.corpora.ere.EREEntityMention; import com.bbn.nlp.corpora.ere.EREEvent; import com.bbn.nlp.corpora.ere.EREEventMention; import com.bbn.nlp.corpora.ere.EREFillerArgument; import com.bbn.nlp.corpora.ere.ERELoader; import com.bbn.nlp.events.HasEventType; import com.bbn.nlp.events.scoring.DocLevelEventArg; import com.bbn.nlp.parsing.HeadFinders; import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multiset; import com.google.common.io.Files; import com.google.common.reflect.TypeToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.Random; import static com.bbn.bue.common.evaluation.InspectorTreeDSL.inspect; import static com.bbn.bue.common.evaluation.InspectorTreeDSL.transformLeft; import static com.bbn.bue.common.evaluation.InspectorTreeDSL.transformRight; import static com.bbn.bue.common.evaluation.InspectorTreeDSL.transformed; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; /** * Scores KBP 2015 event argument output against an ERE gold standard. Scoring is in terms of * (Event Type, Event Role, Entity) tuples. This program is an experimental rough draft and has a * number of limitations: <ul> <li>We only handle arguments which are entity mentions; others are * ignored according to the ERE structure on the gold side and by filtering out a (currently * hardcoded) set of argument roles on the system side.</li> <i>We map system responses to entities * by looking for an entity which has a mention which shares the character offsets of the base * filler exactly either by itself or by its nominal head (given in ERE). In the future we may * implement more lenient alignment strategies.</i> <li> Currently system responses which fail to * align to any entity at all are discarded rather than penalized.</li> </ul> */ public final class ScoreKBPAgainstERE { private static final Logger log = LoggerFactory.getLogger(ScoreKBPAgainstERE.class); private ScoreKBPAgainstERE() { throw new UnsupportedOperationException(); } public static void main(String[] argv) { // we wrap the main method in this way to // ensure a non-zero return value on failure try { trueMain(argv); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private static void trueMain(String[] argv) throws IOException { Parameters params = Parameters.loadSerifStyle(new File(argv[0])); log.info(params.dump()); final ImmutableSet<Symbol> docIDsToScore = ImmutableSet.copyOf( FileUtils.loadSymbolList(params.getExistingFile("docIDsToScore"))); final ImmutableMap<Symbol, File> goldDocIDToFileMap = FileUtils.loadSymbolToFileMap( Files.asCharSource(params.getExistingFile("goldDocIDToFileMap"), Charsets.UTF_8)); final File outputDir = params.getCreatableDirectory("outputDir"); final AnnotationStore annStore = AssessmentSpecFormats.openAnnotationStore( params.getExistingDirectory("annotationStore"), AssessmentSpecFormats.Format.KBP2015); final ImmutableMap<Symbol, File> coreNLPProcessedRawDocs = FileUtils.loadSymbolToFileMap( Files.asCharSource(params.getExistingFile("coreNLPDocIDMap"), Charsets.UTF_8)); final boolean relaxUsingCORENLP = params.getBoolean("relaxUsingCoreNLP"); final boolean useExactMatchForCoreNLPRelaxation = relaxUsingCORENLP && params.getBoolean("useExactMatchForCoreNLPRelaxation"); final CoreNLPXMLLoader coreNLPXMLLoader = CoreNLPXMLLoader.builder(HeadFinders.<CoreNLPParseNode>getEnglishPTBHeadFinder()).build(); log.info("Scoring over {} documents", docIDsToScore.size()); // on the gold side we take an ERE document as input final TypeToken<EREDocument> inputIsEREDoc = new TypeToken<EREDocument>() { }; // on the test side we take an AnswerKey, but we bundle it with the gold ERE document // for use in alignment later final TypeToken<EREDocAndAnswerKey> inputIsEREDocAndAnswerKey = new TypeToken<EREDocAndAnswerKey>() { }; final InspectionNode<EvalPair<EREDocument, EREDocAndAnswerKey>> input = InspectorTreeDSL.pairedInput(inputIsEREDoc, inputIsEREDocAndAnswerKey); // these will extract the scoring tuples from the KBP system input and ERE docs, respectively // we create these here because we will call their .finish method()s // at the end to record some statistics about alignment failures, // so we need to keep references to them final DocLevelArgsFromKBPExtractor docLevelArgsFromKBPExtractor = new DocLevelArgsFromKBPExtractor(coreNLPProcessedRawDocs, coreNLPXMLLoader, relaxUsingCORENLP, useExactMatchForCoreNLPRelaxation); final DocLevelArgsFromEREExtractor docLevelArgsFromEREExtractor = new DocLevelArgsFromEREExtractor(EREToKBPEventOntologyMapper.create2015Mapping()); // this sets it up so that everything fed to input will be scored in various ways setupScoring(input, docLevelArgsFromKBPExtractor, docLevelArgsFromEREExtractor, outputDir); final ERELoader loader = ERELoader.create(); for (final Symbol docID : docIDsToScore) { final File ereFileName = goldDocIDToFileMap.get(docID); if (ereFileName == null) { throw new RuntimeException("Missing key file for " + docID); } final EREDocument ereDoc = loader.loadFrom(ereFileName); checkState(ereDoc.getDocId().equals(docID.asString()), "fetched document ID must be equal to stored"); final AnswerKey answerKey = annStore.read(docID).filter( KEEP_CORRECT_ANSWERS_OF_RELEVANT_ROLES_ONLY); // feed this ERE doc/ KBP output pair to the scoring network input.inspect(EvalPair.of(ereDoc, new EREDocAndAnswerKey(ereDoc, answerKey))); } // trigger the scoring network to write its summary files input.finish(); // log alignment failures docLevelArgsFromKBPExtractor.finish(); docLevelArgsFromEREExtractor.finish(); } private static final ImmutableSet<Symbol> BANNED_ROLES = SymbolUtils.setFrom("Time", "Crime", "Position", "Fine", "Sentence"); public static final AnswerKey.Filter KEEP_CORRECT_ANSWERS_OF_RELEVANT_ROLES_ONLY = new AnswerKey.Filter() { @Override public Predicate<AssessedResponse> assessedFilter() { return new Predicate<AssessedResponse>() { @Override public boolean apply(final AssessedResponse input) { return input.isCorrectUpToInexactJustifications() && !BANNED_ROLES.contains(input.response().role()); } }; } @Override public Predicate<Response> unassessedFilter() { return Predicates.alwaysFalse(); } }; private static Function<EvalPair<? extends Iterable<? extends DocLevelEventArg>, ? extends Iterable<? extends DocLevelEventArg>>, ProvenancedAlignment<DocLevelEventArg, DocLevelEventArg, DocLevelEventArg, DocLevelEventArg>> EXACT_MATCH_ALIGNER = EquivalenceBasedProvenancedAligner .forEquivalenceFunction(Functions.<DocLevelEventArg>identity()) .asFunction(); // this sets up a scoring network which is executed on every input private static void setupScoring( final InspectionNode<EvalPair<EREDocument, EREDocAndAnswerKey>> input, final DocLevelArgsFromKBPExtractor docLevelArgsFromKBPExtractor, final DocLevelArgsFromEREExtractor docLeveLArgsFromKBPExtractor, final File outputDir) { final InspectorTreeNode<EvalPair<ImmutableSet<DocLevelEventArg>, ImmutableSet<DocLevelEventArg>>> inputAsSetsOfScoringTuples = transformRight(transformLeft(input, docLeveLArgsFromKBPExtractor), docLevelArgsFromKBPExtractor); final InspectorTreeNode<ProvenancedAlignment<DocLevelEventArg, DocLevelEventArg, DocLevelEventArg, DocLevelEventArg>> alignmentNode = transformed(inputAsSetsOfScoringTuples, EXACT_MATCH_ALIGNER); // overall F score final AggregateBinaryFScoresInspector<Object, Object> scoreAndWriteOverallFScore = AggregateBinaryFScoresInspector.createOutputtingTo("aggregateF.txt", outputDir); inspect(alignmentNode).with(scoreAndWriteOverallFScore); // log errors final BinaryErrorLogger<HasDocID, HasDocID> logWrongAnswers = BinaryErrorLogger .forStringifierAndOutputDir(Functions.<HasDocID>toStringFunction(), outputDir); inspect(alignmentNode).with(logWrongAnswers); final BinaryFScoreBootstrapStrategy perEventBootstrapStrategy = BinaryFScoreBootstrapStrategy.createBrokenDownBy("EventType", HasEventType.ExtractFunction.INSTANCE, outputDir); final BootstrapInspector breakdownScoresByEventTypeWithBootstrapping = BootstrapInspector.forStrategy(perEventBootstrapStrategy, 1000, new Random(0)); inspect(alignmentNode).with(breakdownScoresByEventTypeWithBootstrapping); } private static final class DocLevelArgsFromEREExtractor implements Function<EREDocument, ImmutableSet<DocLevelEventArg>>, Finishable { // for tracking things from the answer key discarded due to not being entity mentions private final Multiset<String> allGoldArgs = HashMultiset.create(); private final Multiset<String> discarded = HashMultiset.create(); private final SimpleEventOntologyMapper mapper; private DocLevelArgsFromEREExtractor(final SimpleEventOntologyMapper mapper) { this.mapper = checkNotNull(mapper); } @Override public ImmutableSet<DocLevelEventArg> apply(final EREDocument doc) { final ImmutableSet.Builder<DocLevelEventArg> ret = ImmutableSet.builder(); for (final EREEvent ereEvent : doc.getEvents()) { for (final EREEventMention ereEventMention : ereEvent.getEventMentions()) { for (final EREArgument ereArgument : ereEventMention.getArguments()) { final Symbol ereEventMentionType = Symbol.from(ereEventMention.getType()); final Symbol ereEventMentionSubtype = Symbol.from(ereEventMention.getSubtype()); final Symbol ereArgumentRole = Symbol.from(ereArgument.getRole()); boolean skip = false; if (!mapper.eventType(ereEventMentionType).isPresent()) { log.debug("EventType {} is not known to the KBP ontology", ereEventMentionType); skip = true; } if (!mapper.eventRole(ereArgumentRole).isPresent()) { log.debug("EventRole {} is not known to the KBP ontology", ereArgumentRole); skip = true; } if (!mapper.eventSubtype(ereEventMentionSubtype).isPresent()) { log.debug("EventSubtype {} is not known to the KBP ontology", ereEventMentionSubtype); skip = true; } if (skip) { continue; } // type.subtype is Response format final String typeRoleKey = mapper.eventType(ereEventMentionType).get() + "." + mapper.eventSubtype(ereEventMentionSubtype).get() + "/" + mapper.eventRole(ereArgumentRole).get(); allGoldArgs.add(typeRoleKey); if (ereArgument instanceof EREEntityArgument) { final EREEntityMention entityMention = ((EREEntityArgument) ereArgument).entityMention(); final Optional<EREEntity> containingEntity = doc.getEntityContaining(entityMention); checkState(containingEntity.isPresent(), "Corrupt ERE key input lacks " + "entity for entity mention %s", entityMention); ret.add(DocLevelEventArg.create(Symbol.from(doc.getDocId()), Symbol.from(mapper.eventType(ereEventMentionType).get() + "." + mapper.eventSubtype(ereEventMentionSubtype).get()), mapper.eventRole(ereArgumentRole).get(), containingEntity.get().getID())); } else if (ereArgument instanceof EREFillerArgument) { // we don't currently handle non-entity mention arguments discarded.add(typeRoleKey); } else { throw new RuntimeException("Unknown ERE argument type " + ereArgument.getClass()); } } } } return ret.build(); } @Override public void finish() throws IOException { log.info( "Of {} gold event arguments, {} were discarded as non-entities", allGoldArgs.size(), discarded.size()); for (final String errKey : discarded.elementSet()) { if (discarded.count(errKey) > 0) { log.info("Of {} gold {} arguments, {} discarded ", +allGoldArgs.count(errKey), errKey, discarded.count(errKey)); } } } } private static final class DocLevelArgsFromKBPExtractor implements Function<EREDocAndAnswerKey, ImmutableSet<DocLevelEventArg>>, Finishable { private Multiset<String> mentionAlignmentFailures = HashMultiset.create(); private Multiset<String> numResponses = HashMultiset.create(); private final ImmutableMap<Symbol, File> ereMapping; private final CoreNLPXMLLoader coreNLPXMLLoader; private final boolean relaxUsingCORENLP; private final boolean useExactMatchForCoreNLPRelaxation; public DocLevelArgsFromKBPExtractor(final Map<Symbol, File> ereMapping, final CoreNLPXMLLoader coreNLPXMLLoader, final boolean relaxUsingCORENLP, final boolean useExactMatchForCoreNLPRelaxation) { this.ereMapping = ImmutableMap.copyOf(ereMapping); this.coreNLPXMLLoader = coreNLPXMLLoader; this.relaxUsingCORENLP = relaxUsingCORENLP; this.useExactMatchForCoreNLPRelaxation = useExactMatchForCoreNLPRelaxation; } public ImmutableSet<DocLevelEventArg> apply(final EREDocAndAnswerKey input) { final ImmutableSet.Builder<DocLevelEventArg> ret = ImmutableSet.builder(); final AnswerKey answerKey = input.answerKey(); final EREDocument doc = input.ereDoc(); final Symbol ereID = Symbol.from(doc.getDocId()); final Optional<CoreNLPDocument> coreNLPDoc; try { coreNLPDoc = Optional.fromNullable(ereMapping.get(ereID)).isPresent() ? Optional .of(coreNLPXMLLoader.loadFrom(ereMapping.get(ereID))) : Optional.<CoreNLPDocument>absent(); } catch (IOException e) { throw new RuntimeException(e); } for (final Response response: answerKey.allResponses()) { // we try to align a system response to an ERE entity by exact offset match of the // basefiller against one of an entity's mentions // this search could be faster but is probably good enough numResponses.add(errKey(response)); final OffsetRange<CharOffset> baseFillerOffsets = response.baseFiller().asCharOffsetRange(); EREEntity matchingEntity = null; for (final EREEntity entity : doc.getEntities()) { for (final EREEntityMention ereEntityMention : entity.getMentions()) { final OffsetRange<CharOffset> mentionRange = OffsetRange.charOffsetRange( ereEntityMention.getExtent().getStart(), ereEntityMention.getExtent().getEnd()); if (baseFillerOffsets.equals(mentionRange)) { matchingEntity = entity; break; } if (ereEntityMention.getHead().isPresent()) { final OffsetRange<CharOffset> headRange = OffsetRange.charOffsetRange( ereEntityMention.getHead().get().getStart(), ereEntityMention.getHead().get().getEnd()); if (baseFillerOffsets.equals(headRange)) { matchingEntity = entity; break; } if (coreNLPDoc.isPresent() && relaxUsingCORENLP) { final Optional<CoreNLPSentence> sent = coreNLPDoc.get().firstSentenceContaining(baseFillerOffsets); if (sent.isPresent()) { final Optional<CoreNLPParseNode> node = sent.get().nodeForOffsets(baseFillerOffsets); if (node.isPresent()) { final Optional<CoreNLPParseNode> terminalHead = node.get().terminalHead(); if (terminalHead.isPresent()) { // how strict do we want this to be? terminalHead.get().span(); final OffsetRange<CharOffset> ereHead = OffsetRange .charOffsetRange(ereEntityMention.getHead().get().getStart(), ereEntityMention.getHead().get().getEnd()); if ((useExactMatchForCoreNLPRelaxation && ereHead.equals(terminalHead.get().span())) || (!useExactMatchForCoreNLPRelaxation && ereHead.contains(terminalHead.get().span()))) { matchingEntity = entity; break; } } } } } } } } if (matchingEntity != null) { ret.add(DocLevelEventArg.create(Symbol.from(doc.getDocId()), response.type(), response.role(), matchingEntity.getID())); } else if (coreNLPDoc.isPresent() && relaxUsingCORENLP) { final String parseString; final Optional<CoreNLPSentence> sent = coreNLPDoc.get().firstSentenceContaining(baseFillerOffsets); if (sent.isPresent()) { final Optional<CoreNLPConstituencyParse> parse = sent.get().parse(); if (parse.isPresent()) { parseString = parse.get().coreNLPString(); } else { parseString = "no parse found!"; } } else { parseString = "no sentence found!"; } log.info( "Failed to align base filler with offsets {} to an ERE mention for response {}, parse tree is {}", baseFillerOffsets, response, parseString); mentionAlignmentFailures.add(errKey(response)); } else { log.info("Failed to align base filler with offsets {} to an ERE mention for response {}", baseFillerOffsets, response); mentionAlignmentFailures.add(errKey(response)); } } return ret.build(); } public String errKey(Response r) { return r.type() + "/" + r.role(); } public void finish() { log.info( "Of {} system responses, got {} mention alignment failures", numResponses.size(), mentionAlignmentFailures.size()); for (final String errKey : numResponses.elementSet()) { if (mentionAlignmentFailures.count(errKey) > 0) { log.info("Of {} {} responses, {} mention alignment failures", +numResponses.count(errKey), errKey, mentionAlignmentFailures.count(errKey)); } } } } } final class EREDocAndAnswerKey { private final EREDocument ereDoc; private final AnswerKey anwerKey; public EREDocAndAnswerKey(final EREDocument ereDoc, final AnswerKey anwerKey) { this.ereDoc = checkNotNull(ereDoc); this.anwerKey = checkNotNull(anwerKey); } public EREDocument ereDoc() { return ereDoc; } public AnswerKey answerKey() { return anwerKey; } }
tac-kbp-eal-scorer/src/main/java/com/bbn/kbp/events/ScoreKBPAgainstERE.java
package com.bbn.kbp.events; import com.bbn.bue.common.Finishable; import com.bbn.bue.common.HasDocID; import com.bbn.bue.common.evaluation.AggregateBinaryFScoresInspector; import com.bbn.bue.common.evaluation.BinaryErrorLogger; import com.bbn.bue.common.evaluation.BinaryFScoreBootstrapStrategy; import com.bbn.bue.common.evaluation.BootstrapInspector; import com.bbn.bue.common.evaluation.EquivalenceBasedProvenancedAligner; import com.bbn.bue.common.evaluation.EvalPair; import com.bbn.bue.common.evaluation.InspectionNode; import com.bbn.bue.common.evaluation.InspectorTreeDSL; import com.bbn.bue.common.evaluation.InspectorTreeNode; import com.bbn.bue.common.evaluation.ProvenancedAlignment; import com.bbn.bue.common.files.FileUtils; import com.bbn.bue.common.parameters.Parameters; import com.bbn.bue.common.strings.offsets.CharOffset; import com.bbn.bue.common.strings.offsets.OffsetRange; import com.bbn.bue.common.symbols.Symbol; import com.bbn.bue.common.symbols.SymbolUtils; import com.bbn.kbp.events.ontology.EREToKBPEventOntologyMapper; import com.bbn.kbp.events.ontology.SimpleEventOntologyMapper; import com.bbn.kbp.events2014.AnswerKey; import com.bbn.kbp.events2014.AssessedResponse; import com.bbn.kbp.events2014.Response; import com.bbn.kbp.events2014.io.AnnotationStore; import com.bbn.kbp.events2014.io.AssessmentSpecFormats; import com.bbn.nlp.corenlp.CoreNLPConstituencyParse; import com.bbn.nlp.corenlp.CoreNLPDocument; import com.bbn.nlp.corenlp.CoreNLPParseNode; import com.bbn.nlp.corenlp.CoreNLPSentence; import com.bbn.nlp.corenlp.CoreNLPXMLLoader; import com.bbn.nlp.corpora.ere.EREArgument; import com.bbn.nlp.corpora.ere.EREDocument; import com.bbn.nlp.corpora.ere.EREEntity; import com.bbn.nlp.corpora.ere.EREEntityArgument; import com.bbn.nlp.corpora.ere.EREEntityMention; import com.bbn.nlp.corpora.ere.EREEvent; import com.bbn.nlp.corpora.ere.EREEventMention; import com.bbn.nlp.corpora.ere.EREFillerArgument; import com.bbn.nlp.corpora.ere.ERELoader; import com.bbn.nlp.events.HasEventType; import com.bbn.nlp.events.scoring.DocLevelEventArg; import com.bbn.nlp.parsing.HeadFinders; import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multiset; import com.google.common.io.Files; import com.google.common.reflect.TypeToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.Random; import static com.bbn.bue.common.evaluation.InspectorTreeDSL.inspect; import static com.bbn.bue.common.evaluation.InspectorTreeDSL.transformLeft; import static com.bbn.bue.common.evaluation.InspectorTreeDSL.transformRight; import static com.bbn.bue.common.evaluation.InspectorTreeDSL.transformed; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; /** * Scores KBP 2015 event argument output against an ERE gold standard. Scoring is in terms of * (Event Type, Event Role, Entity) tuples. This program is an experimental rough draft and has a * number of limitations: <ul> <li>We only handle arguments which are entity mentions; others are * ignored according to the ERE structure on the gold side and by filtering out a (currently * hardcoded) set of argument roles on the system side.</li> <i>We map system responses to entities * by looking for an entity which has a mention which shares the character offsets of the base * filler exactly either by itself or by its nominal head (given in ERE). In the future we may * implement more lenient alignment strategies.</i> <li> Currently system responses which fail to * align to any entity at all are discarded rather than penalized.</li> </ul> */ public final class ScoreKBPAgainstERE { private static final Logger log = LoggerFactory.getLogger(ScoreKBPAgainstERE.class); private ScoreKBPAgainstERE() { throw new UnsupportedOperationException(); } public static void main(String[] argv) { // we wrap the main method in this way to // ensure a non-zero return value on failure try { trueMain(argv); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private static void trueMain(String[] argv) throws IOException { Parameters params = Parameters.loadSerifStyle(new File(argv[0])); log.info(params.dump()); final ImmutableSet<Symbol> docIDsToScore = ImmutableSet.copyOf( FileUtils.loadSymbolList(params.getExistingFile("docIDsToScore"))); final ImmutableMap<Symbol, File> goldDocIDToFileMap = FileUtils.loadSymbolToFileMap( Files.asCharSource(params.getExistingFile("goldDocIDToFileMap"), Charsets.UTF_8)); final File outputDir = params.getCreatableDirectory("outputDir"); final AnnotationStore annStore = AssessmentSpecFormats.openAnnotationStore( params.getExistingDirectory("annotationStore"), AssessmentSpecFormats.Format.KBP2015); final ImmutableMap<Symbol, File> coreNLPProcessedRawDocs = FileUtils.loadSymbolToFileMap( Files.asCharSource(params.getExistingFile("coreNLPDocIDMap"), Charsets.UTF_8)); final boolean relaxUsingCORENLP = params.getBoolean("relaxUsingCoreNLP"); final boolean useExactMatchForCoreNLPRelaxation = relaxUsingCORENLP && params.getBoolean("useExactMatchForCoreNLPRelaxation"); final CoreNLPXMLLoader coreNLPXMLLoader = CoreNLPXMLLoader.builder(HeadFinders.<CoreNLPParseNode>getEnglishPTBHeadFinder()).build(); log.info("Scoring over {} documents", docIDsToScore.size()); // on the gold side we take an ERE document as input final TypeToken<EREDocument> inputIsEREDoc = new TypeToken<EREDocument>() { }; // on the test side we take an AnswerKey, but we bundle it with the gold ERE document // for use in alignment later final TypeToken<EREDocAndAnswerKey> inputIsEREDocAndAnswerKey = new TypeToken<EREDocAndAnswerKey>() { }; final InspectionNode<EvalPair<EREDocument, EREDocAndAnswerKey>> input = InspectorTreeDSL.pairedInput(inputIsEREDoc, inputIsEREDocAndAnswerKey); // these will extract the scoring tuples from the KBP system input and ERE docs, respectively // we create these here because we will call their .finish method()s // at the end to record some statistics about alignment failures, // so we need to keep references to them final DocLevelArgsFromKBPExtractor docLevelArgsFromKBPExtractor = new DocLevelArgsFromKBPExtractor(coreNLPProcessedRawDocs, coreNLPXMLLoader, relaxUsingCORENLP, useExactMatchForCoreNLPRelaxation); final DocLevelArgsFromEREExtractor docLevelArgsFromEREExtractor = new DocLevelArgsFromEREExtractor(EREToKBPEventOntologyMapper.create2015Mapping()); // this sets it up so that everything fed to input will be scored in various ways setupScoring(input, docLevelArgsFromKBPExtractor, docLevelArgsFromEREExtractor, outputDir); final ERELoader loader = ERELoader.create(); for (final Symbol docID : docIDsToScore) { final File ereFileName = goldDocIDToFileMap.get(docID); if (ereFileName == null) { throw new RuntimeException("Missing key file for " + docID); } final EREDocument ereDoc = loader.loadFrom(ereFileName); checkState(ereDoc.getDocId().equals(docID.asString()), "fetched document ID must be equal to stored"); final AnswerKey answerKey = annStore.read(docID).filter( KEEP_CORRECT_ANSWERS_OF_RELEVANT_ROLES_ONLY); // feed this ERE doc/ KBP output pair to the scoring network input.inspect(EvalPair.of(ereDoc, new EREDocAndAnswerKey(ereDoc, answerKey))); } // trigger the scoring network to write its summary files input.finish(); // log alignment failures docLevelArgsFromKBPExtractor.finish(); docLevelArgsFromEREExtractor.finish(); } private static final ImmutableSet<Symbol> BANNED_ROLES = SymbolUtils.setFrom("Time", "Crime", "Position", "Fine", "Sentence"); public static final AnswerKey.Filter KEEP_CORRECT_ANSWERS_OF_RELEVANT_ROLES_ONLY = new AnswerKey.Filter() { @Override public Predicate<AssessedResponse> assessedFilter() { return new Predicate<AssessedResponse>() { @Override public boolean apply(final AssessedResponse input) { return input.isCorrectUpToInexactJustifications() && !BANNED_ROLES.contains(input.response().role()); } }; } @Override public Predicate<Response> unassessedFilter() { return Predicates.alwaysFalse(); } }; private static Function<EvalPair<? extends Iterable<? extends DocLevelEventArg>, ? extends Iterable<? extends DocLevelEventArg>>, ProvenancedAlignment<DocLevelEventArg, DocLevelEventArg, DocLevelEventArg, DocLevelEventArg>> EXACT_MATCH_ALIGNER = EquivalenceBasedProvenancedAligner .forEquivalenceFunction(Functions.<DocLevelEventArg>identity()) .asFunction(); // this sets up a scoring network which is executed on every input private static void setupScoring( final InspectionNode<EvalPair<EREDocument, EREDocAndAnswerKey>> input, final DocLevelArgsFromKBPExtractor docLevelArgsFromKBPExtractor, final DocLevelArgsFromEREExtractor docLeveLArgsFromKBPExtractor, final File outputDir) { final InspectorTreeNode<EvalPair<ImmutableSet<DocLevelEventArg>, ImmutableSet<DocLevelEventArg>>> inputAsSetsOfScoringTuples = transformRight(transformLeft(input, docLeveLArgsFromKBPExtractor), docLevelArgsFromKBPExtractor); final InspectorTreeNode<ProvenancedAlignment<DocLevelEventArg, DocLevelEventArg, DocLevelEventArg, DocLevelEventArg>> alignmentNode = transformed(inputAsSetsOfScoringTuples, EXACT_MATCH_ALIGNER); // overall F score final AggregateBinaryFScoresInspector<Object, Object> scoreAndWriteOverallFScore = AggregateBinaryFScoresInspector.createOutputtingTo("aggregateF.txt", outputDir); inspect(alignmentNode).with(scoreAndWriteOverallFScore); // log errors final BinaryErrorLogger<HasDocID, HasDocID> logWrongAnswers = BinaryErrorLogger .forStringifierAndOutputDir(Functions.<HasDocID>toStringFunction(), outputDir); inspect(alignmentNode).with(logWrongAnswers); final BinaryFScoreBootstrapStrategy perEventBootstrapStrategy = BinaryFScoreBootstrapStrategy.createBrokenDownBy("EventType", HasEventType.ExtractFunction.INSTANCE, outputDir); final BootstrapInspector breakdownScoresByEventTypeWithBootstrapping = BootstrapInspector.forStrategy(perEventBootstrapStrategy, 1000, new Random(0)); inspect(alignmentNode).with(breakdownScoresByEventTypeWithBootstrapping); } private static final class DocLevelArgsFromEREExtractor implements Function<EREDocument, ImmutableSet<DocLevelEventArg>>, Finishable { // for tracking things from the answer key discarded due to not being entity mentions private final Multiset<String> allGoldArgs = HashMultiset.create(); private final Multiset<String> discarded = HashMultiset.create(); private final SimpleEventOntologyMapper mapper; private DocLevelArgsFromEREExtractor(final SimpleEventOntologyMapper mapper) { this.mapper = checkNotNull(mapper); } @Override public ImmutableSet<DocLevelEventArg> apply(final EREDocument doc) { final ImmutableSet.Builder<DocLevelEventArg> ret = ImmutableSet.builder(); for (final EREEvent ereEvent : doc.getEvents()) { for (final EREEventMention ereEventMention : ereEvent.getEventMentions()) { for (final EREArgument ereArgument : ereEventMention.getArguments()) { final Symbol ereEventMentionType = Symbol.from(ereEventMention.getType()); final Symbol ereEventMentionSubtype = Symbol.from(ereEventMention.getSubtype()); final Symbol ereArgumentRole = Symbol.from(ereArgument.getRole()); boolean skip = false; if (!mapper.eventType(ereEventMentionType).isPresent()) { log.debug("EventType {} is not known to the KBP ontology", ereEventMentionType); skip = true; } if (!mapper.eventRole(ereArgumentRole).isPresent()) { log.debug("EventRole {} is not known to the KBP ontology", ereArgumentRole); skip = true; } if (!mapper.eventSubtype(ereEventMentionSubtype).isPresent()) { log.debug("EventSubtype {} is not known to the KBP ontology", ereEventMentionSubtype); skip = true; } if (skip) { continue; } // type.subtype is Response format final String typeRoleKey = mapper.eventType(ereEventMentionType).get() + "." + mapper.eventSubtype(ereEventMentionSubtype).get() + "/" + mapper.eventRole(ereArgumentRole).get(); allGoldArgs.add(typeRoleKey); if (ereArgument instanceof EREEntityArgument) { final EREEntityMention entityMention = ((EREEntityArgument) ereArgument).entityMention(); final Optional<EREEntity> containingEntity = doc.getEntityContaining(entityMention); checkState(containingEntity.isPresent(), "Corrupt ERE key input lacks " + "entity for entity mention %s", entityMention); ret.add(DocLevelEventArg.create(Symbol.from(doc.getDocId()), Symbol.from(mapper.eventType(ereEventMentionType).get() + "." + mapper.eventSubtype(ereEventMentionSubtype).get()), mapper.eventRole(ereArgumentRole).get(), containingEntity.get().getID())); } else if (ereArgument instanceof EREFillerArgument) { // we don't currently handle non-entity mention arguments discarded.add(typeRoleKey); } else { throw new RuntimeException("Unknown ERE argument type " + ereArgument.getClass()); } } } } return ret.build(); } @Override public void finish() throws IOException { log.info( "Of {} gold event arguments, {} were discarded as non-entities", allGoldArgs.size(), discarded.size()); for (final String errKey : discarded.elementSet()) { if (discarded.count(errKey) > 0) { log.info("Of {} gold {} arguments, {} discarded ", +allGoldArgs.count(errKey), errKey, discarded.count(errKey)); } } } } private static final class DocLevelArgsFromKBPExtractor implements Function<EREDocAndAnswerKey, ImmutableSet<DocLevelEventArg>>, Finishable { private Multiset<String> mentionAlignmentFailures = HashMultiset.create(); private Multiset<String> numResponses = HashMultiset.create(); private final ImmutableMap<Symbol, File> ereMapping; private final CoreNLPXMLLoader coreNLPXMLLoader; private final boolean relaxUsingCORENLP; private final boolean useExactMatchForCoreNLPRelaxation; public DocLevelArgsFromKBPExtractor(final Map<Symbol, File> ereMapping, final CoreNLPXMLLoader coreNLPXMLLoader, final boolean relaxUsingCORENLP, final boolean useExactMatchForCoreNLPRelaxation) { this.ereMapping = ImmutableMap.copyOf(ereMapping); this.coreNLPXMLLoader = coreNLPXMLLoader; this.relaxUsingCORENLP = relaxUsingCORENLP; this.useExactMatchForCoreNLPRelaxation = useExactMatchForCoreNLPRelaxation; } public ImmutableSet<DocLevelEventArg> apply(final EREDocAndAnswerKey input) { final ImmutableSet.Builder<DocLevelEventArg> ret = ImmutableSet.builder(); final AnswerKey answerKey = input.answerKey(); final EREDocument doc = input.ereDoc(); final Symbol ereID = Symbol.from(doc.getDocId()); final Optional<CoreNLPDocument> coreNLPDoc; try { coreNLPDoc = Optional.fromNullable(ereMapping.get(ereID)).isPresent() ? Optional .of(coreNLPXMLLoader.loadFrom(ereMapping.get(ereID))) : Optional.<CoreNLPDocument>absent(); } catch (IOException e) { throw new RuntimeException(e); } for (final AssessedResponse annResponse : answerKey.annotatedResponses()) { // we try to align a system response to an ERE entity by exact offset match of the // basefiller against one of an entity's mentions // this search could be faster but is probably good enough final Response response = annResponse.response(); numResponses.add(errKey(response)); final OffsetRange<CharOffset> baseFillerOffsets = response.baseFiller().asCharOffsetRange(); EREEntity matchingEntity = null; for (final EREEntity entity : doc.getEntities()) { for (final EREEntityMention ereEntityMention : entity.getMentions()) { final OffsetRange<CharOffset> mentionRange = OffsetRange.charOffsetRange( ereEntityMention.getExtent().getStart(), ereEntityMention.getExtent().getEnd()); if (baseFillerOffsets.equals(mentionRange)) { matchingEntity = entity; break; } if (ereEntityMention.getHead().isPresent()) { final OffsetRange<CharOffset> headRange = OffsetRange.charOffsetRange( ereEntityMention.getHead().get().getStart(), ereEntityMention.getHead().get().getEnd()); if (baseFillerOffsets.equals(headRange)) { matchingEntity = entity; break; } if (coreNLPDoc.isPresent() && relaxUsingCORENLP) { final Optional<CoreNLPSentence> sent = coreNLPDoc.get().firstSentenceContaining(baseFillerOffsets); if (sent.isPresent()) { final Optional<CoreNLPParseNode> node = sent.get().nodeForOffsets(baseFillerOffsets); if (node.isPresent()) { final Optional<CoreNLPParseNode> terminalHead = node.get().terminalHead(); if (terminalHead.isPresent()) { // how strict do we want this to be? terminalHead.get().span(); final OffsetRange<CharOffset> ereHead = OffsetRange .charOffsetRange(ereEntityMention.getHead().get().getStart(), ereEntityMention.getHead().get().getEnd()); if ((useExactMatchForCoreNLPRelaxation && ereHead.equals(terminalHead.get().span())) || (!useExactMatchForCoreNLPRelaxation && ereHead.contains(terminalHead.get().span()))) { matchingEntity = entity; break; } } } } } } } } if (matchingEntity != null) { ret.add(DocLevelEventArg.create(Symbol.from(doc.getDocId()), response.type(), response.role(), matchingEntity.getID())); } else if (coreNLPDoc.isPresent() && relaxUsingCORENLP) { final String parseString; final Optional<CoreNLPSentence> sent = coreNLPDoc.get().firstSentenceContaining(baseFillerOffsets); if (sent.isPresent()) { final Optional<CoreNLPConstituencyParse> parse = sent.get().parse(); if (parse.isPresent()) { parseString = parse.get().coreNLPString(); } else { parseString = "no parse found!"; } } else { parseString = "no sentence found!"; } log.info( "Failed to align base filler with offsets {} to an ERE mention for response {}, parse tree is {}", baseFillerOffsets, response, parseString); mentionAlignmentFailures.add(errKey(response)); } else { log.info("Failed to align base filler with offsets {} to an ERE mention for response {}", baseFillerOffsets, response); mentionAlignmentFailures.add(errKey(response)); } } return ret.build(); } public String errKey(Response r) { return r.type() + "/" + r.role(); } public void finish() { log.info( "Of {} system responses, got {} mention alignment failures", numResponses.size(), mentionAlignmentFailures.size()); for (final String errKey : numResponses.elementSet()) { if (mentionAlignmentFailures.count(errKey) > 0) { log.info("Of {} {} responses, {} mention alignment failures", +numResponses.count(errKey), errKey, mentionAlignmentFailures.count(errKey)); } } } } } final class EREDocAndAnswerKey { private final EREDocument ereDoc; private final AnswerKey anwerKey; public EREDocAndAnswerKey(final EREDocument ereDoc, final AnswerKey anwerKey) { this.ereDoc = checkNotNull(ereDoc); this.anwerKey = checkNotNull(anwerKey); } public EREDocument ereDoc() { return ereDoc; } public AnswerKey answerKey() { return anwerKey; } }
this does not need an actual assessed response
tac-kbp-eal-scorer/src/main/java/com/bbn/kbp/events/ScoreKBPAgainstERE.java
this does not need an actual assessed response
<ide><path>ac-kbp-eal-scorer/src/main/java/com/bbn/kbp/events/ScoreKBPAgainstERE.java <ide> } catch (IOException e) { <ide> throw new RuntimeException(e); <ide> } <del> for (final AssessedResponse annResponse : answerKey.annotatedResponses()) { <add> for (final Response response: answerKey.allResponses()) { <ide> // we try to align a system response to an ERE entity by exact offset match of the <ide> // basefiller against one of an entity's mentions <ide> // this search could be faster but is probably good enough <del> final Response response = annResponse.response(); <ide> numResponses.add(errKey(response)); <ide> final OffsetRange<CharOffset> baseFillerOffsets = response.baseFiller().asCharOffsetRange(); <ide>
Java
bsd-3-clause
eedd2e865dae23b063d98832d812b5081c87ed64
0
yungsters/rain-workload-toolkit,yungsters/rain-workload-toolkit,sguazt/rain-workload-toolkit,sguazt/rain-workload-toolkit,yungsters/rain-workload-toolkit,sguazt/rain-workload-toolkit
/* * Copyright (c) 2010, Regents of the University of California * 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 University of California, Berkeley * 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 OWNER 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. * * Author: Marco Guazzone ([email protected]), 2013. */ package radlab.rain.workload.rubis; import java.io.IOException; import java.util.ArrayList; import java.util.List; import radlab.rain.IScoreboard; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.message.BasicNameValuePair; import org.apache.http.NameValuePair; import radlab.rain.workload.rubis.model.RubisItem; import radlab.rain.workload.rubis.model.RubisUser; /** * Buy-Now-Item operation. * * Emulates the following requests: * 1. Click on the 'Buy-Now' link located in the item detail page * 2. Send user authentication (login name and password) * 3. Fill-in the form and click on the 'Buy now!' button, to buy the item * * @author Marco Guazzone ([email protected]) */ public class BuyNowItemOperation extends RubisOperation { public BuyNowItemOperation(boolean interactive, IScoreboard scoreboard) { super(interactive, scoreboard); this._operationName = "Buy Now Item"; this._operationIndex = RubisGenerator.BUY_NOW_ITEM_OP; } @Override public void execute() throws Throwable { StringBuilder response = null; // Generate a random item and perform a Buy-Now-Auth operation RubisItem item = this.getGenerator().generateItem(); if (!this.getGenerator().isValidItem(item)) { // Just print a warning, but do not set the operation as failed this.getLogger().warning("No valid item has been found. Operation interrupted."); this.setFailed(false); return; } // Click on the 'Buy-Now' link located in the item detail page URIBuilder uri = new URIBuilder(this.getGenerator().getBuyNowAuthURL()); uri.setParameter("itemId", Integer.toString(item.id)); HttpGet reqGet = new HttpGet(uri.build()); response = this.getHttpTransport().fetch(reqGet); this.trace(reqGet.getURI().toString()); if (!this.getGenerator().checkHttpResponse(response.toString())) { throw new IOException("Problems in performing request to URL: " + reqGet.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")"); } // Need a logged user RubisUser loggedUser = null; if (this.getGenerator().isUserLoggedIn()) { loggedUser = this.getGenerator().getLoggedUser(); } else { loggedUser = this.getGenerator().generateUser(); this.getGenerator().setLoggedUserId(loggedUser.id); } if (!this.getGenerator().isValidUser(loggedUser)) { // Just print a warning, but do not set the operation as failed this.getLogger().warning("No valid user has been found. Operation interrupted."); this.setFailed(false); return; } HttpPost reqPost = null; List<NameValuePair> form = null; UrlEncodedFormEntity entity = null; // Send user authentication (login name and password) reqPost = new HttpPost(this.getGenerator().getBuyNowURL()); form = new ArrayList<NameValuePair>(); form.add(new BasicNameValuePair("itemId", Integer.toString(item.id))); form.add(new BasicNameValuePair("nickname", loggedUser.nickname)); form.add(new BasicNameValuePair("password", loggedUser.password)); entity = new UrlEncodedFormEntity(form, "UTF-8"); reqPost.setEntity(entity); response = this.getHttpTransport().fetch(reqPost); this.trace(reqPost.getURI().toString()); if (!this.getGenerator().checkHttpResponse(response.toString())) { throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")"); } // Fill-in the form and click on the 'Buy now!' button, to buy the item reqPost = new HttpPost(this.getGenerator().getStoreBuyNowURL()); form = new ArrayList<NameValuePair>(); form.add(new BasicNameValuePair("itemId", Integer.toString(item.id))); form.add(new BasicNameValuePair("userId", Integer.toString(loggedUser.id))); String str = null; int maxQty = 1; str = RubisUtility.extractFormParamFromHtml(response.toString(), "maxQty"); if (str != null && !str.isEmpty()) { maxQty = Math.max(Integer.parseInt(str), maxQty); } form.add(new BasicNameValuePair("maxQty", Integer.toString(maxQty))); int qty = this.getRandomGenerator().nextInt(maxQty)+1; form.add(new BasicNameValuePair("qty", Integer.toString(qty))); entity = new UrlEncodedFormEntity(form, "UTF-8"); reqPost.setEntity(entity); response = this.getHttpTransport().fetch(reqPost); this.trace(reqPost.getURI().toString()); if (!this.getGenerator().checkHttpResponse(response.toString())) { throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")"); } this.setFailed(false); } }
src/radlab/rain/workload/rubis/BuyNowItemOperation.java
/* * Copyright (c) 2010, Regents of the University of California * 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 University of California, Berkeley * 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 OWNER 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. * * Author: Marco Guazzone ([email protected]), 2013. */ package radlab.rain.workload.rubis; import java.io.IOException; import java.util.ArrayList; import java.util.List; import radlab.rain.IScoreboard; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.message.BasicNameValuePair; import org.apache.http.NameValuePair; import radlab.rain.workload.rubis.model.RubisItem; import radlab.rain.workload.rubis.model.RubisUser; /** * Buy-Now-Item operation. * * Emulates the following requests: * 1. Click on the 'Buy-Now' link located in the item detail page * 2. Send user authentication (login name and password) * 3. Fill-in the form and click on the 'Buy now!' button, to buy the item * * @author Marco Guazzone ([email protected]) */ public class BuyNowItemOperation extends RubisOperation { public BuyNowItemOperation(boolean interactive, IScoreboard scoreboard) { super(interactive, scoreboard); this._operationName = "Buy Now Item"; this._operationIndex = RubisGenerator.BUY_NOW_ITEM_OP; } @Override public void execute() throws Throwable { StringBuilder response = null; // Generate a random item and perform a Buy-Now-Auth operation RubisItem item = this.getGenerator().generateItem(); if (!this.getGenerator().isValidItem(item)) { // Just print a warning, but do not set the operation as failed this.getLogger().warning("No valid item has been found. Operation interrupted."); this.setFailed(false); return; } // Click on the 'Buy-Now' link located in the item detail page URIBuilder uri = new URIBuilder(this.getGenerator().getBuyNowAuthURL()); uri.setParameter("itemId", Integer.toString(item.id)); HttpGet reqGet = new HttpGet(uri.build()); response = this.getHttpTransport().fetch(reqGet); this.trace(reqGet.getURI().toString()); if (!this.getGenerator().checkHttpResponse(response.toString())) { throw new IOException("Problems in performing request to URL: " + reqGet.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")"); } // Need a logged user RubisUser loggedUser = null; if (this.getGenerator().isUserLoggedIn()) { loggedUser = this.getGenerator().getLoggedUser(); } else { loggedUser = this.getGenerator().generateUser(); this.getGenerator().setLoggedUserId(loggedUser.id); } if (!this.getGenerator().isValidUser(loggedUser)) { // Just print a warning, but do not set the operation as failed this.getLogger().warning("No valid user has been found. Operation interrupted."); this.setFailed(false); return; } HttpPost reqPost = null; List<NameValuePair> form = null; UrlEncodedFormEntity entity = null; // Send user authentication (login name and password) reqPost = new HttpPost(this.getGenerator().getBuyNowURL()); form = new ArrayList<NameValuePair>(); form.add(new BasicNameValuePair("itemId", Integer.toString(item.id))); form.add(new BasicNameValuePair("nickname", loggedUser.nickname)); form.add(new BasicNameValuePair("password", loggedUser.password)); entity = new UrlEncodedFormEntity(form, "UTF-8"); reqPost.setEntity(entity); response = this.getHttpTransport().fetch(reqPost); this.trace(reqPost.getURI().toString()); if (!this.getGenerator().checkHttpResponse(response.toString())) { throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")"); } // Fill-in the form and click on the 'Buy now!' button, to buy the item reqPost = new HttpPost(this.getGenerator().getStoreBuyNowURL()); form = new ArrayList<NameValuePair>(); form.add(new BasicNameValuePair("itemId", Integer.toString(item.id))); form.add(new BasicNameValuePair("userId", Integer.toString(loggedUser.id))); int maxQty = Math.min(item.quantity, 1); form.add(new BasicNameValuePair("maxQty", Integer.toString(maxQty))); form.add(new BasicNameValuePair("qty", Integer.toString(this.getRandomGenerator().nextInt(maxQty)+1))); entity = new UrlEncodedFormEntity(form, "UTF-8"); reqPost.setEntity(entity); response = this.getHttpTransport().fetch(reqPost); this.trace(reqPost.getURI().toString()); if (!this.getGenerator().checkHttpResponse(response.toString())) { throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")"); } this.setFailed(false); } }
[rubis] (bug-fix:minor) In Buy-Now operation, forgot to parse maxQty from HTML response.
src/radlab/rain/workload/rubis/BuyNowItemOperation.java
[rubis] (bug-fix:minor) In Buy-Now operation, forgot to parse maxQty from HTML response.
<ide><path>rc/radlab/rain/workload/rubis/BuyNowItemOperation.java <ide> form = new ArrayList<NameValuePair>(); <ide> form.add(new BasicNameValuePair("itemId", Integer.toString(item.id))); <ide> form.add(new BasicNameValuePair("userId", Integer.toString(loggedUser.id))); <del> int maxQty = Math.min(item.quantity, 1); <add> String str = null; <add> int maxQty = 1; <add> str = RubisUtility.extractFormParamFromHtml(response.toString(), "maxQty"); <add> if (str != null && !str.isEmpty()) <add> { <add> maxQty = Math.max(Integer.parseInt(str), maxQty); <add> } <ide> form.add(new BasicNameValuePair("maxQty", Integer.toString(maxQty))); <del> form.add(new BasicNameValuePair("qty", Integer.toString(this.getRandomGenerator().nextInt(maxQty)+1))); <add> int qty = this.getRandomGenerator().nextInt(maxQty)+1; <add> form.add(new BasicNameValuePair("qty", Integer.toString(qty))); <ide> entity = new UrlEncodedFormEntity(form, "UTF-8"); <ide> reqPost.setEntity(entity); <ide> response = this.getHttpTransport().fetch(reqPost);
JavaScript
agpl-3.0
abc327e8e783aa5cd4adb49aee3d1c125e6e1c3b
0
denkbar/step,denkbar/step,denkbar/step,denkbar/step,denkbar/step
angular.module('seleniumPlugin',['step','functionsControllers']) .run(function(FunctionTypeRegistry) { //FunctionTypeRegistry.register('step.plugins.selenium.SeleniumFunction','Selenium','seleniumplugin/partials/selenium.html'); })
step-functions-plugins/step-functions-plugins-selenium/step-functions-plugins-selenium-controller-def/src/main/resources/step/plugins/selenium/webapp/js/selenium.js
angular.module('seleniumPlugin',['step','functionsControllers']) .run(function(FunctionTypeRegistry) { FunctionTypeRegistry.register('step.plugins.selenium.SeleniumFunction','Selenium','seleniumplugin/partials/selenium.html'); })
Disabling Selenium Plugin
step-functions-plugins/step-functions-plugins-selenium/step-functions-plugins-selenium-controller-def/src/main/resources/step/plugins/selenium/webapp/js/selenium.js
Disabling Selenium Plugin
<ide><path>tep-functions-plugins/step-functions-plugins-selenium/step-functions-plugins-selenium-controller-def/src/main/resources/step/plugins/selenium/webapp/js/selenium.js <ide> angular.module('seleniumPlugin',['step','functionsControllers']) <ide> <ide> .run(function(FunctionTypeRegistry) { <del> FunctionTypeRegistry.register('step.plugins.selenium.SeleniumFunction','Selenium','seleniumplugin/partials/selenium.html'); <add> //FunctionTypeRegistry.register('step.plugins.selenium.SeleniumFunction','Selenium','seleniumplugin/partials/selenium.html'); <ide> })
Java
apache-2.0
2f1259575f84c11948d0d461adf100a765138864
0
igorakkerman/jlib
package org.jlib.container.sequence.index.array.storage; /** * Strategy of capacity provision in a {@link LinearIndexStorage}. * * @author Igor Akkerman */ public interface LinearIndexStorageCapacityStrategy { /** * Asserts that the referenced {@link LinearIndexStorage} fits the specified * number of Items, adding the specified capacity at the head of the * {@link LinearIndexStorage}. The indices of all stored Items are * incremented, if necessary. * * @param fullCapacity * integer specifying the capacity * * @param headCapacity * integer specifying the size of the hole * * @throws LinearIndexStorageException * if {@code fullCapacity < 1 || * headCapacity < 0 || * headCapacity + linearIndexStorage.getItemsCount() > fullCapacity} */ public void assertCapacityWithHeadHole(final int fullCapacity, final int headCapacity) throws LinearIndexStorageException; /** * Asserts that the referenced {@link LinearIndexStorage} fits the specified * number of Items, adding the specified capacity in the middle of the * {@link LinearIndexStorage}. The indices of the stored Items stored after * the specified middle index are incremented. * * @param fullCapacity * integer specifying the capacity * * @param middleIndex * integer specifying the hole index * * @param middleCapacity * integer specifying the size of the hole * * @throws LinearIndexStorageException * if {@code fullCapacity < 1 || * middleIndex < linearIndexStorage.getFirstIndex() || middleIndex > linearIndexStorage.getLastIndex() || * middleCapacity < 0 || * linearIndexStorage.getLastItemIndex() + 1 + middleCapacity > fullCapacity} */ public void assertCapacityWithMiddleHole(final int fullCapacity, final int middleIndex, final int middleCapacity) throws LinearIndexStorageException; /** * Asserts that the referenced {@link LinearIndexStorage} fits the specified * number of Items, adding the specified capacity at the tail of the * {@link LinearIndexStorage}. The indices of all stored Items are left * unchanged. * * @param fullCapacity * integer specifying the capacity * * @param tailCapacity * integer specifying the size of the hole * * @throws LinearIndexStorageException * if {@code fullCapacity < 1 || * tailCapacity < 0 || * linearIndexStorage.getLastItemIndex() + 1 + tailCapacity > fullCapacity} */ public void assertCapacityWithTailHole(final int fullCapacity, final int tailCapacity) throws LinearIndexStorageException; }
jlib.container/src/main/java/org/jlib/container/sequence/index/array/storage/LinearIndexStorageCapacityStrategy.java
package org.jlib.container.sequence.index.array.storage; /** * Strategy of capacity provision in a {@link LinearIndexStorage}. * * @author Igor Akkerman */ public interface LinearIndexStorageCapacityStrategy { /** * Asserts that the referenced {@link LinearIndexStorage} fits the specified * number of Items, leaving a hole of the specified size in front of the * existing Items. The first index of the {@link LinearIndexStorage} is * decremented by the hole size. The indices of all existing Items are left * unchanged. * * @param capacity * integer specifying the capacity * * @param holeSize * integer specifying the size of the hole * * @throws LinearIndexStorageException * if {@code capacity < 1 || * holeSize < 0 || * holeSize + linearIndexStorage.getItemsCount() > capacity} */ public void assertCapacityWithHeadHole(final int capacity, final int holeSize) throws LinearIndexStorageException; /** * Asserts that the referenced {@link LinearIndexStorage} fits the specified * number of Items, leaving a hole of the specified size between the * existing Items. If necessary, the Items located behind the hole index are * moved behind the hole. * * @param capacity * integer specifying the capacity * * @param holeIndex * integer specifying the hole index * * @param holeSize * integer specifying the size of the hole * * @throws LinearIndexStorageException * if {@code capacity < 1 || * holeIndex < linearIndexStorage.getFirstIndex() || holeIndex > linearIndexStorage.getLastIndex() || * holeSize < 0 || * linearIndexStorage.getLastItemIndex() + 1 + holeSize > capacity} */ public void assertCapacityWithMiddleHole(final int capacity, final int holeIndex, final int holeSize) throws LinearIndexStorageException; /** * Asserts that the referenced {@link LinearIndexStorage} fits the specified * number of Items, leaving a hole of the specified size behind the existing * Items. The last index of the {@link LinearIndexStorage} is incremented by * the hole size. The indices of all existing Items are left unchanged. * * @param capacity * integer specifying the capacity * * @param holeSize * integer specifying the size of the hole * * @throws LinearIndexStorageException * if {@code capacity < 1 || * holeSize < 0 || * linearIndexStorage.getLastItemIndex() + 1 + holeSize > capacity} */ public void assertCapacityWithTailHole(final int capacity, final int holeSize) throws LinearIndexStorageException; }
LinearIndexStorageCapacityStrategy: old assert methods recreated, holes renamed
jlib.container/src/main/java/org/jlib/container/sequence/index/array/storage/LinearIndexStorageCapacityStrategy.java
LinearIndexStorageCapacityStrategy: old assert methods recreated, holes renamed
<ide><path>lib.container/src/main/java/org/jlib/container/sequence/index/array/storage/LinearIndexStorageCapacityStrategy.java <ide> <ide> /** <ide> * Asserts that the referenced {@link LinearIndexStorage} fits the specified <del> * number of Items, leaving a hole of the specified size in front of the <del> * existing Items. The first index of the {@link LinearIndexStorage} is <del> * decremented by the hole size. The indices of all existing Items are left <del> * unchanged. <add> * number of Items, adding the specified capacity at the head of the <add> * {@link LinearIndexStorage}. The indices of all stored Items are <add> * incremented, if necessary. <ide> * <del> * @param capacity <add> * @param fullCapacity <ide> * integer specifying the capacity <ide> * <del> * @param holeSize <add> * @param headCapacity <ide> * integer specifying the size of the hole <ide> * <ide> * @throws LinearIndexStorageException <del> * if {@code capacity < 1 || <del> * holeSize < 0 || <del> * holeSize + linearIndexStorage.getItemsCount() > capacity} <add> * if {@code fullCapacity < 1 || <add> * headCapacity < 0 || <add> * headCapacity + linearIndexStorage.getItemsCount() > fullCapacity} <ide> */ <del> public void assertCapacityWithHeadHole(final int capacity, final int holeSize) <add> public void assertCapacityWithHeadHole(final int fullCapacity, final int headCapacity) <ide> throws LinearIndexStorageException; <ide> <ide> /** <ide> * Asserts that the referenced {@link LinearIndexStorage} fits the specified <del> * number of Items, leaving a hole of the specified size between the <del> * existing Items. If necessary, the Items located behind the hole index are <del> * moved behind the hole. <add> * number of Items, adding the specified capacity in the middle of the <add> * {@link LinearIndexStorage}. The indices of the stored Items stored after <add> * the specified middle index are incremented. <ide> * <del> * @param capacity <add> * @param fullCapacity <ide> * integer specifying the capacity <ide> * <del> * @param holeIndex <add> * @param middleIndex <ide> * integer specifying the hole index <ide> * <del> * @param holeSize <add> * @param middleCapacity <ide> * integer specifying the size of the hole <ide> * <ide> * @throws LinearIndexStorageException <del> * if {@code capacity < 1 || <del> * holeIndex < linearIndexStorage.getFirstIndex() || holeIndex > linearIndexStorage.getLastIndex() || <del> * holeSize < 0 || <del> * linearIndexStorage.getLastItemIndex() + 1 + holeSize > capacity} <add> * if {@code fullCapacity < 1 || <add> * middleIndex < linearIndexStorage.getFirstIndex() || middleIndex > linearIndexStorage.getLastIndex() || <add> * middleCapacity < 0 || <add> * linearIndexStorage.getLastItemIndex() + 1 + middleCapacity > fullCapacity} <ide> */ <del> public void assertCapacityWithMiddleHole(final int capacity, final int holeIndex, final int holeSize) <add> public void assertCapacityWithMiddleHole(final int fullCapacity, final int middleIndex, final int middleCapacity) <ide> throws LinearIndexStorageException; <ide> <ide> /** <ide> * Asserts that the referenced {@link LinearIndexStorage} fits the specified <del> * number of Items, leaving a hole of the specified size behind the existing <del> * Items. The last index of the {@link LinearIndexStorage} is incremented by <del> * the hole size. The indices of all existing Items are left unchanged. <add> * number of Items, adding the specified capacity at the tail of the <add> * {@link LinearIndexStorage}. The indices of all stored Items are left <add> * unchanged. <ide> * <del> * @param capacity <add> * @param fullCapacity <ide> * integer specifying the capacity <ide> * <del> * @param holeSize <add> * @param tailCapacity <ide> * integer specifying the size of the hole <ide> * <ide> * @throws LinearIndexStorageException <del> * if {@code capacity < 1 || <del> * holeSize < 0 || <del> * linearIndexStorage.getLastItemIndex() + 1 + holeSize > capacity} <add> * if {@code fullCapacity < 1 || <add> * tailCapacity < 0 || <add> * linearIndexStorage.getLastItemIndex() + 1 + tailCapacity > fullCapacity} <ide> */ <del> public void assertCapacityWithTailHole(final int capacity, final int holeSize) <add> public void assertCapacityWithTailHole(final int fullCapacity, final int tailCapacity) <ide> throws LinearIndexStorageException; <ide> }
JavaScript
mit
115dce0f49076f62bdd14bf1a601b5e6254dfaf3
0
muut/riotjs,muut/riotjs
// allow to require('riot') const path = require('path'), fs = require('fs'), hasRiotPath = !!process.env.RIOT, riotPath = path.normalize(process.env.RIOT || path.join('..', '..', 'riot')), riot = require(riotPath), // simple-dom helper sdom = require('./sdom'), Module = require('module'), compiler = require('riot-compiler') // fix #2225 // rollup considers the riot.default key as default export value instead of what we export here delete riot.default // time riot should wait before throwing during an async rendering riot.settings.asyncRenderTimeout = 1000 /** * Function that will be used by riot.require and by require('some.tag') * @param { String } filename - path to the file to load and compile * @param { Object } opts - compiler options * @param { Object } context - context where the tag will be mounted (Module) */ function loadAndCompile(filename, opts, context) { const src = compiler.compile(fs.readFileSync(filename, 'utf8'), opts) const preTag = src.substring(0, src.indexOf('riot.tag')) const tagDefinition = src.substring(src.indexOf('riot.tag')) // here we will use template strings in [email protected] context._compile(` var riot = require('${ hasRiotPath ? riotPath : 'riot' }') ${ preTag } module.exports = ${ tagDefinition } `, filename) } /** * Enable the loading of riot tags with options riot.require('some.tag', { template: 'pug' }) * @param { String } filename - path to the file to load and compile * @param { Object } opts - compiler options * @returns { String } tag name */ function riotRequire(filename, opts) { var module = new Module() module.id = module.filename = filename loadAndCompile(filename, opts, module) return module.exports } // allow to require('some.tag') if (require.extensions) { require.extensions['.tag'] = function(module, filename) { loadAndCompile(filename, {}, module) } } /** * Get the html as string form any riot tag instance * @param { Tag } tag - riot tag instance * @returns { String } tag template */ function getTagHtml(tag) { return sdom.serialize(tag.root) } /** * Render riot tags returning a strings * @param { String } tagName - tag identifier * @param { Object } opts - options to pass to the tag * @returns { String } tag resulting template */ function render(tagName, opts) { var tag = render.tag(tagName, opts), html = getTagHtml(tag) // unmount the tag avoiding memory leaks tag.unmount() return html } /** * Render riot tags asynchronously * @param { String } tagName - tag identifier * @param { Object } opts - options to pass to the tag * @returns { Promise } a promise resolved with the tag template string */ function renderAsync(tagName, opts) { return Promise.race([ new Promise((resolve, reject) => { setTimeout(function() { reject(new Error(`Timeout error:: the tag "${ tagName }" didn't trigger the "ready" event during the rendering process`)) }, riot.settings.asyncRenderTimeout) }), new Promise(resolve => { var tag = render.tag(tagName, opts) tag.on('ready', function() { var html = getTagHtml(tag) tag.unmount() resolve(html) }) }) ]) } // extend the render function with some static methods render.dom = function(tagName, opts) { return riot.render.tag(tagName, opts).root } render.tag = function(tagName, opts) { var root = document.createElement(tagName), tag = riot.mount(root, opts)[0] return tag } // extend the riot api adding some useful serverside methods module.exports = exports.default = Object.assign(riot, { // allow to require('riot').compile compile: compiler.compile, parsers: compiler.parsers, require: riotRequire, render, renderAsync })
lib/server/index.js
// allow to require('riot') const path = require('path'), fs = require('fs'), hasRiotPath = !!process.env.RIOT, riotPath = path.normalize(process.env.RIOT || path.resolve(__dirname, '..', '..', 'riot')), riot = require(riotPath), // simple-dom helper sdom = require('./sdom'), Module = require('module'), compiler = require('riot-compiler') // fix #2225 // rollup considers the riot.default key as default export value instead of what we export here delete riot.default // time riot should wait before throwing during an async rendering riot.settings.asyncRenderTimeout = 1000 /** * Function that will be used by riot.require and by require('some.tag') * @param { String } filename - path to the file to load and compile * @param { Object } opts - compiler options * @param { Object } context - context where the tag will be mounted (Module) */ function loadAndCompile(filename, opts, context) { const src = compiler.compile(fs.readFileSync(filename, 'utf8'), opts) const preTag = src.substring(0, src.indexOf('riot.tag')) const tagDefinition = src.substring(src.indexOf('riot.tag')) // here we will use template strings in [email protected] context._compile(` var riot = require('${ hasRiotPath ? riotPath : 'riot' }') ${ preTag } module.exports = ${ tagDefinition } `, filename) } /** * Enable the loading of riot tags with options riot.require('some.tag', { template: 'pug' }) * @param { String } filename - path to the file to load and compile * @param { Object } opts - compiler options * @returns { String } tag name */ function riotRequire(filename, opts) { var module = new Module() module.id = module.filename = filename loadAndCompile(filename, opts, module) return module.exports } // allow to require('some.tag') require.extensions['.tag'] = function(module, filename) { loadAndCompile(filename, {}, module) } /** * Get the html as string form any riot tag instance * @param { Tag } tag - riot tag instance * @returns { String } tag template */ function getTagHtml(tag) { return sdom.serialize(tag.root) } /** * Render riot tags returning a strings * @param { String } tagName - tag identifier * @param { Object } opts - options to pass to the tag * @returns { String } tag resulting template */ function render(tagName, opts) { var tag = render.tag(tagName, opts), html = getTagHtml(tag) // unmount the tag avoiding memory leaks tag.unmount() return html } /** * Render riot tags asynchronously * @param { String } tagName - tag identifier * @param { Object } opts - options to pass to the tag * @returns { Promise } a promise resolved with the tag template string */ function renderAsync(tagName, opts) { return Promise.race([ new Promise((resolve, reject) => { setTimeout(function() { reject(new Error(`Timeout error:: the tag "${ tagName }" didn't trigger the "ready" event during the rendering process`)) }, riot.settings.asyncRenderTimeout) }), new Promise(resolve => { var tag = render.tag(tagName, opts) tag.on('ready', function() { var html = getTagHtml(tag) tag.unmount() resolve(html) }) }) ]) } // extend the render function with some static methods render.dom = function(tagName, opts) { return riot.render.tag(tagName, opts).root } render.tag = function(tagName, opts) { var root = document.createElement(tagName), tag = riot.mount(root, opts)[0] return tag } // extend the riot api adding some useful serverside methods module.exports = exports.default = Object.assign(riot, { // allow to require('riot').compile compile: compiler.compile, parsers: compiler.parsers, require: riotRequire, render, renderAsync })
Relative Pathing and checking for require.extensions In lib/server/index.js, we use path.resolve(__dirname, '..', '..', 'riot') to access the relative path of riot.js . path.join('..', '..', 'riot') seems more appropriate for a relative path inside a module. Additionally in lib/server/index.js , we attempt to modify require.extensions[.tag], however, that is not ideal both because someone might have already replqced require (eg: SystemJS) and/or because require.extensions is deprecated. For now, putting an if (require.extensions) around the code at least guards us from a runtime exception, although this may not be the ideal solution because we don't have a replacement for the fact that .tag files won't be able to be required like this. But maybe that's okay because if you are in this problem state, you are using something like Webpack or JSPM which has their own loader for .tag files?
lib/server/index.js
Relative Pathing and checking for require.extensions
<ide><path>ib/server/index.js <ide> path = require('path'), <ide> fs = require('fs'), <ide> hasRiotPath = !!process.env.RIOT, <del> riotPath = path.normalize(process.env.RIOT || path.resolve(__dirname, '..', '..', 'riot')), <add> riotPath = path.normalize(process.env.RIOT || path.join('..', '..', 'riot')), <ide> riot = require(riotPath), <ide> // simple-dom helper <ide> sdom = require('./sdom'), <ide> } <ide> <ide> // allow to require('some.tag') <del>require.extensions['.tag'] = function(module, filename) { <del> loadAndCompile(filename, {}, module) <add>if (require.extensions) { <add> require.extensions['.tag'] = function(module, filename) { <add> loadAndCompile(filename, {}, module) <add> } <ide> } <ide> <ide> /**
Java
apache-2.0
85641534568372e949e5f8d40741f6453c6a08c6
0
ssaarela/javersion,ssaarela/javersion,ssaarela/javersion
/* * Copyright 2013 Samppa Saarela * * 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. */ package org.javersion.reflect; import static com.google.common.collect.Sets.newHashSet; import static org.assertj.core.api.Assertions.*; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; import org.junit.Test; import com.google.common.base.Predicate; public class TypeDescriptorTest { static final TypeDescriptors TYPES = new TypeDescriptors(); static final TypeDescriptors STATIC_FIELDS = new TypeDescriptors(input -> Modifier.isStatic(input.getModifiers())); public static class Cycle { Cycle cycle; public Cycle() { throw new IllegalArgumentException(); } } public enum E { EVAL } public static class Generic { Map<String, Long> map; Map<String, Map<String, Long>> mapOfMaps; } private final Class<?>[] expectedSuperClasses = { LinkedHashMap.class, HashMap.class, AbstractMap.class, Object.class }; private final Class<?>[] expectedInterfaces = { Map.class, Cloneable.class, Serializable.class }; @Test public void Get_Super_Classes() { TypeDescriptor type = TYPES.get(LinkedHashMap.class); Set<Class<?>> superClasses = type.getSuperClasses(); assertThat(superClasses).contains(expectedSuperClasses); } @Test public void Get_Interfaces() { TypeDescriptor type = TYPES.get(LinkedHashMap.class); Set<Class<?>> superClasses = type.getInterfaces(); assertThat(superClasses).contains(expectedInterfaces); } @Test public void Get_Fields() { TypeDescriptor type = TYPES.get(ArrayList.class); assertThat(type.getFields().keySet()).isEqualTo((Set<String>) newHashSet( "elementData", "size", "modCount")); } @Test public void to_string() { TypeDescriptor type = TYPES.get(Cycle.class); assertThat(type.toString()).isEqualTo("org.javersion.reflect.TypeDescriptorTest$Cycle"); type = TYPES.get(TypeDescriptorTest.class); assertThat(type.toString()).isEqualTo("org.javersion.reflect.TypeDescriptorTest"); } @Test public void simple_name() { TypeDescriptor type = TYPES.get(Cycle.class); assertThat(type.getSimpleName()).isEqualTo("TypeDescriptorTest$Cycle"); type = TYPES.get(TypeDescriptorTest.class); assertThat(type.getSimpleName()).isEqualTo("TypeDescriptorTest"); } @Test public void raw_type_equality_check() { TypeDescriptor setType = TYPES.get(Set.class); assertThat(setType.equalTo(Set.class)).isTrue(); assertThat(setType.equalTo(Collection.class)).isFalse(); } @Test public void field_existence_check() { TypeDescriptor type = TYPES.get(FieldDescriptorTest.class); assertThat(type.hasField("privateField")).isTrue(); assertThat(type.hasField("foobar")).isFalse(); } @Test(expected = IllegalArgumentException.class) public void field_not_found() { TypeDescriptor type = TYPES.get(FieldDescriptorTest.class); type.getField("foobar"); } @Test public void get_element_returns_raw_type() { assertThat(TYPES.get(Set.class).getElement()).isEqualTo(Set.class); } @Test public void create_instance() { TypeDescriptor type = TYPES.get(TypeDescriptorTest.class); TypeDescriptorTest instance = (TypeDescriptorTest) type.newInstance(); assertThat(instance).isNotSameAs(this); } @Test(expected = ReflectionException.class) public void constructor_not_found() { TypeDescriptor type = TYPES.get(FieldDescriptor.class); type.newInstance(); } @Test(expected = ReflectionException.class) public void construction_exception() { TypeDescriptor type = TYPES.get(Cycle.class); type.newInstance(); } @Test public void enum_check() { TypeDescriptor type = TYPES.get(FieldDescriptor.class); assertThat(type.isEnum()).isFalse(); type = TYPES.get(E.class); assertThat(type.isEnum()).isTrue(); } @Test public void super_type_check() { TypeDescriptor setType = TYPES.get(Set.class); assertThat(setType.isSuperTypeOf(Collection.class)).isFalse(); assertThat(setType.isSuperTypeOf(Set.class)).isTrue(); assertThat(setType.isSuperTypeOf(SortedSet.class)).isTrue(); assertThat(setType.isSuperTypeOf(TreeSet.class)).isTrue(); } @Test public void sub_type_check() { TypeDescriptor setType = TYPES.get(Set.class); assertThat(setType.isSubTypeOf(Collection.class)).isTrue(); assertThat(setType.isSubTypeOf(Set.class)).isTrue(); assertThat(setType.isSubTypeOf(SortedSet.class)).isFalse(); } @Test public void not_equal() { assertThat(TypeDescriptors.getTypeDescriptor(Object.class)).isNotEqualTo(new Object()); } @Test(expected = IllegalArgumentException.class) public void get_type_descriptor_of_null() { TypeDescriptors.getTypeDescriptor(null); } @Test public void primitive_or_wrapper() { TypeDescriptor type = TYPES.get(Cycle.class); assertThat(type.isPrimitiveOrWrapper()).isFalse(); type = TYPES.get(int.class); assertThat(type.isPrimitiveOrWrapper()).isTrue(); type = TYPES.get(Boolean.class); assertThat(type.isPrimitiveOrWrapper()).isTrue(); type = TYPES.get(String.class); assertThat(type.isPrimitiveOrWrapper()).isFalse(); } @Test public void Recursive_Identity() { TypeDescriptor type = TYPES.get(Cycle.class); FieldDescriptor field = type.getField("cycle"); TypeDescriptor fieldType = field.getType(); FieldDescriptor fieldTypeField = fieldType.getField("cycle"); assertThat(type.hashCode()).isEqualTo(fieldType.hashCode()); assertThat(field.hashCode()).isEqualTo(fieldTypeField.hashCode()); assertThat(type).isEqualTo(fieldType); assertThat(field).isEqualTo(fieldTypeField); } @Test public void Generic_Identity() { TypeDescriptor type = TYPES.get(Generic.class); FieldDescriptor mapField = type.getField("map"); FieldDescriptor mapOfMapsField = type.getField("mapOfMaps"); assertThat(mapField.getType()).isNotEqualTo(mapOfMapsField.getType()); TypeDescriptor mapOfMapsValueType = mapOfMapsField.getType().resolveGenericParameter(Map.class, 1); assertThat(mapField.getType()).isEqualTo(mapOfMapsValueType); } @Test(expected=RuntimeException.class) public void Unmodifiable_All_Classes() { TYPES.get(LinkedHashMap.class).getAllClasses().add(TypeDescriptorTest.class); } @Test(expected=RuntimeException.class) public void Unmodifiable_Interfaces() { TYPES.get(LinkedHashMap.class).getInterfaces().add(TypeDescriptorTest.class); } @Test(expected=RuntimeException.class) public void Unmodifiable_Super_Classes() { TYPES.get(LinkedHashMap.class).getSuperClasses().add(TypeDescriptorTest.class); } @Test(expected=RuntimeException.class) public void Unmodifiable_Fields() { TYPES.get(ArrayList.class).getFields().remove("elementData"); } @Test public void Resolve_Generic_Parameter() { FieldDescriptor fieldDescriptor = STATIC_FIELDS.get(getClass()).getField("TYPES"); TypeDescriptor fieldType = fieldDescriptor.getType(); assertThat(fieldType.resolveGenericParameter(AbstractTypeDescriptors.class, 0)) .isEqualTo(STATIC_FIELDS.get(FieldDescriptor.class)); assertThat(fieldType.resolveGenericParameter(AbstractTypeDescriptors.class, 1)) .isEqualTo(STATIC_FIELDS.get(TypeDescriptor.class)); } }
javersion-reflect/src/test/java/org/javersion/reflect/TypeDescriptorTest.java
/* * Copyright 2013 Samppa Saarela * * 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. */ package org.javersion.reflect; import static com.google.common.collect.Sets.newHashSet; import static org.assertj.core.api.Assertions.*; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; import org.junit.Test; import com.google.common.base.Predicate; public class TypeDescriptorTest { static final TypeDescriptors TYPES = new TypeDescriptors(); static final TypeDescriptors STATIC_FIELDS = new TypeDescriptors(input -> Modifier.isStatic(input.getModifiers())); public static class Cycle { Cycle cycle; public Cycle() { throw new IllegalArgumentException(); } } public enum E { EVAL } public static class Generic { Map<String, Long> map; Map<String, Map<String, Long>> mapOfMaps; } private final Class<?>[] expectedSuperClasses = { LinkedHashMap.class, HashMap.class, AbstractMap.class, Object.class }; private final Class<?>[] expectedInterfaces = { Map.class, Cloneable.class, Serializable.class }; @Test public void Get_Super_Classes() { TypeDescriptor type = TYPES.get(LinkedHashMap.class); Set<Class<?>> superClasses = type.getSuperClasses(); assertThat(superClasses).contains(expectedSuperClasses); } @Test public void Get_Interfaces() { TypeDescriptor type = TYPES.get(LinkedHashMap.class); Set<Class<?>> superClasses = type.getInterfaces(); assertThat(superClasses).contains(expectedInterfaces); } @Test public void Get_Fields() { TypeDescriptor type = TYPES.get(ArrayList.class); assertThat(type.getFields().keySet()).isEqualTo((Set<String>) newHashSet( "elementData", "size", "modCount")); } @Test public void to_string() { TypeDescriptor type = TYPES.get(Cycle.class); assertThat(type.toString()).isEqualTo("org.javersion.reflect.TypeDescriptorTest$Cycle"); type = TYPES.get(TypeDescriptorTest.class); assertThat(type.toString()).isEqualTo("org.javersion.reflect.TypeDescriptorTest"); } @Test public void simple_name() { TypeDescriptor type = TYPES.get(Cycle.class); assertThat(type.getSimpleName()).isEqualTo("TypeDescriptorTest$Cycle"); type = TYPES.get(TypeDescriptorTest.class); assertThat(type.getSimpleName()).isEqualTo("TypeDescriptorTest"); } @Test public void raw_type_equality_check() { TypeDescriptor setType = TYPES.get(Set.class); assertThat(setType.equalTo(Set.class)).isTrue(); assertThat(setType.equalTo(Collection.class)).isFalse(); } @Test public void field_existence_check() { TypeDescriptor type = TYPES.get(FieldDescriptorTest.class); assertThat(type.hasField("privateField")).isTrue(); assertThat(type.hasField("foobar")).isFalse(); } @Test(expected = IllegalArgumentException.class) public void field_not_found() { TypeDescriptor type = TYPES.get(FieldDescriptorTest.class); type.getField("foobar"); } @Test public void get_element_returns_raw_type() { assertThat(TYPES.get(Set.class).getElement()).isEqualTo(Set.class); } @Test public void create_instance() { TypeDescriptor type = TYPES.get(TypeDescriptorTest.class); TypeDescriptorTest instance = (TypeDescriptorTest) type.newInstance(); assertThat(instance).isNotSameAs(this); } @Test(expected = ReflectionException.class) public void constructor_not_found() { TypeDescriptor type = TYPES.get(FieldDescriptor.class); type.newInstance(); } @Test(expected = ReflectionException.class) public void construction_exception() { TypeDescriptor type = TYPES.get(Cycle.class); type.newInstance(); } @Test public void enum_check() { TypeDescriptor type = TYPES.get(FieldDescriptor.class); assertThat(type.isEnum()).isFalse(); type = TYPES.get(E.class); assertThat(type.isEnum()).isTrue(); } @Test public void super_type_check() { TypeDescriptor setType = TYPES.get(Set.class); assertThat(setType.isSuperTypeOf(Collection.class)).isFalse(); assertThat(setType.isSuperTypeOf(Set.class)).isTrue(); assertThat(setType.isSuperTypeOf(SortedSet.class)).isTrue(); assertThat(setType.isSuperTypeOf(TreeSet.class)).isTrue(); } @Test public void sub_type_check() { TypeDescriptor setType = TYPES.get(Set.class); assertThat(setType.isSubTypeOf(Collection.class)).isTrue(); assertThat(setType.isSubTypeOf(Set.class)).isTrue(); assertThat(setType.isSubTypeOf(SortedSet.class)).isFalse(); } @Test public void not_equal() { assertThat(TYPES.get(Object.class)).isNotEqualTo(new Object()); } @Test public void primitive_or_wrapper() { TypeDescriptor type = TYPES.get(Cycle.class); assertThat(type.isPrimitiveOrWrapper()).isFalse(); type = TYPES.get(int.class); assertThat(type.isPrimitiveOrWrapper()).isTrue(); type = TYPES.get(Boolean.class); assertThat(type.isPrimitiveOrWrapper()).isTrue(); type = TYPES.get(String.class); assertThat(type.isPrimitiveOrWrapper()).isFalse(); } @Test public void Recursive_Identity() { TypeDescriptor type = TYPES.get(Cycle.class); FieldDescriptor field = type.getField("cycle"); TypeDescriptor fieldType = field.getType(); FieldDescriptor fieldTypeField = fieldType.getField("cycle"); assertThat(type.hashCode()).isEqualTo(fieldType.hashCode()); assertThat(field.hashCode()).isEqualTo(fieldTypeField.hashCode()); assertThat(type).isEqualTo(fieldType); assertThat(field).isEqualTo(fieldTypeField); } @Test public void Generic_Identity() { TypeDescriptor type = TYPES.get(Generic.class); FieldDescriptor mapField = type.getField("map"); FieldDescriptor mapOfMapsField = type.getField("mapOfMaps"); assertThat(mapField.getType()).isNotEqualTo(mapOfMapsField.getType()); TypeDescriptor mapOfMapsValueType = mapOfMapsField.getType().resolveGenericParameter(Map.class, 1); assertThat(mapField.getType()).isEqualTo(mapOfMapsValueType); } @Test(expected=RuntimeException.class) public void Unmodifiable_All_Classes() { TYPES.get(LinkedHashMap.class).getAllClasses().add(TypeDescriptorTest.class); } @Test(expected=RuntimeException.class) public void Unmodifiable_Interfaces() { TYPES.get(LinkedHashMap.class).getInterfaces().add(TypeDescriptorTest.class); } @Test(expected=RuntimeException.class) public void Unmodifiable_Super_Classes() { TYPES.get(LinkedHashMap.class).getSuperClasses().add(TypeDescriptorTest.class); } @Test(expected=RuntimeException.class) public void Unmodifiable_Fields() { TYPES.get(ArrayList.class).getFields().remove("elementData"); } @Test public void Resolve_Generic_Parameter() { FieldDescriptor fieldDescriptor = STATIC_FIELDS.get(getClass()).getField("TYPES"); TypeDescriptor fieldType = fieldDescriptor.getType(); assertThat(fieldType.resolveGenericParameter(AbstractTypeDescriptors.class, 0)) .isEqualTo(STATIC_FIELDS.get(FieldDescriptor.class)); assertThat(fieldType.resolveGenericParameter(AbstractTypeDescriptors.class, 1)) .isEqualTo(STATIC_FIELDS.get(TypeDescriptor.class)); } }
Full (practical) line coverage for reflection module
javersion-reflect/src/test/java/org/javersion/reflect/TypeDescriptorTest.java
Full (practical) line coverage for reflection module
<ide><path>aversion-reflect/src/test/java/org/javersion/reflect/TypeDescriptorTest.java <ide> <ide> @Test <ide> public void not_equal() { <del> assertThat(TYPES.get(Object.class)).isNotEqualTo(new Object()); <add> assertThat(TypeDescriptors.getTypeDescriptor(Object.class)).isNotEqualTo(new Object()); <add> } <add> <add> @Test(expected = IllegalArgumentException.class) <add> public void get_type_descriptor_of_null() { <add> TypeDescriptors.getTypeDescriptor(null); <ide> } <ide> <ide> @Test
Java
mit
e4987c511b8e5d68c352d897ff755ff16f504119
0
fr1kin/ForgeHax,fr1kin/ForgeHax
package com.matt.forgehax.mods.services; import static com.matt.forgehax.Helper.getLocalPlayer; import com.google.common.util.concurrent.FutureCallback; import com.matt.forgehax.asm.events.PacketEvent; import com.matt.forgehax.events.ChatMessageEvent; import com.matt.forgehax.util.entity.PlayerInfo; import com.matt.forgehax.util.entity.PlayerInfoHelper; import com.matt.forgehax.util.mod.ServiceMod; import com.matt.forgehax.util.mod.loader.RegisterMod; import com.mojang.authlib.GameProfile; import java.util.function.BiConsumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; import joptsimple.internal.Strings; import net.minecraft.client.network.NetworkPlayerInfo; import net.minecraft.network.play.server.SPacketChat; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; /** Created on 7/18/2017 by fr1kin */ @RegisterMod public class ChatIdentifierService extends ServiceMod { // should split into two groups: group 1: senders name. group 2: message private static final Pattern[] MESSAGE_PATTERNS = { Pattern.compile("<(.*?)> (.*)"), // vanilla }; private static final Pattern[] INCOMING_PRIVATE_MESSAGES = { Pattern.compile("(.*?) whispers to you: (.*)"), // vanilla Pattern.compile("(.*?) whispers: (.*)"), // 2b2t }; private static final Pattern[] OUTGOING_PRIVATE_MESSAGES = { Pattern.compile("[Tt]o (.*?): (.*)"), // 2b2t and vanilla i think }; public ChatIdentifierService() { super("ChatIdentifierService", "Listens to incoming chat messages and identifies the sender"); } private static boolean extract( String message, Pattern[] patterns, BiConsumer<GameProfile, String> callback) { for (Pattern pattern : patterns) { Matcher matcher = pattern.matcher(message); if (matcher.find()) { final String messageSender = matcher.group(1); final String messageOnly = matcher.group(2); if (!Strings.isNullOrEmpty(messageSender)) { for (NetworkPlayerInfo data : getLocalPlayer().connection.getPlayerInfoMap()) { if (String.CASE_INSENSITIVE_ORDER.compare( messageSender, data.getGameProfile().getName()) == 0) { callback.accept(data.getGameProfile(), messageOnly); return true; } } } } } return false; } @SuppressWarnings("Duplicates") @SubscribeEvent public void onChatMessage(PacketEvent.Incoming.Pre event) { if (getLocalPlayer() == null || getLocalPlayer().connection == null) return; else if (event.getPacket() instanceof SPacketChat) { SPacketChat packet = (SPacketChat) event.getPacket(); String message = packet.getChatComponent().getUnformattedText(); if (!Strings.isNullOrEmpty(message)) { // normal public messages if (extract( message, MESSAGE_PATTERNS, (senderProfile, msg) -> { PlayerInfoHelper.registerWithCallback( senderProfile.getName(), new FutureCallback<PlayerInfo>() { @Override public void onSuccess(@Nullable PlayerInfo result) { if (result != null) MinecraftForge.EVENT_BUS.post(ChatMessageEvent.newPublicChat(result, msg)); } @Override public void onFailure(Throwable t) { PlayerInfoHelper.generateOfflineWithCallback(senderProfile.getName(), this); } }); })) return; // private messages to the local player if (extract( message, INCOMING_PRIVATE_MESSAGES, (senderProfile, msg) -> { PlayerInfoHelper.registerWithCallback( senderProfile.getName(), new FutureCallback<PlayerInfo>() { @Override public void onSuccess(final @Nullable PlayerInfo sender) { // now get the local player if (sender != null) PlayerInfoHelper.registerWithCallback( getLocalPlayer().getName(), new FutureCallback<PlayerInfo>() { @Override public void onSuccess(@Nullable PlayerInfo result) { if (result != null) MinecraftForge.EVENT_BUS.post( ChatMessageEvent.newPrivateChat(sender, result, msg)); } @Override public void onFailure(Throwable t) { PlayerInfoHelper.generateOfflineWithCallback( getLocalPlayer().getName(), this); } }); } @Override public void onFailure(Throwable t) { PlayerInfoHelper.generateOfflineWithCallback(senderProfile.getName(), this); } }); })) return; // outgoing pms from local player if (extract( message, OUTGOING_PRIVATE_MESSAGES, (receiverProfile, msg) -> { PlayerInfoHelper.registerWithCallback( receiverProfile.getName(), new FutureCallback<PlayerInfo>() { @Override public void onSuccess(final @Nullable PlayerInfo receiver) { // now get the local player if (receiver != null) PlayerInfoHelper.registerWithCallback( getLocalPlayer().getName(), new FutureCallback<PlayerInfo>() { @Override public void onSuccess(@Nullable PlayerInfo sender) { if (sender != null) MinecraftForge.EVENT_BUS.post( ChatMessageEvent.newPrivateChat(sender, receiver, msg)); } @Override public void onFailure(Throwable t) { PlayerInfoHelper.generateOfflineWithCallback( getLocalPlayer().getName(), this); } }); } @Override public void onFailure(Throwable t) { PlayerInfoHelper.generateOfflineWithCallback(receiverProfile.getName(), this); } }); })) return; // if reached here then the message is unrecognized } } } }
src/main/java/com/matt/forgehax/mods/services/ChatIdentifierService.java
package com.matt.forgehax.mods.services; import static com.matt.forgehax.Helper.getLocalPlayer; import com.google.common.util.concurrent.FutureCallback; import com.matt.forgehax.asm.events.PacketEvent; import com.matt.forgehax.events.ChatMessageEvent; import com.matt.forgehax.util.entity.PlayerInfo; import com.matt.forgehax.util.entity.PlayerInfoHelper; import com.matt.forgehax.util.mod.ServiceMod; import com.matt.forgehax.util.mod.loader.RegisterMod; import com.mojang.authlib.GameProfile; import java.util.function.BiConsumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; import joptsimple.internal.Strings; import net.minecraft.client.network.NetworkPlayerInfo; import net.minecraft.network.play.server.SPacketChat; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; /** Created on 7/18/2017 by fr1kin */ @RegisterMod public class ChatIdentifierService extends ServiceMod { // should split into two groups: group 1: senders name. group 2: message private static final Pattern[] MESSAGE_PATTERNS = { Pattern.compile("<(.*?)> (.*)"), // vanilla }; private static final Pattern[] INCOMING_PRIVATE_MESSAGES = { Pattern.compile("(.*?) whispers to you: (.*)"), // vanilla Pattern.compile("(.*?) whispers: (.*)"), // 2b2t }; private static final Pattern[] OUTGOING_PRIVATE_MESSAGES = { Pattern.compile("[Tt]o (.*?): (.*)"), // 2b2t and vanilla i think }; public ChatIdentifierService() { super("ChatIdentifierService", "Listens to incoming chat messages and identifies the sender"); } private static boolean extract( String message, Pattern[] patterns, BiConsumer<GameProfile, String> callback) { for (Pattern pattern : patterns) { Matcher matcher = pattern.matcher(message); if (matcher.find()) { final String messageSender = matcher.group(1); final String messageOnly = matcher.group(2); if (!Strings.isNullOrEmpty(messageSender)) { for (NetworkPlayerInfo data : getLocalPlayer().connection.getPlayerInfoMap()) { if (String.CASE_INSENSITIVE_ORDER.compare( messageSender, data.getGameProfile().getName()) == 0) { callback.accept(data.getGameProfile(), messageOnly); return true; } } } } } return false; } @SuppressWarnings("Duplicates") @SubscribeEvent public void onChatMessage(PacketEvent.Incoming.Pre event) { if(getLocalPlayer() == null || getLocalPlayer().connection == null) return; else if (event.getPacket() instanceof SPacketChat) { SPacketChat packet = (SPacketChat) event.getPacket(); String message = packet.getChatComponent().getUnformattedText(); if (!Strings.isNullOrEmpty(message)) { // normal public messages if (extract( message, MESSAGE_PATTERNS, (senderProfile, msg) -> { PlayerInfoHelper.registerWithCallback( senderProfile.getName(), new FutureCallback<PlayerInfo>() { @Override public void onSuccess(@Nullable PlayerInfo result) { if (result != null) MinecraftForge.EVENT_BUS.post(ChatMessageEvent.newPublicChat(result, msg)); } @Override public void onFailure(Throwable t) { PlayerInfoHelper.generateOfflineWithCallback(senderProfile.getName(), this); } }); })) return; // private messages to the local player if (extract( message, INCOMING_PRIVATE_MESSAGES, (senderProfile, msg) -> { PlayerInfoHelper.registerWithCallback( senderProfile.getName(), new FutureCallback<PlayerInfo>() { @Override public void onSuccess(final @Nullable PlayerInfo sender) { // now get the local player if (sender != null) PlayerInfoHelper.registerWithCallback( getLocalPlayer().getName(), new FutureCallback<PlayerInfo>() { @Override public void onSuccess(@Nullable PlayerInfo result) { if (result != null) MinecraftForge.EVENT_BUS.post( ChatMessageEvent.newPrivateChat(sender, result, msg)); } @Override public void onFailure(Throwable t) { PlayerInfoHelper.generateOfflineWithCallback( getLocalPlayer().getName(), this); } }); } @Override public void onFailure(Throwable t) { PlayerInfoHelper.generateOfflineWithCallback(senderProfile.getName(), this); } }); })) return; // outgoing pms from local player if (extract( message, OUTGOING_PRIVATE_MESSAGES, (receiverProfile, msg) -> { PlayerInfoHelper.registerWithCallback( receiverProfile.getName(), new FutureCallback<PlayerInfo>() { @Override public void onSuccess(final @Nullable PlayerInfo receiver) { // now get the local player if (receiver != null) PlayerInfoHelper.registerWithCallback( getLocalPlayer().getName(), new FutureCallback<PlayerInfo>() { @Override public void onSuccess(@Nullable PlayerInfo sender) { if (sender != null) MinecraftForge.EVENT_BUS.post( ChatMessageEvent.newPrivateChat(sender, receiver, msg)); } @Override public void onFailure(Throwable t) { PlayerInfoHelper.generateOfflineWithCallback( getLocalPlayer().getName(), this); } }); } @Override public void onFailure(Throwable t) { PlayerInfoHelper.generateOfflineWithCallback(receiverProfile.getName(), this); } }); })) return; // if reached here then the message is unrecognized } } } }
ran spotless
src/main/java/com/matt/forgehax/mods/services/ChatIdentifierService.java
ran spotless
<ide><path>rc/main/java/com/matt/forgehax/mods/services/ChatIdentifierService.java <ide> @SuppressWarnings("Duplicates") <ide> @SubscribeEvent <ide> public void onChatMessage(PacketEvent.Incoming.Pre event) { <del> if(getLocalPlayer() == null || getLocalPlayer().connection == null) <del> return; <add> if (getLocalPlayer() == null || getLocalPlayer().connection == null) return; <ide> else if (event.getPacket() instanceof SPacketChat) { <ide> SPacketChat packet = (SPacketChat) event.getPacket(); <ide> String message = packet.getChatComponent().getUnformattedText();
Java
mit
65ce2619de599d9e698507315ecfaef19a0e6db0
0
chenichadowitz/intelligent-chess-engine
package ice; import java.util.*; @SuppressWarnings("unchecked") public abstract class Board { Player whitePlayer; Player blackPlayer; protected boolean playersTurn = true; // whiteturn if true protected ArrayList<Piece> pieces = new ArrayList<Piece>(); protected LinkedList<Piece>[][] boardState = (LinkedList<Piece>[][]) new LinkedList[8][8]; public boolean getTurn(){ return playersTurn;} public ArrayList<Piece> getPieces(){ return pieces;} public LinkedList<Piece>[][] getBoardState(){ return boardState;} public boolean[] statusOfSquare(int[] square){ boolean[] squareStatus = {false,true}; //possible returns are: //true,true = occupied by white piece //true,false = occupied by black piece //false,true = unoccupied on board //false,false = unoccupied off board if(square[0] < 0 || square[1] < 0 || square[0] > 7 || square[1] > 7){ squareStatus[1] = false; return squareStatus; } else{ for(int searcher = 0; searcher < pieces.size(); searcher ++){ if (Arrays.equals(pieces.get(searcher).getPosition(), square)){ squareStatus[0] = true; squareStatus[1] = pieces.get(searcher).getColor(); return squareStatus; } } } return squareStatus; } public void switchTurn(){playersTurn = !playersTurn;} public void update(int[] square){ LinkedList<Piece> temp = new LinkedList<Piece>(); for(Piece p : boardState[square[0]][square[1]]){ temp.add(p); } for(Piece currentPiece: temp){ currentPiece.removeFromBoardState(); currentPiece.generateMoves(); currentPiece.addToBoardState(); } } public void display(){ Piece current; int[] place = new int[2]; for(int i=7;i>=0;i--){ System.out.print(i+1 + " "); for(int j=0;j<8;j++){ place[0] = j; place[1] = i; current = pieceAt(place); if(current == null){ System.out.print("-- "); } else { System.out.print(current+" "); } } System.out.println(); } System.out.println(" a b c d e f g h"); } public void buildBoardState(){ LinkedList<Piece> dummy = new LinkedList<Piece>(); for(int i=0; i<8; i++){ for(int j=0; j<8; j++){ boardState[i][j] = dummy; } } for(Piece currentPiece: this.getPieces()){ currentPiece.generateMoves(); currentPiece.addToBoardState(); } } public Piece pieceAt(int[] square){ for(Piece currentPiece: pieces){ if(Arrays.equals(currentPiece.getPosition(), square)){ return currentPiece; } } return null; //no piece at square !!!BOOM!!! } public void takePiece(Piece taken){ taken.removeFromBoardState(); taken.setPosition(null); taken.setBoard(null); pieces.remove(taken); } abstract boolean movePiece(int[] squareAB); public String toString(){ return "board"; } }
src/ice/Board.java
package ice; import java.util.*; public abstract class Board { Player whitePlayer; Player blackPlayer; protected boolean playersTurn = true; // whiteturn if true protected ArrayList<Piece> pieces = new ArrayList<Piece>(); protected LinkedList<Piece>[][] boardState = (LinkedList<Piece>[][]) new LinkedList[8][8]; public boolean getTurn(){ return playersTurn;} public ArrayList<Piece> getPieces(){ return pieces;} public LinkedList<Piece>[][] getBoardState(){ return boardState;} public boolean[] statusOfSquare(int[] square){ boolean[] squareStatus = {false,true}; //possible returns are: //true,true = occupied by white piece //true,false = occupied by black piece //false,true = unoccupied on board //false,false = unoccupied off board if(square[0] < 0 || square[1] < 0 || square[0] > 7 || square[1] > 7){ squareStatus[1] = false; return squareStatus; } else{ for(int searcher = 0; searcher < pieces.size(); searcher ++){ if (Arrays.equals(pieces.get(searcher).getPosition(), square)){ squareStatus[0] = true; squareStatus[1] = pieces.get(searcher).getColor(); return squareStatus; } } } return squareStatus; } public void switchTurn(){playersTurn = !playersTurn;} public void update(int[] square){ LinkedList<Piece> temp = new LinkedList<Piece>(); for(Piece p : boardState[square[0]][square[1]]){ temp.add(p); } for(Piece currentPiece: temp){ currentPiece.removeFromBoardState(); currentPiece.generateMoves(); currentPiece.addToBoardState(); } } public void display(){ Piece current; int[] place = new int[2]; for(int i=7;i>=0;i--){ System.out.print(i+1 + " "); for(int j=0;j<8;j++){ place[0] = j; place[1] = i; current = pieceAt(place); if(current == null){ System.out.print("-- "); } else { System.out.print(current+" "); } } System.out.println(); } System.out.println(" a b c d e f g h"); } public void buildBoardState(){ LinkedList<Piece> dummy = new LinkedList<Piece>(); for(int i=0; i<8; i++){ for(int j=0; j<8; j++){ boardState[i][j] = dummy; } } for(Piece currentPiece: this.getPieces()){ currentPiece.generateMoves(); currentPiece.addToBoardState(); } } public Piece pieceAt(int[] square){ for(Piece currentPiece: pieces){ if(Arrays.equals(currentPiece.getPosition(), square)){ return currentPiece; } } return null; //no piece at square !!!BOOM!!! } public void takePiece(Piece taken){ taken.removeFromBoardState(); taken.setPosition(null); taken.setBoard(null); pieces.remove(taken); } abstract boolean movePiece(int[] squareAB); public String toString(){ return "board"; } }
- removed type-cast warning
src/ice/Board.java
- removed type-cast warning
<ide><path>rc/ice/Board.java <ide> package ice; <ide> import java.util.*; <ide> <add>@SuppressWarnings("unchecked") <ide> public abstract class Board { <ide> Player whitePlayer; <ide> Player blackPlayer;
Java
apache-2.0
ee983ea032b533a8f7fb74736fec14e40b5caeb0
0
arquivo/functional-tests,arquivo/functional-tests
package pt.fccn.mobile.arquivo.pages; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class AdvancedSearchPage { private final WebDriver driver; private final String topicsToSearch = "expo 98"; private final String negTerm = "concerto"; private final String expressionTerm = "\"pavilhao da utopia\""; private final String[ ] terms = new String[ ]{ "pavilhao da utopia", "pavilhao", "da", "utopia", "expo" , "98" }; private final String siteSearch = "www.arquivo.pt"; private final int timeout = 50; public AdvancedSearchPage( WebDriver driver ) { this.driver = driver; try { Thread.sleep( 5000 ); //wait for page to load } catch( InterruptedException ex ) { Thread.currentThread( ).interrupt( ); } // Check that we're on the right page. String pageTitle= driver.getTitle( ); System.out.println( "pageTile = " + pageTitle ); } public boolean checkSiteOperator( String language ) { System.out.println( "[checkSiteOperator]" ); String inputSearch = "//*[@id=\"adv_and\"]"; String divExpandable = "//*[@id=\"domains\"]/legend/i"; String inputSiteSearch = "//*[@id=\"site\"]"; String buttonSearch = "//*[@id=\"btnSubmitBottom\"]"; try{ if( language.equals( "EN" ) ) { switchLanguage( ); } if( searchSiteSearch( inputSearch , inputSiteSearch , divExpandable , buttonSearch ) ) return true; else return false; } catch( NoSuchElementException e ) { System.out.println( "Error in checkOPSite" ); e.printStackTrace( ); return false; } } private boolean searchSiteSearch( String inputSearch, String inputSiteSearch, String divExpandable, String buttonSearch ) { System.out.println( "[searchSiteSearch]" ); System.out.println( "Search for " + topicsToSearch ); WebElement elementSearch = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputSearch ) ) ); elementSearch.clear( ); elementSearch.sendKeys( topicsToSearch ); WebElement divElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( divExpandable ) ) ); divElement.click( ); sleepThread( ); System.out.println( "Search for site \"" + siteSearch+ "\"" ); WebElement elementExpression = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputSiteSearch ) ) ); elementExpression.clear( ); elementExpression.sendKeys( siteSearch ); WebElement btnSubmitElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( buttonSearch ) ) ); btnSubmitElement.click( ); sleepThread( ); if( !checkSiteResults( siteSearch ) ) return false; return true; } private boolean checkSiteResults( String siteSearch ) { System.out.println( "[AdvancedSearch][checkSiteResults]" ); String getURLResults = "//*[@id=\"resultados-lista\"]/ul/li/div[1]"; String domainSearch = expandURL( siteSearch.toLowerCase( ).trim( ) ); try{ List< WebElement > results = ( new WebDriverWait( driver, timeout ) ) .until( ExpectedConditions .visibilityOfAllElementsLocatedBy( By.xpath( getURLResults ) ) ); System.out.println( "results size = " + results.size( ) ); for( WebElement elem : results ) { String url = elem.getText( ).toLowerCase( ).trim( ); String treatedURL = expandURL( url ); System.out.println( "[AdvancedSearch][checkSiteResults] domainSearch["+domainSearch+"] equals treatedURL["+treatedURL+"]" ); if( !domainSearch.equals( treatedURL ) ) return false; } return true; } catch( NoSuchElementException e ){ System.out.println( "Error in checkOPSite" ); e.printStackTrace( ); return false; } } public boolean checkAdvancedSearch( String language ) { System.out.println( "[checkAdvancedSearch]" ); String inputSearch = "//*[@id=\"adv_and\"]"; String inputExpression = "//*[@id=\"adv_phr\"]"; String inputNeg = "//*[@id=\"adv_not\"]"; String buttonSearch = "//*[@id=\"btnSubmitBottom\"]"; try{ if( language.equals( "EN" ) ) { switchLanguage( ); if( searchFullTextEN( inputSearch , inputExpression , inputNeg , buttonSearch ) ) return true; else return false; } else if( searchFullTextPT( inputSearch , inputExpression , inputNeg , buttonSearch ) ) return true; else return false; } catch( NoSuchElementException e ) { System.out.println( "Error in checkOPSite" ); e.printStackTrace( ); return false; } } private boolean searchFullTextPT( String inputSearch , String inputExpression , String inputNeg , String buttonSearch ) { System.out.println( "[searchFullTextPT]" ); System.out.println( "Search for " + topicsToSearch ); WebElement elementSearch = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputSearch ) ) ); elementSearch.clear( ); elementSearch.sendKeys( topicsToSearch ); System.out.println( "Search for expression \"" + expressionTerm+ "\"" ); WebElement elementExpression = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputExpression ) ) ); elementExpression.clear( ); elementExpression.sendKeys( expressionTerm ); System.out.println( "Search for denial operator -" + negTerm ); WebElement elementNeg = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputNeg ) ) ); elementNeg.clear( ); elementNeg.sendKeys( negTerm ); sleepThread( ); WebElement btnSubmitElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( buttonSearch ) ) ); btnSubmitElement.click( ); sleepThread( ); if( !checkResults( terms ) ) return false; return true; } private boolean searchFullTextEN( String inputSearch , String inputExpression , String inputNeg , String buttonSearch ) { System.out.println( "[AdvancedTest][searchEN]" ); System.out.println( "Search for " + topicsToSearch ); WebElement elementSearch = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputSearch ) ) ); elementSearch.clear( ); elementSearch.sendKeys( topicsToSearch ); System.out.println( "Search for expression \"" + expressionTerm+ "\"" ); WebElement elementExpression = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputExpression ) ) ); elementExpression.clear( ); elementExpression.sendKeys( expressionTerm ); System.out.println( "Search for denial operator -" + negTerm ); WebElement elementNeg = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputNeg ) ) ); elementNeg.clear( ); elementNeg.sendKeys( negTerm ); sleepThread( ); WebElement btnSubmitElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( buttonSearch ) ) ); btnSubmitElement.click( ); sleepThread( ); if( !checkResults( terms ) ) return false; return true; } private boolean checkResults( String[ ] terms ) { System.out.println( "[AdvancedSearch][checkResults]" ); String getResumeResults = "//*[@id=\"resultados-lista\"]/ul/li/span[1]/em"; boolean checkTerm = false; try{ List< WebElement > results = ( new WebDriverWait( driver, timeout ) ) .until( ExpectedConditions .visibilityOfAllElementsLocatedBy( By.xpath( getResumeResults ) ) ); System.out.println( "results size = " + results.size( ) ); for( WebElement elem : results ) { String boldText = elem.getText( ).toLowerCase( ).trim( ); for( String term : terms ){ System.out.println( "[AdvancedSearch][checkResults] term["+term.toLowerCase( ).trim( )+"] equals boldText["+boldText+"]" ); if( term.toLowerCase( ).trim( ).equals( boldText ) ) checkTerm = true; } if( !checkTerm ) return false; } return true; } catch( NoSuchElementException e ){ System.out.println( "Error in checkOPSite" ); e.printStackTrace( ); return false; } } /** * Change to the English version */ private void switchLanguage( ){ System.out.println( "[switchLanguage]" ); String xpathEnglishVersion = "//*[@id=\"languageSelection\"]"; if( driver.findElement( By.xpath( xpathEnglishVersion ) ).getText( ).equals( "EN" ) ) { System.out.println( "Change language to English" ); driver.findElement( By.xpath( xpathEnglishVersion ) ).click( ); sleepThread( ); } } /** * remove protocol and subdirectories in the url * @param url * @return */ public String expandURL( String url ) { String urlResult; if ( url.startsWith( "http://" ) ) urlResult = urlRemoveProtocol( "http://" , url ); else if ( url.startsWith( "https://" ) ) urlResult = urlRemoveProtocol( "https://" , url ); else urlResult = urlRemoveProtocol( "http://" , "http://".concat( url ) ); if( urlResult == null || urlResult == "" ) return ""; if( urlResult.startsWith( "www." ) ) urlResult = urlResult.replaceFirst( "www." , "" ); urlResult = removeSubdirectories( urlResult ); return urlResult; } /** * remove protocol in the url stIndexPage index = new IndexPage( driver );ring * @param protocol * @param url * @return */ public String urlRemoveProtocol( String protocol , String url ) { String urlexpanded = ""; String siteHost = ""; try{ URL siteURL = new URL( url ); siteHost = siteURL.getHost( ); url = url.replace( siteHost, siteHost.toLowerCase( ) ); // hostname to lowercase urlexpanded = url.substring( protocol.length( ) ); return urlexpanded; } catch ( MalformedURLException e ) { return null; } } /** * remove subdirectorires in the url string * @param input * @return */ public static String removeSubdirectories( String input ) { if( input == null || input.equals( "" ) ) return ""; int idx = input.indexOf( "/" ); if( idx == -1 ) return input; return input.substring( 0 , idx ); } private void sleepThread( ) { try { Thread.sleep( 3000 ); } catch ( InterruptedException e ) { e.printStackTrace( ); } } }
test/pt/fccn/mobile/arquivo/pages/AdvancedSearchPage.java
package pt.fccn.mobile.arquivo.pages; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class AdvancedSearchPage { private final WebDriver driver; private final String topicsToSearch = "expo 98"; private final String negTerm = "concerto"; private final String expressionTerm = "\"pavilhao da utopia\""; private final String[ ] terms = new String[ ]{ "pavilhao da utopia", "pavilhao", "da", "utopia", "expo" , "98" }; private final String siteSearch = "www.arquivo.pt"; private final int timeout = 50; public AdvancedSearchPage( WebDriver driver ) { this.driver = driver; try { Thread.sleep( 5000 ); //wait for page to load } catch( InterruptedException ex ) { Thread.currentThread( ).interrupt( ); } // Check that we're on the right page. String pageTitle= driver.getTitle( ); System.out.println( "pageTile = " + pageTitle ); } public boolean checkSiteOperator( String language ) { System.out.println( "[checkSiteOperator]" ); String inputSearch = "//*[@id=\"adv_and\"]"; String divExpandable = "//*[@id=\"domains\"]/legend/i"; String inputSiteSearch = "//*[@id=\"site\"]"; String buttonSearch = "//*[@id=\"btnSubmitBottom\"]"; try{ if( language.equals( "EN" ) ) { switchLanguage( ); } if( searchSiteSearch( inputSearch , inputSiteSearch , divExpandable , buttonSearch ) ) return true; else return false; } catch( NoSuchElementException e ) { System.out.println( "Error in checkOPSite" ); e.printStackTrace( ); return false; } } private boolean searchSiteSearch( String inputSearch, String inputSiteSearch, String divExpandable, String buttonSearch ) { System.out.println( "[searchSiteSearch]" ); System.out.println( "Search for " + topicsToSearch ); WebElement elementSearch = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputSearch ) ) ); elementSearch.clear( ); elementSearch.sendKeys( topicsToSearch ); WebElement divElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( divExpandable ) ) ); divElement.click( ); sleepThread( ); System.out.println( "Search for site \"" + siteSearch+ "\"" ); WebElement elementExpression = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputSiteSearch ) ) ); elementExpression.clear( ); elementExpression.sendKeys( siteSearch ); WebElement btnSubmitElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( buttonSearch ) ) ); btnSubmitElement.click( ); sleepThread( ); if( !checkSiteResults( siteSearch ) ) return false; return true; } private boolean checkSiteResults( String siteSearch ) { System.out.println( "[AdvancedSearch][checkSiteResults]" ); String getURLResults = "//*[@id=\"resultados-lista\"]/ul/li/div[1]"; String domainSearch = expandURL( siteSearch.toLowerCase( ).trim( ) ); boolean checkURL = false; try{ List< WebElement > results = ( new WebDriverWait( driver, timeout ) ) .until( ExpectedConditions .visibilityOfAllElementsLocatedBy( By.xpath( getURLResults ) ) ); System.out.println( "results size = " + results.size( ) ); for( WebElement elem : results ) { String url = elem.getText( ).toLowerCase( ).trim( ); String treatedURL = expandURL( url ); System.out.println( "[AdvancedSearch][checkSiteResults] domainSearch["+domainSearch+"] equals treatedURL["+treatedURL+"]" ); if( !domainSearch.equals( treatedURL ) ) checkURL = false; } if( !checkURL ) return false; else return true; } catch( NoSuchElementException e ){ System.out.println( "Error in checkOPSite" ); e.printStackTrace( ); return false; } } public boolean checkAdvancedSearch( String language ) { System.out.println( "[checkAdvancedSearch]" ); String inputSearch = "//*[@id=\"adv_and\"]"; String inputExpression = "//*[@id=\"adv_phr\"]"; String inputNeg = "//*[@id=\"adv_not\"]"; String buttonSearch = "//*[@id=\"btnSubmitBottom\"]"; try{ if( language.equals( "EN" ) ) { switchLanguage( ); if( searchFullTextEN( inputSearch , inputExpression , inputNeg , buttonSearch ) ) return true; else return false; } else if( searchFullTextPT( inputSearch , inputExpression , inputNeg , buttonSearch ) ) return true; else return false; } catch( NoSuchElementException e ) { System.out.println( "Error in checkOPSite" ); e.printStackTrace( ); return false; } } private boolean searchFullTextPT( String inputSearch , String inputExpression , String inputNeg , String buttonSearch ) { System.out.println( "[searchFullTextPT]" ); System.out.println( "Search for " + topicsToSearch ); WebElement elementSearch = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputSearch ) ) ); elementSearch.clear( ); elementSearch.sendKeys( topicsToSearch ); System.out.println( "Search for expression \"" + expressionTerm+ "\"" ); WebElement elementExpression = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputExpression ) ) ); elementExpression.clear( ); elementExpression.sendKeys( expressionTerm ); System.out.println( "Search for denial operator -" + negTerm ); WebElement elementNeg = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputNeg ) ) ); elementNeg.clear( ); elementNeg.sendKeys( negTerm ); sleepThread( ); WebElement btnSubmitElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( buttonSearch ) ) ); btnSubmitElement.click( ); sleepThread( ); if( !checkResults( terms ) ) return false; return true; } private boolean searchFullTextEN( String inputSearch , String inputExpression , String inputNeg , String buttonSearch ) { System.out.println( "[AdvancedTest][searchEN]" ); System.out.println( "Search for " + topicsToSearch ); WebElement elementSearch = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputSearch ) ) ); elementSearch.clear( ); elementSearch.sendKeys( topicsToSearch ); System.out.println( "Search for expression \"" + expressionTerm+ "\"" ); WebElement elementExpression = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputExpression ) ) ); elementExpression.clear( ); elementExpression.sendKeys( expressionTerm ); System.out.println( "Search for denial operator -" + negTerm ); WebElement elementNeg = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( inputNeg ) ) ); elementNeg.clear( ); elementNeg.sendKeys( negTerm ); sleepThread( ); WebElement btnSubmitElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( buttonSearch ) ) ); btnSubmitElement.click( ); sleepThread( ); if( !checkResults( terms ) ) return false; return true; } private boolean checkResults( String[ ] terms ) { System.out.println( "[AdvancedSearch][checkResults]" ); String getResumeResults = "//*[@id=\"resultados-lista\"]/ul/li/span[1]/em"; boolean checkTerm = false; try{ List< WebElement > results = ( new WebDriverWait( driver, timeout ) ) .until( ExpectedConditions .visibilityOfAllElementsLocatedBy( By.xpath( getResumeResults ) ) ); System.out.println( "results size = " + results.size( ) ); for( WebElement elem : results ) { String boldText = elem.getText( ).toLowerCase( ).trim( ); for( String term : terms ){ System.out.println( "[AdvancedSearch][checkResults] term["+term.toLowerCase( ).trim( )+"] equals boldText["+boldText+"]" ); if( term.toLowerCase( ).trim( ).equals( boldText ) ) checkTerm = true; } if( !checkTerm ) return false; } return true; } catch( NoSuchElementException e ){ System.out.println( "Error in checkOPSite" ); e.printStackTrace( ); return false; } } /** * Change to the English version */ private void switchLanguage( ){ System.out.println( "[switchLanguage]" ); String xpathEnglishVersion = "//*[@id=\"languageSelection\"]"; if( driver.findElement( By.xpath( xpathEnglishVersion ) ).getText( ).equals( "EN" ) ) { System.out.println( "Change language to English" ); driver.findElement( By.xpath( xpathEnglishVersion ) ).click( ); sleepThread( ); } } /** * remove protocol and subdirectories in the url * @param url * @return */ public String expandURL( String url ) { String urlResult; if ( url.startsWith( "http://" ) ) urlResult = urlRemoveProtocol( "http://" , url ); else if ( url.startsWith( "https://" ) ) urlResult = urlRemoveProtocol( "https://" , url ); else urlResult = urlRemoveProtocol( "http://" , "http://".concat( url ) ); if( urlResult == null || urlResult == "" ) return ""; if( urlResult.startsWith( "www." ) ) urlResult = urlResult.replaceFirst( "www." , "" ); urlResult = removeSubdirectories( urlResult ); return urlResult; } /** * remove protocol in the url stIndexPage index = new IndexPage( driver );ring * @param protocol * @param url * @return */ public String urlRemoveProtocol( String protocol , String url ) { String urlexpanded = ""; String siteHost = ""; try{ URL siteURL = new URL( url ); siteHost = siteURL.getHost( ); url = url.replace( siteHost, siteHost.toLowerCase( ) ); // hostname to lowercase urlexpanded = url.substring( protocol.length( ) ); return urlexpanded; } catch ( MalformedURLException e ) { return null; } } /** * remove subdirectorires in the url string * @param input * @return */ public static String removeSubdirectories( String input ) { if( input == null || input.equals( "" ) ) return ""; int idx = input.indexOf( "/" ); if( idx == -1 ) return input; return input.substring( 0 , idx ); } private void sleepThread( ) { try { Thread.sleep( 3000 ); } catch ( InterruptedException e ) { e.printStackTrace( ); } } }
[Mobile-tests][AdvancedSearch] fixed bug
test/pt/fccn/mobile/arquivo/pages/AdvancedSearchPage.java
[Mobile-tests][AdvancedSearch] fixed bug
<ide><path>est/pt/fccn/mobile/arquivo/pages/AdvancedSearchPage.java <ide> <ide> private boolean searchSiteSearch( String inputSearch, String inputSiteSearch, String divExpandable, String buttonSearch ) { <ide> System.out.println( "[searchSiteSearch]" ); <del> <add> <ide> System.out.println( "Search for " + topicsToSearch ); <ide> WebElement elementSearch = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ <ide> .until( <ide> System.out.println( "[AdvancedSearch][checkSiteResults]" ); <ide> String getURLResults = "//*[@id=\"resultados-lista\"]/ul/li/div[1]"; <ide> String domainSearch = expandURL( siteSearch.toLowerCase( ).trim( ) ); <del> boolean checkURL = false; <add> <ide> try{ <ide> List< WebElement > results = ( new WebDriverWait( driver, timeout ) ) <ide> .until( ExpectedConditions <ide> String treatedURL = expandURL( url ); <ide> System.out.println( "[AdvancedSearch][checkSiteResults] domainSearch["+domainSearch+"] equals treatedURL["+treatedURL+"]" ); <ide> if( !domainSearch.equals( treatedURL ) ) <del> checkURL = false; <add> return false; <ide> } <ide> <del> if( !checkURL ) <del> return false; <del> else <del> return true; <add> return true; <ide> <ide> } catch( NoSuchElementException e ){ <ide> System.out.println( "Error in checkOPSite" );
Java
lgpl-2.1
2cfe0de71a8a7a094905cb4bbbfe4cf78d2e80f6
0
zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform
package org.zanata.search; import java.util.Collection; import java.util.List; import org.hibernate.Query; import org.hibernate.criterion.MatchMode; import org.joda.time.DateTime; import org.zanata.common.HasContents; import org.zanata.model.HLocale; import org.zanata.util.HqlCriterion; import org.zanata.util.QueryBuilder; import org.zanata.webtrans.shared.model.DocumentId; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists; import lombok.AccessLevel; import lombok.Setter; import static org.zanata.search.FilterConstraintToQuery.Parameters.*; import static org.zanata.util.HqlCriterion.eq; import static org.zanata.util.HqlCriterion.escapeWildcard; import static org.zanata.util.HqlCriterion.ilike; import static org.zanata.util.HqlCriterion.match; import static org.zanata.util.QueryBuilder.and; /** * @author Patrick Huang <a * href="mailto:[email protected]">[email protected]</a> */ public class FilterConstraintToQuery { private final FilterConstraints constraints; private final boolean hasSearch; private String searchString; private DocumentId documentId; private Collection<Long> documentIds; @Setter(AccessLevel.PACKAGE) private ContentCriterion contentCriterion = new ContentCriterion( HasContents.MAX_PLURALS); private FilterConstraintToQuery(FilterConstraints constraints, DocumentId documentId) { this(constraints); this.documentId = documentId; } public FilterConstraintToQuery(FilterConstraints constraints, Collection<Long> documentIds) { this(constraints); this.documentIds = documentIds; } private FilterConstraintToQuery(FilterConstraints constraints) { this.constraints = constraints; hasSearch = !Strings.isNullOrEmpty(constraints.getSearchString()); if (hasSearch) { String term = constraints.isCaseSensitive() ? constraints .getSearchString() : constraints.getSearchString() .toLowerCase(); term = escapeWildcard(term); searchString = match(term, MatchMode.ANYWHERE); } } public static FilterConstraintToQuery filterInSingleDocument( FilterConstraints constraints, DocumentId documentId) { Preconditions.checkNotNull(documentId); return new FilterConstraintToQuery(constraints, documentId); } public static FilterConstraintToQuery filterInMultipleDocuments( FilterConstraints constraints, Collection<Long> documentIds) { Preconditions.checkNotNull(documentIds); Preconditions.checkState(!documentIds.isEmpty()); return new FilterConstraintToQuery(constraints, documentIds); } /** * This builds a query for constructing TransUnit in editor. It returns a * list of HTextFlow objects * * @return the HQL query */ public String toEntityQuery() { String docIdCondition; if (documentId != null) { docIdCondition = eq("tf.document.id", Parameters.documentId.placeHolder()); } else { docIdCondition = "tf.document.id in (" + documentIdList.placeHolder() + ")"; } return buildQuery("distinct tf", docIdCondition); } private String buildQuery(String selectStatement, String docIdCondition) { String obsoleteCondition = eq("tf.obsolete", "0"); String searchCondition = buildSearchCondition(); String stateCondition = buildStateCondition(); QueryBuilder query = QueryBuilder .select(selectStatement) .from("HTextFlow tf") .leftJoin("tf.targets tfts") .with(eq("tfts.index", locale.placeHolder())) .where(and(obsoleteCondition, docIdCondition, searchCondition, stateCondition)) .orderBy("tf.pos"); return query.toQueryString(); } /** * This builds a query for editor modal navigation. It only select text flow * id and text flow target content state. * * @return the HQL query */ public String toModalNavigationQuery() { String docIdCondition = eq("tf.document.id", Parameters.documentId.placeHolder()); return buildQuery( "distinct tf.id as id, (case when tfts is null then 0 else tfts.state end) as state, tf.pos as pos", docIdCondition); } protected String buildSearchCondition() { String searchInSourceCondition = null; List<String> sourceConjunction = Lists.newArrayList(); if (hasSearch && constraints.isSearchInSource()) { String contentsCriterion = contentCriterion.contentsCriterionAsString("tf", constraints.isCaseSensitive(), Parameters.searchString.placeHolder()); addToJunctionIfNotNull(sourceConjunction, contentsCriterion); } addToJunctionIfNotNull(sourceConjunction, buildSourceCommentCondition(constraints.getSourceComment())); addToJunctionIfNotNull(sourceConjunction, buildMsgContextCondition()); addToJunctionIfNotNull(sourceConjunction, buildResourceIdCondition()); if (!sourceConjunction.isEmpty()) { searchInSourceCondition = QueryBuilder.and(sourceConjunction); } String searchInTargetCondition = null; List<String> targetConjunction = Lists.newArrayList(); if (hasSearch && constraints.isSearchInTarget()) { targetConjunction.add(contentCriterion.contentsCriterionAsString( null, constraints.isCaseSensitive(), Parameters.searchString.placeHolder())); } addToJunctionIfNotNull(targetConjunction, buildLastModifiedByCondition()); addToJunctionIfNotNull(targetConjunction, buildTargetCommentCondition(constraints.getTransComment())); addToJunctionIfNotNull(targetConjunction, buildLastModifiedDateCondition()); if (!targetConjunction.isEmpty()) { targetConjunction.add(eq("textFlow", "tf")); targetConjunction.add(eq("locale", locale.placeHolder())); searchInTargetCondition = QueryBuilder.exists().from("HTextFlowTarget") .where(QueryBuilder.and(targetConjunction)) .toQueryString(); } if (searchInSourceCondition == null && searchInTargetCondition == null) { return null; } return QueryBuilder .or(searchInSourceCondition, searchInTargetCondition); } private static List<String> addToJunctionIfNotNull(List<String> junction, String criterion) { if (criterion != null) { junction.add(criterion); } return junction; } private String buildResourceIdCondition() { if (Strings.isNullOrEmpty(constraints.getResId())) { return null; } return ilike("resId", resId.placeHolder()); } private String buildMsgContextCondition() { if (Strings.isNullOrEmpty(constraints.getMsgContext())) { return null; } return ilike("tf.potEntryData.context", msgContext.placeHolder()); } private String buildSourceCommentCondition(String commentToSearch) { if (Strings.isNullOrEmpty(commentToSearch)) { return null; } return ilike("tf.comment.comment", sourceComment.placeHolder()); } private String buildTargetCommentCondition(String transComment) { if (Strings.isNullOrEmpty(transComment)) { return null; } return ilike("comment.comment", targetComment.placeHolder()); } private String buildLastModifiedDateCondition() { DateTime changedBeforeTime = constraints.getChangedBefore(); DateTime changedAfterTime = constraints.getChangedAfter(); if (changedBeforeTime == null && changedAfterTime == null) { return null; } String changedAfter = null; String changedBefore = null; if (changedAfterTime != null) { changedAfter = HqlCriterion.gt("lastChanged", lastChangedAfter.placeHolder()); } if (changedBeforeTime != null) { changedBefore = HqlCriterion.lt("lastChanged", lastChangedBefore.placeHolder()); } return QueryBuilder.and(changedAfter, changedBefore); } protected String buildStateCondition() { if (constraints.getIncludedStates().hasAllStates()) { return null; } List<String> conjunction = Lists.newArrayList(); conjunction.add(eq("textFlow", "tf")); conjunction.add(eq("locale", locale.placeHolder())); String textFlowAndLocaleRestriction = and(eq("textFlow", "tf"), eq("locale", locale.placeHolder())); String stateInListWhereClause = and(textFlowAndLocaleRestriction, String.format("state in (%s)", contentStateList.placeHolder())); String stateInListCondition = QueryBuilder.exists().from("HTextFlowTarget") .where(stateInListWhereClause).toQueryString(); if (constraints.getIncludedStates().hasNew()) { String nullTargetCondition = String.format("%s not in indices(tf.targets)", locale.placeHolder()); if (hasSearch && constraints.isSearchInSource()) { nullTargetCondition = and(nullTargetCondition, contentCriterion.contentsCriterionAsString( "tf", constraints.isCaseSensitive(), Parameters.searchString.placeHolder())); } return QueryBuilder.or(stateInListCondition, nullTargetCondition); } return stateInListCondition; } protected String buildLastModifiedByCondition() { if (Strings.isNullOrEmpty(constraints.getLastModifiedByUser())) { return null; } return eq("lastModifiedBy.account.username", lastModifiedBy.placeHolder()); } public Query setQueryParameters(Query textFlowQuery, HLocale hLocale) { if (documentId != null) { textFlowQuery.setParameter(Parameters.documentId.namedParam(), documentId.getId()); } else { textFlowQuery.setParameterList(documentIdList.namedParam(), documentIds); } textFlowQuery.setParameter(locale.namedParam(), hLocale.getId()); if (hasSearch) { textFlowQuery.setParameter(Parameters.searchString.namedParam(), searchString); } if (!constraints.getIncludedStates().hasAllStates()) { textFlowQuery.setParameterList(contentStateList.namedParam(), constraints.getIncludedStates().asList()); } addWildcardSearchParamIfPresent(textFlowQuery, constraints.getResId(), resId); addWildcardSearchParamIfPresent(textFlowQuery, constraints.getMsgContext(), msgContext); addWildcardSearchParamIfPresent(textFlowQuery, constraints.getSourceComment(), sourceComment); addWildcardSearchParamIfPresent(textFlowQuery, constraints.getTransComment(), targetComment); if (!Strings.isNullOrEmpty(constraints.getLastModifiedByUser())) { textFlowQuery.setParameter(lastModifiedBy.namedParam(), constraints.getLastModifiedByUser()); } if (constraints.getChangedAfter() != null) { textFlowQuery.setParameter(lastChangedAfter.namedParam(), constraints.getChangedAfter().toDate()); } if (constraints.getChangedBefore() != null) { textFlowQuery.setParameter(lastChangedBefore.namedParam(), constraints.getChangedBefore().toDate()); } return textFlowQuery; } private static Query addWildcardSearchParamIfPresent(Query textFlowQuery, String filterProperty, Parameters filterParam) { if (!Strings.isNullOrEmpty(filterProperty)) { String escapedAndLowered = HqlCriterion.escapeWildcard(filterProperty.toLowerCase()); textFlowQuery.setParameter(filterParam.namedParam(), HqlCriterion.match(escapedAndLowered, MatchMode.ANYWHERE)); } return textFlowQuery; } enum Parameters { searchString, contentStateList, locale, documentId, documentIdList, resId, sourceComment, msgContext, targetComment, lastModifiedBy, lastChangedAfter, lastChangedBefore; public String placeHolder() { return ":" + name(); } public String namedParam() { return name(); } } }
zanata-war/src/main/java/org/zanata/search/FilterConstraintToQuery.java
package org.zanata.search; import java.util.Collection; import java.util.List; import org.hibernate.Query; import org.hibernate.criterion.MatchMode; import org.joda.time.DateTime; import org.zanata.common.HasContents; import org.zanata.model.HLocale; import org.zanata.util.HqlCriterion; import org.zanata.util.QueryBuilder; import org.zanata.webtrans.shared.model.DocumentId; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists; import lombok.AccessLevel; import lombok.Setter; import static org.zanata.search.FilterConstraintToQuery.Parameters.*; import static org.zanata.util.HqlCriterion.eq; import static org.zanata.util.HqlCriterion.escapeWildcard; import static org.zanata.util.HqlCriterion.ilike; import static org.zanata.util.HqlCriterion.match; import static org.zanata.util.QueryBuilder.and; /** * @author Patrick Huang <a * href="mailto:[email protected]">[email protected]</a> */ public class FilterConstraintToQuery { private final FilterConstraints constraints; private final boolean hasSearch; private String searchString; private DocumentId documentId; private Collection<Long> documentIds; @Setter(AccessLevel.PACKAGE) private ContentCriterion contentCriterion = new ContentCriterion( HasContents.MAX_PLURALS); private FilterConstraintToQuery(FilterConstraints constraints, DocumentId documentId) { this(constraints); this.documentId = documentId; } public FilterConstraintToQuery(FilterConstraints constraints, Collection<Long> documentIds) { this(constraints); this.documentIds = documentIds; } private FilterConstraintToQuery(FilterConstraints constraints) { this.constraints = constraints; hasSearch = !Strings.isNullOrEmpty(constraints.getSearchString()); if (hasSearch) { String term = constraints.isCaseSensitive() ? constraints .getSearchString() : constraints.getSearchString() .toLowerCase(); term = escapeWildcard(term); searchString = match(term, MatchMode.ANYWHERE); } } public static FilterConstraintToQuery filterInSingleDocument( FilterConstraints constraints, DocumentId documentId) { Preconditions.checkNotNull(documentId); return new FilterConstraintToQuery(constraints, documentId); } public static FilterConstraintToQuery filterInMultipleDocuments( FilterConstraints constraints, Collection<Long> documentIds) { Preconditions.checkNotNull(documentIds); Preconditions.checkState(!documentIds.isEmpty()); return new FilterConstraintToQuery(constraints, documentIds); } public String toEntityQuery() { String docIdCondition; if (documentId != null) { docIdCondition = eq("tf.document.id", Parameters.documentId.placeHolder()); } else { docIdCondition = "tf.document.id in (" + documentIdList.placeHolder() + ")"; } String obsoleteCondition = eq("tf.obsolete", "0"); String searchCondition = buildSearchCondition(); String stateCondition = buildStateCondition(); QueryBuilder query = QueryBuilder .select("distinct tf") .from("HTextFlow tf") .leftJoin("tf.targets tfts") .with(eq("tfts.index", locale.placeHolder())) .where(and(obsoleteCondition, docIdCondition, searchCondition, stateCondition)) .orderBy("tf.pos"); return query.toQueryString(); } public String toModalNavigationQuery() { String docIdCondition = eq("tf.document.id", Parameters.documentId.placeHolder()); String obsoleteCondition = eq("tf.obsolete", "0"); String searchCondition = buildSearchCondition(); String stateCondition = buildStateCondition(); QueryBuilder queryBuilder = QueryBuilder .select("distinct tf.id as id, (case when tfts is null then 0 else tfts.state end) as state, tf.pos as pos") .from("HTextFlow tf") .leftJoin("tf.targets tfts") .with(eq("tfts.index", locale.placeHolder())) .where(and(obsoleteCondition, docIdCondition, searchCondition, stateCondition)) .orderBy("tf.pos"); return queryBuilder.toQueryString(); } protected String buildSearchCondition() { String searchInSourceCondition = null; List<String> sourceConjunction = Lists.newArrayList(); if (hasSearch && constraints.isSearchInSource()) { String contentsCriterion = contentCriterion.contentsCriterionAsString("tf", constraints.isCaseSensitive(), Parameters.searchString.placeHolder()); addToJunctionIfNotNull(sourceConjunction, contentsCriterion); } addToJunctionIfNotNull(sourceConjunction, buildSourceCommentCondition(constraints.getSourceComment())); addToJunctionIfNotNull(sourceConjunction, buildMsgContextCondition()); addToJunctionIfNotNull(sourceConjunction, buildResourceIdCondition()); if (!sourceConjunction.isEmpty()) { searchInSourceCondition = QueryBuilder.and(sourceConjunction); } String searchInTargetCondition = null; List<String> targetConjunction = Lists.newArrayList(); if (hasSearch && constraints.isSearchInTarget()) { targetConjunction.add(contentCriterion.contentsCriterionAsString( null, constraints.isCaseSensitive(), Parameters.searchString.placeHolder())); } addToJunctionIfNotNull(targetConjunction, buildLastModifiedByCondition()); addToJunctionIfNotNull(targetConjunction, buildTargetCommentCondition(constraints.getTransComment())); addToJunctionIfNotNull(targetConjunction, buildLastModifiedDateCondition()); if (!targetConjunction.isEmpty()) { targetConjunction.add(eq("textFlow", "tf")); targetConjunction.add(eq("locale", locale.placeHolder())); searchInTargetCondition = QueryBuilder.exists().from("HTextFlowTarget") .where(QueryBuilder.and(targetConjunction)) .toQueryString(); } if (searchInSourceCondition == null && searchInTargetCondition == null) { return null; } return QueryBuilder .or(searchInSourceCondition, searchInTargetCondition); } private static List<String> addToJunctionIfNotNull(List<String> junction, String criterion) { if (criterion != null) { junction.add(criterion); } return junction; } private String buildResourceIdCondition() { if (Strings.isNullOrEmpty(constraints.getResId())) { return null; } return ilike("resId", resId.placeHolder()); } private String buildMsgContextCondition() { if (Strings.isNullOrEmpty(constraints.getMsgContext())) { return null; } return ilike("tf.potEntryData.context", msgContext.placeHolder()); } private String buildSourceCommentCondition(String commentToSearch) { if (Strings.isNullOrEmpty(commentToSearch)) { return null; } return ilike("tf.comment.comment", sourceComment.placeHolder()); } private String buildTargetCommentCondition(String transComment) { if (Strings.isNullOrEmpty(transComment)) { return null; } return ilike("comment.comment", targetComment.placeHolder()); } private String buildLastModifiedDateCondition() { DateTime changedBeforeTime = constraints.getChangedBefore(); DateTime changedAfterTime = constraints.getChangedAfter(); if (changedBeforeTime == null && changedAfterTime == null) { return null; } String changedAfter = null; String changedBefore = null; if (changedAfterTime != null) { changedAfter = HqlCriterion.gt("lastChanged", lastChangedAfter.placeHolder()); } if (changedBeforeTime != null) { changedBefore = HqlCriterion.lt("lastChanged", lastChangedBefore.placeHolder()); } return QueryBuilder.and(changedAfter, changedBefore); } protected String buildStateCondition() { if (constraints.getIncludedStates().hasAllStates()) { return null; } List<String> conjunction = Lists.newArrayList(); conjunction.add(eq("textFlow", "tf")); conjunction.add(eq("locale", locale.placeHolder())); String textFlowAndLocaleRestriction = and(eq("textFlow", "tf"), eq("locale", locale.placeHolder())); String stateInListWhereClause = and(textFlowAndLocaleRestriction, String.format("state in (%s)", contentStateList.placeHolder())); String stateInListCondition = QueryBuilder.exists().from("HTextFlowTarget") .where(stateInListWhereClause).toQueryString(); if (constraints.getIncludedStates().hasNew()) { String nullTargetCondition = String.format("%s not in indices(tf.targets)", locale.placeHolder()); if (hasSearch && constraints.isSearchInSource()) { nullTargetCondition = and(nullTargetCondition, contentCriterion.contentsCriterionAsString( "tf", constraints.isCaseSensitive(), Parameters.searchString.placeHolder())); } return QueryBuilder.or(stateInListCondition, nullTargetCondition); } return stateInListCondition; } protected String buildLastModifiedByCondition() { if (Strings.isNullOrEmpty(constraints.getLastModifiedByUser())) { return null; } return eq("lastModifiedBy.account.username", lastModifiedBy.placeHolder()); } public Query setQueryParameters(Query textFlowQuery, HLocale hLocale) { if (documentId != null) { textFlowQuery.setParameter(Parameters.documentId.namedParam(), documentId.getId()); } else { textFlowQuery.setParameterList(documentIdList.namedParam(), documentIds); } textFlowQuery.setParameter(locale.namedParam(), hLocale.getId()); if (hasSearch) { textFlowQuery.setParameter(Parameters.searchString.namedParam(), searchString); } if (!constraints.getIncludedStates().hasAllStates()) { textFlowQuery.setParameterList(contentStateList.namedParam(), constraints.getIncludedStates().asList()); } addWildcardSearchParamIfPresent(textFlowQuery, constraints.getResId(), resId); addWildcardSearchParamIfPresent(textFlowQuery, constraints.getMsgContext(), msgContext); addWildcardSearchParamIfPresent(textFlowQuery, constraints.getSourceComment(), sourceComment); addWildcardSearchParamIfPresent(textFlowQuery, constraints.getTransComment(), targetComment); if (!Strings.isNullOrEmpty(constraints.getLastModifiedByUser())) { textFlowQuery.setParameter(lastModifiedBy.namedParam(), constraints.getLastModifiedByUser()); } if (constraints.getChangedAfter() != null) { textFlowQuery.setParameter(lastChangedAfter.namedParam(), constraints.getChangedAfter().toDate()); } if (constraints.getChangedBefore() != null) { textFlowQuery.setParameter(lastChangedBefore.namedParam(), constraints.getChangedBefore().toDate()); } return textFlowQuery; } private static Query addWildcardSearchParamIfPresent(Query textFlowQuery, String filterProperty, Parameters filterParam) { if (!Strings.isNullOrEmpty(filterProperty)) { String escapedAndLowered = HqlCriterion.escapeWildcard(filterProperty.toLowerCase()); textFlowQuery.setParameter(filterParam.namedParam(), HqlCriterion.match(escapedAndLowered, MatchMode.ANYWHERE)); } return textFlowQuery; } enum Parameters { searchString, contentStateList, locale, documentId, documentIdList, resId, sourceComment, msgContext, targetComment, lastModifiedBy, lastChangedAfter, lastChangedBefore; public String placeHolder() { return ":" + name(); } public String namedParam() { return name(); } } }
rhbz882770 - refactor FilterConstraintToQuery to share code
zanata-war/src/main/java/org/zanata/search/FilterConstraintToQuery.java
rhbz882770 - refactor FilterConstraintToQuery to share code
<ide><path>anata-war/src/main/java/org/zanata/search/FilterConstraintToQuery.java <ide> return new FilterConstraintToQuery(constraints, documentIds); <ide> } <ide> <add> /** <add> * This builds a query for constructing TransUnit in editor. It returns a <add> * list of HTextFlow objects <add> * <add> * @return the HQL query <add> */ <ide> public String toEntityQuery() { <ide> String docIdCondition; <ide> if (documentId != null) { <ide> docIdCondition = <ide> "tf.document.id in (" + documentIdList.placeHolder() + ")"; <ide> } <add> return buildQuery("distinct tf", docIdCondition); <add> } <add> <add> private String buildQuery(String selectStatement, String docIdCondition) { <add> <ide> String obsoleteCondition = eq("tf.obsolete", "0"); <ide> String searchCondition = buildSearchCondition(); <ide> String stateCondition = buildStateCondition(); <ide> <ide> QueryBuilder query = <ide> QueryBuilder <del> .select("distinct tf") <add> .select(selectStatement) <ide> .from("HTextFlow tf") <ide> .leftJoin("tf.targets tfts") <ide> .with(eq("tfts.index", locale.placeHolder())) <ide> return query.toQueryString(); <ide> } <ide> <add> /** <add> * This builds a query for editor modal navigation. It only select text flow <add> * id and text flow target content state. <add> * <add> * @return the HQL query <add> */ <ide> public String toModalNavigationQuery() { <ide> String docIdCondition = <ide> eq("tf.document.id", Parameters.documentId.placeHolder()); <del> String obsoleteCondition = eq("tf.obsolete", "0"); <del> String searchCondition = buildSearchCondition(); <del> String stateCondition = buildStateCondition(); <del> QueryBuilder queryBuilder = <del> QueryBuilder <del> .select("distinct tf.id as id, (case when tfts is null then 0 else tfts.state end) as state, tf.pos as pos") <del> .from("HTextFlow tf") <del> .leftJoin("tf.targets tfts") <del> .with(eq("tfts.index", locale.placeHolder())) <del> .where(and(obsoleteCondition, docIdCondition, <del> searchCondition, stateCondition)) <del> .orderBy("tf.pos"); <del> return queryBuilder.toQueryString(); <add> return buildQuery( <add> "distinct tf.id as id, (case when tfts is null then 0 else tfts.state end) as state, tf.pos as pos", <add> docIdCondition); <ide> } <ide> <ide> protected String buildSearchCondition() {
Java
mit
f7d1a429987d2b0275eb8da9a0dc179c5407b553
0
caelum/tubaina,caelum/tubaina,caelum/tubaina,caelum/tubaina,caelum/tubaina
package br.com.caelum.tubaina.parser.latex; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FilenameUtils; import br.com.caelum.tubaina.parser.Tag; public class ImageTag implements Tag { double pageWidth = 175; public String parse(final String path, final String options) { String output = "\\begin{figure}[H]\n\\centering\n"; output = output + "\\includegraphics"; Pattern label = Pattern.compile("(?s)(?i)label=(\\w+)%?"); Matcher labelMatcher = label.matcher(options); Pattern description = Pattern.compile("(?s)(?i)\"(.+?)\""); Matcher descriptionMatcher = description.matcher(options); Pattern horizontalScale = Pattern.compile("(?s)(?i)w=(\\d+)%?"); Matcher horizontalMatcher = horizontalScale.matcher(options); Pattern actualWidth = Pattern.compile("(?s)(?i)\\[(.+?)\\]"); Matcher actualWidthMatcher = actualWidth.matcher(options); double width = Double.MAX_VALUE; if (actualWidthMatcher.find()) { width = Double.parseDouble(actualWidthMatcher.group(1)); } if (horizontalMatcher.find()) { output = output + "[width=" + pageWidth * (Double.parseDouble(horizontalMatcher.group(1)) / 100) + "mm]"; } else if (width > pageWidth) { output = output + "[width=\\textwidth]"; } else { output = output + "[scale=1]"; } String imgsrc = FilenameUtils.getName(path); output = output + "{" + imgsrc + "}\n"; if (descriptionMatcher.find()) { output = output + "\n\n\\caption{" + descriptionMatcher.group(1) + "}\n\n"; } if (labelMatcher.find()) { output += "\\label{" + labelMatcher.group(1) + "}\n"; } output = output + "\\end{figure}\n\n"; return output; } public Integer getScale(final String string) { if (string == null) { return null; } Pattern horizontalScale = Pattern.compile("(?s)(?i)w=(\\d+)%?"); Matcher sMatcher = horizontalScale.matcher(string); if (sMatcher.find()) { return Integer.parseInt(sMatcher.group(1)); } return null; } }
src/main/java/br/com/caelum/tubaina/parser/latex/ImageTag.java
package br.com.caelum.tubaina.parser.latex; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FilenameUtils; import br.com.caelum.tubaina.parser.Tag; public class ImageTag implements Tag { double pageWidth = 175; public String parse(final String path, final String options) { String output = "\\begin{figure}[H]\n\\centering\n"; output = output + "\\includegraphics"; Pattern label = Pattern.compile("(?s)(?i)label=(\\w+)%?"); Matcher labelMatcher = label.matcher(options); Pattern description = Pattern.compile("(?s)(?i)\"(.+?)\""); Matcher descriptionMatcher = description.matcher(options); Pattern horizontalScale = Pattern.compile("(?s)(?i)w=(\\d+)%?"); Matcher horizontalMatcher = horizontalScale.matcher(options); Pattern actualWidth = Pattern.compile("(?s)(?i)\\[(.+?)\\]"); Matcher actualWidthMatcher = actualWidth.matcher(options); double width = Double.MAX_VALUE; if (actualWidthMatcher.find()) { width = Double.parseDouble(actualWidthMatcher.group(1)); } if (horizontalMatcher.find()) { output = output + "[width=" + pageWidth * (Double.parseDouble(horizontalMatcher.group(1)) / 100) + "mm]"; } else if (width > pageWidth) { output = output + "[width=\\textwidth]"; } else { output = output + "[scale=1]"; } String imgsrc = FilenameUtils.getName(path); output = output + "{" + imgsrc + "}\n"; if (labelMatcher.find()) { output += "\\label{" + labelMatcher.group(1) + "}\n"; } if (descriptionMatcher.find()) { output = output + "\n\n\\caption{" + descriptionMatcher.group(1) + "}\n\n"; } output = output + "\\end{figure}\n\n"; return output; } public Integer getScale(final String string) { if (string == null) { return null; } Pattern horizontalScale = Pattern.compile("(?s)(?i)w=(\\d+)%?"); Matcher sMatcher = horizontalScale.matcher(string); if (sMatcher.find()) { return Integer.parseInt(sMatcher.group(1)); } return null; } }
writing label after caption tag
src/main/java/br/com/caelum/tubaina/parser/latex/ImageTag.java
writing label after caption tag
<ide><path>rc/main/java/br/com/caelum/tubaina/parser/latex/ImageTag.java <ide> String imgsrc = FilenameUtils.getName(path); <ide> output = output + "{" + imgsrc + "}\n"; <ide> <add> if (descriptionMatcher.find()) { <add> output = output + "\n\n\\caption{" + descriptionMatcher.group(1) + "}\n\n"; <add> } <add> <ide> if (labelMatcher.find()) { <ide> output += "\\label{" + labelMatcher.group(1) + "}\n"; <del> } <del> <del> if (descriptionMatcher.find()) { <del> output = output + "\n\n\\caption{" + descriptionMatcher.group(1) + "}\n\n"; <ide> } <ide> <ide> output = output + "\\end{figure}\n\n";
Java
apache-2.0
dec4a12e06865782b261b4bfb85d5f2d797c6ed5
0
apache/commons-net,apache/commons-net
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.commons.net; import org.apache.commons.net.util.SubnetUtils; import org.apache.commons.net.util.SubnetUtils.SubnetInfo; import junit.framework.TestCase; @SuppressWarnings("deprecation") // deliberate use of deprecated methods public class SubnetUtilsTest extends TestCase { // TODO Lower address test public void testAddresses() { SubnetUtils utils = new SubnetUtils("192.168.0.1/29"); SubnetInfo info = utils.getInfo(); assertTrue(info.isInRange("192.168.0.1")); // We don't count the broadcast address as usable assertFalse(info.isInRange("192.168.0.7")); assertFalse(info.isInRange("192.168.0.8")); assertFalse(info.isInRange("10.10.2.1")); assertFalse(info.isInRange("192.168.1.1")); assertFalse(info.isInRange("192.168.0.255")); } /** * Test using the inclusiveHostCount flag, which includes the network and broadcast addresses in host counts */ public void testCidrAddresses() { SubnetUtils utils = new SubnetUtils("192.168.0.1/8"); utils.setInclusiveHostCount(true); SubnetInfo info = utils.getInfo(); assertEquals("255.0.0.0", info.getNetmask()); assertEquals(16777216, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/0"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("0.0.0.0", info.getNetmask()); assertEquals(4294967296L, info.getAddressCountLong()); utils = new SubnetUtils("192.168.0.1/1"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("128.0.0.0", info.getNetmask()); assertEquals(2147483648L, info.getAddressCountLong()); utils = new SubnetUtils("192.168.0.1/9"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.128.0.0", info.getNetmask()); assertEquals(8388608, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/10"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.192.0.0", info.getNetmask()); assertEquals(4194304, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/11"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.224.0.0", info.getNetmask()); assertEquals(2097152, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/12"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.240.0.0", info.getNetmask()); assertEquals(1048576, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/13"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.248.0.0", info.getNetmask()); assertEquals(524288, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/14"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.252.0.0", info.getNetmask()); assertEquals(262144, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/15"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.254.0.0", info.getNetmask()); assertEquals(131072, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/16"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.0.0", info.getNetmask()); assertEquals(65536, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/17"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.128.0", info.getNetmask()); assertEquals(32768, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/18"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.192.0", info.getNetmask()); assertEquals(16384, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/19"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.224.0", info.getNetmask()); assertEquals(8192, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/20"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.240.0", info.getNetmask()); assertEquals(4096, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/21"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.248.0", info.getNetmask()); assertEquals(2048, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/22"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.252.0", info.getNetmask()); assertEquals(1024, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/23"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.254.0", info.getNetmask()); assertEquals(512, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/24"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.0", info.getNetmask()); assertEquals(256, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/25"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.128", info.getNetmask()); assertEquals(128, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/26"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.192", info.getNetmask()); assertEquals(64, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/27"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.224", info.getNetmask()); assertEquals(32, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/28"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.240", info.getNetmask()); assertEquals(16, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/29"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.248", info.getNetmask()); assertEquals(8, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/30"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.252", info.getNetmask()); assertEquals(4, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/31"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.254", info.getNetmask()); assertEquals(2, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/32"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.255", info.getNetmask()); assertEquals(1, info.getAddressCount()); } public void testNET675() { SubnetUtils utils = new SubnetUtils("192.168.0.15/32"); utils.setInclusiveHostCount(true); SubnetInfo info = utils.getInfo(); assertTrue(info.isInRange("192.168.0.15")); } public void testNET679() { SubnetUtils utils = new SubnetUtils("10.213.160.0/16"); utils.setInclusiveHostCount(true); SubnetInfo info = utils.getInfo(); assertTrue(info.isInRange("10.213.0.0")); assertTrue(info.isInRange("10.213.255.255")); } public void testInvalidMasks() { try { new SubnetUtils("192.168.0.1/33"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { // Ignored } } public void testNET428_31() throws Exception { final SubnetUtils subnetUtils = new SubnetUtils("1.2.3.4/31"); assertEquals(0, subnetUtils.getInfo().getAddressCount()); String[] address = subnetUtils.getInfo().getAllAddresses(); assertNotNull(address); assertEquals(0, address.length); } public void testNET428_32() throws Exception { final SubnetUtils subnetUtils = new SubnetUtils("1.2.3.4/32"); assertEquals(0, subnetUtils.getInfo().getAddressCount()); String[] address = subnetUtils.getInfo().getAllAddresses(); assertNotNull(address); assertEquals(0, address.length); } public void testParseSimpleNetmask() { final String address = "192.168.0.1"; final String masks[] = new String[] { "255.0.0.0", "255.255.0.0", "255.255.255.0", "255.255.255.248" }; final String bcastAddresses[] = new String[] { "192.255.255.255", "192.168.255.255", "192.168.0.255", "192.168.0.7" }; final String lowAddresses[] = new String[] { "192.0.0.1", "192.168.0.1", "192.168.0.1", "192.168.0.1" }; final String highAddresses[] = new String[] { "192.255.255.254", "192.168.255.254", "192.168.0.254", "192.168.0.6" }; final String nextAddresses[] = new String[] { "192.168.0.2", "192.168.0.2", "192.168.0.2", "192.168.0.2" }; final String previousAddresses[] = new String[] { "192.168.0.0", "192.168.0.0", "192.168.0.0", "192.168.0.0" }; final String networkAddresses[] = new String[] { "192.0.0.0", "192.168.0.0", "192.168.0.0", "192.168.0.0" }; final String cidrSignatures[] = new String[] { "192.168.0.1/8", "192.168.0.1/16", "192.168.0.1/24", "192.168.0.1/29" }; final int usableAddresses[] = new int[] { 16777214, 65534, 254, 6 }; for (int i = 0; i < masks.length; ++i) { SubnetUtils utils = new SubnetUtils(address, masks[i]); SubnetInfo info = utils.getInfo(); assertEquals(bcastAddresses[i], info.getBroadcastAddress()); assertEquals(cidrSignatures[i], info.getCidrSignature()); assertEquals(lowAddresses[i], info.getLowAddress()); assertEquals(highAddresses[i], info.getHighAddress()); assertEquals(nextAddresses[i], info.getNextAddress()); assertEquals(previousAddresses[i], info.getPreviousAddress()); assertEquals(networkAddresses[i], info.getNetworkAddress()); assertEquals(usableAddresses[i], info.getAddressCount()); } } public void testParseSimpleNetmaskExclusive() { String address = "192.168.15.7"; String masks[] = new String[] { "255.255.255.252", "255.255.255.254", "255.255.255.255" }; String bcast[] = new String[] { "192.168.15.7", "192.168.15.7", "192.168.15.7" }; String netwk[] = new String[] { "192.168.15.4", "192.168.15.6", "192.168.15.7" }; String lowAd[] = new String[] { "192.168.15.5", "0.0.0.0", "0.0.0.0" }; String highA[] = new String[] { "192.168.15.6", "0.0.0.0", "0.0.0.0" }; String cidrS[] = new String[] { "192.168.15.7/30", "192.168.15.7/31", "192.168.15.7/32" }; int usableAd[] = new int[] { 2, 0, 0 }; // low and high addresses don't exist for (int i = 0; i < masks.length; ++i) { SubnetUtils utils = new SubnetUtils(address, masks[i]); utils.setInclusiveHostCount(false); SubnetInfo info = utils.getInfo(); assertEquals("ci " + masks[i], cidrS[i], info.getCidrSignature()); assertEquals("bc " + masks[i], bcast[i], info.getBroadcastAddress()); assertEquals("nw " + masks[i], netwk[i], info.getNetworkAddress()); assertEquals("ac " + masks[i], usableAd[i], info.getAddressCount()); assertEquals("lo " + masks[i], lowAd[i], info.getLowAddress()); assertEquals("hi " + masks[i], highA[i], info.getHighAddress()); } } public void testParseSimpleNetmaskInclusive() { String address = "192.168.15.7"; String masks[] = new String[] { "255.255.255.252", "255.255.255.254", "255.255.255.255" }; String bcast[] = new String[] { "192.168.15.7", "192.168.15.7", "192.168.15.7" }; String netwk[] = new String[] { "192.168.15.4", "192.168.15.6", "192.168.15.7" }; String lowAd[] = new String[] { "192.168.15.4", "192.168.15.6", "192.168.15.7" }; String highA[] = new String[] { "192.168.15.7", "192.168.15.7", "192.168.15.7" }; String cidrS[] = new String[] { "192.168.15.7/30", "192.168.15.7/31", "192.168.15.7/32" }; int usableAd[] = new int[] { 4, 2, 1 }; for (int i = 0; i < masks.length; ++i) { SubnetUtils utils = new SubnetUtils(address, masks[i]); utils.setInclusiveHostCount(true); SubnetInfo info = utils.getInfo(); assertEquals("ci " + masks[i], cidrS[i], info.getCidrSignature()); assertEquals("bc " + masks[i], bcast[i], info.getBroadcastAddress()); assertEquals("ac " + masks[i], usableAd[i], info.getAddressCount()); assertEquals("nw " + masks[i], netwk[i], info.getNetworkAddress()); assertEquals("lo " + masks[i], lowAd[i], info.getLowAddress()); assertEquals("hi " + masks[i], highA[i], info.getHighAddress()); } } public void testZeroAddressAndCidr() { SubnetUtils snu = new SubnetUtils("0.0.0.0/0"); assertNotNull(snu); } public void testNET521() { SubnetUtils utils; SubnetInfo info; utils = new SubnetUtils("0.0.0.0/0"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("0.0.0.0", info.getNetmask()); assertEquals(4294967296L, info.getAddressCountLong()); try { info.getAddressCount(); fail("Expected RuntimeException"); } catch (RuntimeException expected) { // ignored } utils = new SubnetUtils("128.0.0.0/1"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("128.0.0.0", info.getNetmask()); assertEquals(2147483648L, info.getAddressCountLong()); try { info.getAddressCount(); fail("Expected RuntimeException"); } catch (RuntimeException expected) { // ignored } // if we exclude the broadcast and network addresses, the count is less than Integer.MAX_VALUE utils.setInclusiveHostCount(false); info = utils.getInfo(); assertEquals(2147483646, info.getAddressCount()); } public void testNET624() { new SubnetUtils("0.0.0.0/0"); new SubnetUtils("0.0.0.0","0.0.0.0"); new SubnetUtils("0.0.0.0","128.0.0.0"); try { new SubnetUtils("0.0.0.0","64.0.0.0"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { // Ignored } try { new SubnetUtils("0.0.0.0","0.0.0.1"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { // Ignored } } public void testNET520() { SubnetUtils utils = new SubnetUtils("0.0.0.0/0"); utils.setInclusiveHostCount(true); SubnetInfo info = utils.getInfo(); assertEquals("0.0.0.0",info.getNetworkAddress()); assertEquals("255.255.255.255",info.getBroadcastAddress()); assertTrue(info.isInRange("127.0.0.0")); utils.setInclusiveHostCount(false); assertTrue(info.isInRange("127.0.0.0")); } public void testNET641() { assertFalse(new SubnetUtils("192.168.1.0/00").getInfo().isInRange("0.0.0.0")); assertFalse(new SubnetUtils("192.168.1.0/30").getInfo().isInRange("0.0.0.0")); assertFalse(new SubnetUtils("192.168.1.0/31").getInfo().isInRange("0.0.0.0")); assertFalse(new SubnetUtils("192.168.1.0/32").getInfo().isInRange("0.0.0.0")); } }
src/test/java/org/apache/commons/net/SubnetUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.commons.net; import org.apache.commons.net.util.SubnetUtils; import org.apache.commons.net.util.SubnetUtils.SubnetInfo; import junit.framework.TestCase; @SuppressWarnings("deprecation") // deliberate use of deprecated methods public class SubnetUtilsTest extends TestCase { // TODO Lower address test public void testAddresses() { SubnetUtils utils = new SubnetUtils("192.168.0.1/29"); SubnetInfo info = utils.getInfo(); assertTrue(info.isInRange("192.168.0.1")); // We don't count the broadcast address as usable assertFalse(info.isInRange("192.168.0.7")); assertFalse(info.isInRange("192.168.0.8")); assertFalse(info.isInRange("10.10.2.1")); assertFalse(info.isInRange("192.168.1.1")); assertFalse(info.isInRange("192.168.0.255")); } /** * Test using the inclusiveHostCount flag, which includes the network and broadcast addresses in host counts */ public void testCidrAddresses() { SubnetUtils utils = new SubnetUtils("192.168.0.1/8"); utils.setInclusiveHostCount(true); SubnetInfo info = utils.getInfo(); assertEquals("255.0.0.0", info.getNetmask()); assertEquals(16777216, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/0"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("0.0.0.0", info.getNetmask()); assertEquals(4294967296L, info.getAddressCountLong()); utils = new SubnetUtils("192.168.0.1/1"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("128.0.0.0", info.getNetmask()); assertEquals(2147483648L, info.getAddressCountLong()); utils = new SubnetUtils("192.168.0.1/9"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.128.0.0", info.getNetmask()); assertEquals(8388608, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/10"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.192.0.0", info.getNetmask()); assertEquals(4194304, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/11"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.224.0.0", info.getNetmask()); assertEquals(2097152, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/12"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.240.0.0", info.getNetmask()); assertEquals(1048576, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/13"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.248.0.0", info.getNetmask()); assertEquals(524288, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/14"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.252.0.0", info.getNetmask()); assertEquals(262144, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/15"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.254.0.0", info.getNetmask()); assertEquals(131072, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/16"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.0.0", info.getNetmask()); assertEquals(65536, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/17"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.128.0", info.getNetmask()); assertEquals(32768, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/18"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.192.0", info.getNetmask()); assertEquals(16384, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/19"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.224.0", info.getNetmask()); assertEquals(8192, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/20"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.240.0", info.getNetmask()); assertEquals(4096, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/21"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.248.0", info.getNetmask()); assertEquals(2048, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/22"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.252.0", info.getNetmask()); assertEquals(1024, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/23"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.254.0", info.getNetmask()); assertEquals(512, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/24"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.0", info.getNetmask()); assertEquals(256, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/25"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.128", info.getNetmask()); assertEquals(128, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/26"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.192", info.getNetmask()); assertEquals(64, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/27"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.224", info.getNetmask()); assertEquals(32, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/28"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.240", info.getNetmask()); assertEquals(16, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/29"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.248", info.getNetmask()); assertEquals(8, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/30"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.252", info.getNetmask()); assertEquals(4, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/31"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.254", info.getNetmask()); assertEquals(2, info.getAddressCount()); utils = new SubnetUtils("192.168.0.1/32"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("255.255.255.255", info.getNetmask()); assertEquals(1, info.getAddressCount()); } public void testNET675() { SubnetUtils utils = new SubnetUtils("192.168.0.15/32"); utils.setInclusiveHostCount(true); SubnetInfo info = utils.getInfo(); assertTrue(info.isInRange("192.168.0.15")); } public void testInvalidMasks() { try { new SubnetUtils("192.168.0.1/33"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { // Ignored } } public void testNET428_31() throws Exception { final SubnetUtils subnetUtils = new SubnetUtils("1.2.3.4/31"); assertEquals(0, subnetUtils.getInfo().getAddressCount()); String[] address = subnetUtils.getInfo().getAllAddresses(); assertNotNull(address); assertEquals(0, address.length); } public void testNET428_32() throws Exception { final SubnetUtils subnetUtils = new SubnetUtils("1.2.3.4/32"); assertEquals(0, subnetUtils.getInfo().getAddressCount()); String[] address = subnetUtils.getInfo().getAllAddresses(); assertNotNull(address); assertEquals(0, address.length); } public void testParseSimpleNetmask() { final String address = "192.168.0.1"; final String masks[] = new String[] { "255.0.0.0", "255.255.0.0", "255.255.255.0", "255.255.255.248" }; final String bcastAddresses[] = new String[] { "192.255.255.255", "192.168.255.255", "192.168.0.255", "192.168.0.7" }; final String lowAddresses[] = new String[] { "192.0.0.1", "192.168.0.1", "192.168.0.1", "192.168.0.1" }; final String highAddresses[] = new String[] { "192.255.255.254", "192.168.255.254", "192.168.0.254", "192.168.0.6" }; final String nextAddresses[] = new String[] { "192.168.0.2", "192.168.0.2", "192.168.0.2", "192.168.0.2" }; final String previousAddresses[] = new String[] { "192.168.0.0", "192.168.0.0", "192.168.0.0", "192.168.0.0" }; final String networkAddresses[] = new String[] { "192.0.0.0", "192.168.0.0", "192.168.0.0", "192.168.0.0" }; final String cidrSignatures[] = new String[] { "192.168.0.1/8", "192.168.0.1/16", "192.168.0.1/24", "192.168.0.1/29" }; final int usableAddresses[] = new int[] { 16777214, 65534, 254, 6 }; for (int i = 0; i < masks.length; ++i) { SubnetUtils utils = new SubnetUtils(address, masks[i]); SubnetInfo info = utils.getInfo(); assertEquals(bcastAddresses[i], info.getBroadcastAddress()); assertEquals(cidrSignatures[i], info.getCidrSignature()); assertEquals(lowAddresses[i], info.getLowAddress()); assertEquals(highAddresses[i], info.getHighAddress()); assertEquals(nextAddresses[i], info.getNextAddress()); assertEquals(previousAddresses[i], info.getPreviousAddress()); assertEquals(networkAddresses[i], info.getNetworkAddress()); assertEquals(usableAddresses[i], info.getAddressCount()); } } public void testParseSimpleNetmaskExclusive() { String address = "192.168.15.7"; String masks[] = new String[] { "255.255.255.252", "255.255.255.254", "255.255.255.255" }; String bcast[] = new String[] { "192.168.15.7", "192.168.15.7", "192.168.15.7" }; String netwk[] = new String[] { "192.168.15.4", "192.168.15.6", "192.168.15.7" }; String lowAd[] = new String[] { "192.168.15.5", "0.0.0.0", "0.0.0.0" }; String highA[] = new String[] { "192.168.15.6", "0.0.0.0", "0.0.0.0" }; String cidrS[] = new String[] { "192.168.15.7/30", "192.168.15.7/31", "192.168.15.7/32" }; int usableAd[] = new int[] { 2, 0, 0 }; // low and high addresses don't exist for (int i = 0; i < masks.length; ++i) { SubnetUtils utils = new SubnetUtils(address, masks[i]); utils.setInclusiveHostCount(false); SubnetInfo info = utils.getInfo(); assertEquals("ci " + masks[i], cidrS[i], info.getCidrSignature()); assertEquals("bc " + masks[i], bcast[i], info.getBroadcastAddress()); assertEquals("nw " + masks[i], netwk[i], info.getNetworkAddress()); assertEquals("ac " + masks[i], usableAd[i], info.getAddressCount()); assertEquals("lo " + masks[i], lowAd[i], info.getLowAddress()); assertEquals("hi " + masks[i], highA[i], info.getHighAddress()); } } public void testParseSimpleNetmaskInclusive() { String address = "192.168.15.7"; String masks[] = new String[] { "255.255.255.252", "255.255.255.254", "255.255.255.255" }; String bcast[] = new String[] { "192.168.15.7", "192.168.15.7", "192.168.15.7" }; String netwk[] = new String[] { "192.168.15.4", "192.168.15.6", "192.168.15.7" }; String lowAd[] = new String[] { "192.168.15.4", "192.168.15.6", "192.168.15.7" }; String highA[] = new String[] { "192.168.15.7", "192.168.15.7", "192.168.15.7" }; String cidrS[] = new String[] { "192.168.15.7/30", "192.168.15.7/31", "192.168.15.7/32" }; int usableAd[] = new int[] { 4, 2, 1 }; for (int i = 0; i < masks.length; ++i) { SubnetUtils utils = new SubnetUtils(address, masks[i]); utils.setInclusiveHostCount(true); SubnetInfo info = utils.getInfo(); assertEquals("ci " + masks[i], cidrS[i], info.getCidrSignature()); assertEquals("bc " + masks[i], bcast[i], info.getBroadcastAddress()); assertEquals("ac " + masks[i], usableAd[i], info.getAddressCount()); assertEquals("nw " + masks[i], netwk[i], info.getNetworkAddress()); assertEquals("lo " + masks[i], lowAd[i], info.getLowAddress()); assertEquals("hi " + masks[i], highA[i], info.getHighAddress()); } } public void testZeroAddressAndCidr() { SubnetUtils snu = new SubnetUtils("0.0.0.0/0"); assertNotNull(snu); } public void testNET521() { SubnetUtils utils; SubnetInfo info; utils = new SubnetUtils("0.0.0.0/0"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("0.0.0.0", info.getNetmask()); assertEquals(4294967296L, info.getAddressCountLong()); try { info.getAddressCount(); fail("Expected RuntimeException"); } catch (RuntimeException expected) { // ignored } utils = new SubnetUtils("128.0.0.0/1"); utils.setInclusiveHostCount(true); info = utils.getInfo(); assertEquals("128.0.0.0", info.getNetmask()); assertEquals(2147483648L, info.getAddressCountLong()); try { info.getAddressCount(); fail("Expected RuntimeException"); } catch (RuntimeException expected) { // ignored } // if we exclude the broadcast and network addresses, the count is less than Integer.MAX_VALUE utils.setInclusiveHostCount(false); info = utils.getInfo(); assertEquals(2147483646, info.getAddressCount()); } public void testNET624() { new SubnetUtils("0.0.0.0/0"); new SubnetUtils("0.0.0.0","0.0.0.0"); new SubnetUtils("0.0.0.0","128.0.0.0"); try { new SubnetUtils("0.0.0.0","64.0.0.0"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { // Ignored } try { new SubnetUtils("0.0.0.0","0.0.0.1"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { // Ignored } } public void testNET520() { SubnetUtils utils = new SubnetUtils("0.0.0.0/0"); utils.setInclusiveHostCount(true); SubnetInfo info = utils.getInfo(); assertEquals("0.0.0.0",info.getNetworkAddress()); assertEquals("255.255.255.255",info.getBroadcastAddress()); assertTrue(info.isInRange("127.0.0.0")); utils.setInclusiveHostCount(false); assertTrue(info.isInRange("127.0.0.0")); } public void testNET641() { assertFalse(new SubnetUtils("192.168.1.0/00").getInfo().isInRange("0.0.0.0")); assertFalse(new SubnetUtils("192.168.1.0/30").getInfo().isInRange("0.0.0.0")); assertFalse(new SubnetUtils("192.168.1.0/31").getInfo().isInRange("0.0.0.0")); assertFalse(new SubnetUtils("192.168.1.0/32").getInfo().isInRange("0.0.0.0")); } }
Test for invalid report
src/test/java/org/apache/commons/net/SubnetUtilsTest.java
Test for invalid report
<ide><path>rc/test/java/org/apache/commons/net/SubnetUtilsTest.java <ide> assertTrue(info.isInRange("192.168.0.15")); <ide> } <ide> <add> public void testNET679() { <add> SubnetUtils utils = new SubnetUtils("10.213.160.0/16"); <add> utils.setInclusiveHostCount(true); <add> SubnetInfo info = utils.getInfo(); <add> assertTrue(info.isInRange("10.213.0.0")); <add> assertTrue(info.isInRange("10.213.255.255")); <add> } <add> <ide> public void testInvalidMasks() { <ide> try { <ide> new SubnetUtils("192.168.0.1/33");
Java
apache-2.0
e1a557e06bbd19252525305d17b28f9271d01aba
0
fcrepo4-exts/fcrepo-camel,daniel-dgi/fcrepo-camel
/** * Copyright 2014 DuraSpace, Inc. * * 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. */ package org.fcrepo.camel; import org.apache.camel.Consumer; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.RuntimeCamelException; import org.apache.camel.api.management.ManagedResource; import org.apache.camel.api.management.ManagedAttribute; import org.apache.camel.impl.DefaultEndpoint; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; /** * Represents a Fedora endpoint. * @author Aaron Coburn * @since October 20, 2014 */ @ManagedResource(description = "Managed FcrepoEndpoint") @UriEndpoint(scheme = "fcrepo") public class FedoraEndpoint extends DefaultEndpoint { public static final String FCREPO_BASEURL = "FCREPO_BASEURL"; public static final String FCREPO_IDENTIFIER = "FCREPO_IDENTIFIER"; public static final String DEFAULT_CONTENT_TYPE = "application/rdf+xml"; private volatile String baseUrl = ""; @UriParam private volatile String contentType = null; @UriParam private volatile String accept = null; @UriParam private volatile String transform = null; @UriParam private volatile String authUsername = null; @UriParam private volatile String authPassword = null; @UriParam private volatile String authHost = null; @UriParam private volatile Boolean tombstone = false; @UriParam private volatile Boolean metadata = true; @UriParam private volatile Boolean throwExceptionOnFailure = true; /** * Create a FedoraEndpoint with a uri, path and component * @param uri the endpoint uri (without path values) * @param remaining any path values on the endpoint uri * @param component an existing component value */ public FedoraEndpoint(final String uri, final String remaining, final FedoraComponent component) { super(uri, component); this.setBaseUrl(remaining); } /** * Create a producer endpoint. */ @Override public Producer createProducer() { return new FedoraProducer(this); } /** * This component does not implement a consumer endpoint. */ @Override public Consumer createConsumer(final Processor processor) { throw new RuntimeCamelException("Cannot produce to a FedoraEndpoint: " + getEndpointUri()); } /** * Define the component as a singleton */ @Override public boolean isSingleton() { return true; } /** * baseUrl setter * @param url the baseUrl string */ public void setBaseUrl(final String url) { this.baseUrl = url; } /** * baseUrl getter */ public String getBaseUrl() { return baseUrl; } /** * accept setter * @param type the content-type for Accept headers */ @ManagedAttribute(description = "Accept: Header") public void setAccept(final String type) { this.accept = type.replaceAll(" ", "+"); } /** * accept getter */ @ManagedAttribute(description = "Accept: Header") public String getAccept() { return accept; } /** * contentType setter * @param type the content-type for Content-Type headers */ @ManagedAttribute(description = "Content-Type: Header") public void setContentType(final String type) { this.contentType = type.replaceAll(" ", "+"); } /** * contentType getter */ @ManagedAttribute(description = "Content-Type: Header") public String getContentType() { return contentType; } /** * authUsername setter * @param username used for authentication */ @ManagedAttribute(description = "Username for authentication") public void setAuthUsername(final String username) { this.authUsername = username; } /** * authUsername getter */ @ManagedAttribute(description = "Username for authentication") public String getAuthUsername() { return authUsername; } /** * authPassword setter * @param password used for authentication */ @ManagedAttribute(description = "Password for authentication") public void setAuthPassword(final String password) { this.authPassword = password; } /** * authPassword getter */ @ManagedAttribute(description = "Password for authentication") public String getAuthPassword() { return authPassword; } /** * authHost setter * @param host used for authentication */ @ManagedAttribute(description = "Hostname for authentication") public void setAuthHost(final String host) { this.authHost = host; } /** * authHost getter */ @ManagedAttribute(description = "Hostname for authentication") public String getAuthHost() { return authHost; } /** * metadata setter * @param metadata whether to retrieve rdf metadata for non-rdf nodes */ @ManagedAttribute(description = "Whether to retrieve the /fcr:metadata endpoint for Binary nodes") public void setMetadata(final String metadata) { this.metadata = Boolean.valueOf(metadata); } /** * metadata getter */ @ManagedAttribute(description = "Whether to retrieve the /fcr:metadata endpoint for Binary nodes") public Boolean getMetadata() { return metadata; } /** * throwExceptionOnFailure setter * @param throwOnFailure whether non-2xx HTTP response codes throw exceptions */ @ManagedAttribute(description = "Whether non 2xx response codes should throw an exception") public void setThrowExceptionOnFailure(final String throwOnFailure) { this.throwExceptionOnFailure = Boolean.valueOf(throwOnFailure); } /** * throwExceptionOnFailure getter */ @ManagedAttribute(description = "Whether non 2xx response codes should throw an exception") public Boolean getThrowExceptionOnFailure() { return throwExceptionOnFailure; } /** * transform setter * @param transform define an LD-Path transform program for converting RDF to JSON */ @ManagedAttribute(description = "The LDPath transform program to use") public void setTransform(final String transform) { this.transform = transform; } /** * transform getter */ @ManagedAttribute(description = "The LDPath transform program to use") public String getTransform() { return transform; } /** * tombstone setter * @param tombstone whether to access the /fcr:tombstone endpoint for a resource */ @ManagedAttribute(description = "Whether to use the /fcr:tombstone endpoint on objects") public void setTombstone(final String tombstone) { this.tombstone = Boolean.valueOf(tombstone); } /** * tombstone getter */ @ManagedAttribute(description = "Whether to use the /fcr:tombstone endpoint on objects") public Boolean getTombstone() { return tombstone; } }
src/main/java/org/fcrepo/camel/FedoraEndpoint.java
/** * Copyright 2014 DuraSpace, Inc. * * 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. */ package org.fcrepo.camel; import org.apache.camel.Consumer; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.RuntimeCamelException; import org.apache.camel.impl.DefaultEndpoint; /** * Represents a Fedora endpoint. * @author Aaron Coburn * @since October 20, 2014 */ public class FedoraEndpoint extends DefaultEndpoint { public static final String FCREPO_BASEURL = "FCREPO_BASEURL"; public static final String FCREPO_IDENTIFIER = "FCREPO_IDENTIFIER"; public static final String DEFAULT_CONTENT_TYPE = "application/rdf+xml"; private volatile String contentType = null; private volatile String accept = null; private volatile String baseUrl = ""; private volatile String transform = null; private volatile String authUsername = null; private volatile String authPassword = null; private volatile String authHost = null; private volatile Boolean tombstone = false; private volatile Boolean metadata = true; private volatile Boolean throwExceptionOnFailure = true; /** * Create a FedoraEndpoint with a uri, path and component * @param uri the endpoint uri (without path values) * @param remaining any path values on the endpoint uri * @param component an existing component value */ public FedoraEndpoint(final String uri, final String remaining, final FedoraComponent component) { super(uri, component); this.setBaseUrl(remaining); } /** * Create a producer endpoint. */ @Override public Producer createProducer() { return new FedoraProducer(this); } /** * This component does not implement a consumer endpoint. */ @Override public Consumer createConsumer(final Processor processor) { throw new RuntimeCamelException("Cannot produce to a FedoraEndpoint: " + getEndpointUri()); } /** * Define the component as a singleton */ @Override public boolean isSingleton() { return true; } /** * baseUrl setter * @param url the baseUrl string */ public void setBaseUrl(final String url) { this.baseUrl = url; } /** * baseUrl getter */ public String getBaseUrl() { return baseUrl; } /** * accept setter * @param type the content-type for Accept headers */ public void setAccept(final String type) { this.accept = type.replaceAll(" ", "+"); } /** * accept getter */ public String getAccept() { return accept; } /** * contentType setter * @param type the content-type for Content-Type headers */ public void setContentType(final String type) { this.contentType = type.replaceAll(" ", "+"); } /** * contentType getter */ public String getContentType() { return contentType; } /** * authUsername setter * @param username used for authentication */ public void setAuthUsername(final String username) { this.authUsername = username; } /** * authUsername getter */ public String getAuthUsername() { return authUsername; } /** * authPassword setter * @param password used for authentication */ public void setAuthPassword(final String password) { this.authPassword = password; } /** * authPassword getter */ public String getAuthPassword() { return authPassword; } /** * authHost setter * @param host used for authentication */ public void setAuthHost(final String host) { this.authHost = host; } /** * authHost getter */ public String getAuthHost() { return authHost; } /** * metadata setter * @param metadata whether to retrieve rdf metadata for non-rdf nodes */ public void setMetadata(final String metadata) { this.metadata = Boolean.valueOf(metadata); } /** * metadata getter */ public Boolean getMetadata() { return metadata; } /** * throwExceptionOnFailure setter * @param throwOnFailure whether non-2xx HTTP response codes throw exceptions */ public void setThrowExceptionOnFailure(final String throwOnFailure) { this.throwExceptionOnFailure = Boolean.valueOf(throwOnFailure); } /** * throwExceptionOnFailure getter */ public Boolean getThrowExceptionOnFailure() { return throwExceptionOnFailure; } /** * transform setter * @param transform define an LD-Path transform program for converting RDF to JSON */ public void setTransform(final String transform) { this.transform = transform; } /** * transform getter */ public String getTransform() { return transform; } /** * tombstone setter * @param tombstone whether to access the /fcr:tombstone endpoint for a resource */ public void setTombstone(final String tombstone) { this.tombstone = Boolean.valueOf(tombstone); } /** * tombstone getter */ public Boolean getTombstone() { return tombstone; } }
added endpoint annotations for camel; see: http://camel.apache.org/endpoint-annotations.html
src/main/java/org/fcrepo/camel/FedoraEndpoint.java
added endpoint annotations for camel; see: http://camel.apache.org/endpoint-annotations.html
<ide><path>rc/main/java/org/fcrepo/camel/FedoraEndpoint.java <ide> import org.apache.camel.Processor; <ide> import org.apache.camel.Producer; <ide> import org.apache.camel.RuntimeCamelException; <add>import org.apache.camel.api.management.ManagedResource; <add>import org.apache.camel.api.management.ManagedAttribute; <ide> import org.apache.camel.impl.DefaultEndpoint; <add>import org.apache.camel.spi.UriEndpoint; <add>import org.apache.camel.spi.UriParam; <ide> <ide> /** <ide> * Represents a Fedora endpoint. <ide> * @author Aaron Coburn <ide> * @since October 20, 2014 <ide> */ <add>@ManagedResource(description = "Managed FcrepoEndpoint") <add>@UriEndpoint(scheme = "fcrepo") <ide> public class FedoraEndpoint extends DefaultEndpoint { <ide> <ide> public static final String FCREPO_BASEURL = "FCREPO_BASEURL"; <ide> <ide> public static final String DEFAULT_CONTENT_TYPE = "application/rdf+xml"; <ide> <add> private volatile String baseUrl = ""; <add> <add> @UriParam <ide> private volatile String contentType = null; <ide> <add> @UriParam <ide> private volatile String accept = null; <ide> <del> private volatile String baseUrl = ""; <del> <add> @UriParam <ide> private volatile String transform = null; <ide> <add> @UriParam <ide> private volatile String authUsername = null; <ide> <add> @UriParam <ide> private volatile String authPassword = null; <ide> <add> @UriParam <ide> private volatile String authHost = null; <ide> <add> @UriParam <ide> private volatile Boolean tombstone = false; <ide> <add> @UriParam <ide> private volatile Boolean metadata = true; <ide> <add> @UriParam <ide> private volatile Boolean throwExceptionOnFailure = true; <ide> <ide> /** <ide> * accept setter <ide> * @param type the content-type for Accept headers <ide> */ <add> @ManagedAttribute(description = "Accept: Header") <ide> public void setAccept(final String type) { <ide> this.accept = type.replaceAll(" ", "+"); <ide> } <ide> /** <ide> * accept getter <ide> */ <add> @ManagedAttribute(description = "Accept: Header") <ide> public String getAccept() { <ide> return accept; <ide> } <ide> * contentType setter <ide> * @param type the content-type for Content-Type headers <ide> */ <add> @ManagedAttribute(description = "Content-Type: Header") <ide> public void setContentType(final String type) { <ide> this.contentType = type.replaceAll(" ", "+"); <ide> } <ide> /** <ide> * contentType getter <ide> */ <add> @ManagedAttribute(description = "Content-Type: Header") <ide> public String getContentType() { <ide> return contentType; <ide> } <ide> * authUsername setter <ide> * @param username used for authentication <ide> */ <add> @ManagedAttribute(description = "Username for authentication") <ide> public void setAuthUsername(final String username) { <ide> this.authUsername = username; <ide> } <ide> /** <ide> * authUsername getter <ide> */ <add> @ManagedAttribute(description = "Username for authentication") <ide> public String getAuthUsername() { <ide> return authUsername; <ide> } <ide> * authPassword setter <ide> * @param password used for authentication <ide> */ <add> @ManagedAttribute(description = "Password for authentication") <ide> public void setAuthPassword(final String password) { <ide> this.authPassword = password; <ide> } <ide> /** <ide> * authPassword getter <ide> */ <add> @ManagedAttribute(description = "Password for authentication") <ide> public String getAuthPassword() { <ide> return authPassword; <ide> } <ide> * authHost setter <ide> * @param host used for authentication <ide> */ <add> @ManagedAttribute(description = "Hostname for authentication") <ide> public void setAuthHost(final String host) { <ide> this.authHost = host; <ide> } <ide> /** <ide> * authHost getter <ide> */ <add> @ManagedAttribute(description = "Hostname for authentication") <ide> public String getAuthHost() { <ide> return authHost; <ide> } <ide> * metadata setter <ide> * @param metadata whether to retrieve rdf metadata for non-rdf nodes <ide> */ <add> @ManagedAttribute(description = "Whether to retrieve the /fcr:metadata endpoint for Binary nodes") <ide> public void setMetadata(final String metadata) { <ide> this.metadata = Boolean.valueOf(metadata); <ide> } <ide> /** <ide> * metadata getter <ide> */ <add> @ManagedAttribute(description = "Whether to retrieve the /fcr:metadata endpoint for Binary nodes") <ide> public Boolean getMetadata() { <ide> return metadata; <ide> } <ide> * throwExceptionOnFailure setter <ide> * @param throwOnFailure whether non-2xx HTTP response codes throw exceptions <ide> */ <add> @ManagedAttribute(description = "Whether non 2xx response codes should throw an exception") <ide> public void setThrowExceptionOnFailure(final String throwOnFailure) { <ide> this.throwExceptionOnFailure = Boolean.valueOf(throwOnFailure); <ide> } <ide> /** <ide> * throwExceptionOnFailure getter <ide> */ <add> @ManagedAttribute(description = "Whether non 2xx response codes should throw an exception") <ide> public Boolean getThrowExceptionOnFailure() { <ide> return throwExceptionOnFailure; <ide> } <ide> * transform setter <ide> * @param transform define an LD-Path transform program for converting RDF to JSON <ide> */ <add> @ManagedAttribute(description = "The LDPath transform program to use") <ide> public void setTransform(final String transform) { <ide> this.transform = transform; <ide> } <ide> /** <ide> * transform getter <ide> */ <add> @ManagedAttribute(description = "The LDPath transform program to use") <ide> public String getTransform() { <ide> return transform; <ide> } <ide> * tombstone setter <ide> * @param tombstone whether to access the /fcr:tombstone endpoint for a resource <ide> */ <add> @ManagedAttribute(description = "Whether to use the /fcr:tombstone endpoint on objects") <ide> public void setTombstone(final String tombstone) { <ide> this.tombstone = Boolean.valueOf(tombstone); <ide> } <ide> /** <ide> * tombstone getter <ide> */ <add> @ManagedAttribute(description = "Whether to use the /fcr:tombstone endpoint on objects") <ide> public Boolean getTombstone() { <ide> return tombstone; <ide> }
JavaScript
mit
817006d940367dc1834f12cd4a17f747ef53541e
0
notmessenger/sl-ember-components,softlayer/sl-ember-components,softlayer/sl-ember-components,notmessenger/sl-ember-components
import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; import { skip } from 'qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent( 'sl-textarea', 'Integration | Component | sl textarea', { integration: true }); test( 'Default classes are applied', function( assert ) { this.render( hbs` {{#sl-textarea}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).prop( 'class' ), 'ember-view form-group sl-textarea', 'Rendered component has expected classes' ); }); test( '"value" property is supported', function( assert ) { this.set( 'value', 'testBoundValue' ); this.render( hbs` {{#sl-textarea value=value}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).find( 'textarea' ).val(), this.get( 'value' ), 'Text area value is expected value' ); }); test( '"wrap" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea wrap="hard"}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).find( 'textarea' ).attr( 'wrap' ), 'hard', 'Textarea wrap attribute is expected value' ); }); test( '"tabindex" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea tabindex="2"}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).find( 'textarea' ).attr( 'tabindex' ), '2', 'Textarea tabindex attribute is expected value' ); }); test( '"spellcheck" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea spellcheck=true}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).find( 'textarea' ).attr( 'spellcheck' ), 'true', 'Textarea spellcheck attribute is expected value' ); }); test( '"autofocus" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea autofocus=true}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).find( 'textarea' ).attr( 'autofocus' ), 'autofocus', 'Textarea autofocus attribute is present' ); }); test( '"cols" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea cols="8"}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).find( 'textarea' ).attr( 'cols' ), '8', 'Textarea cols attribute is expected value' ); }); test( '"disabled" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea disabled=true}} {{/sl-textarea}} ` ); assert.ok( this.$( '>:first-child' ).find( 'textarea' ).is( ':disabled' ), 'Textarea is disabled as expected' ); }); test( '"maxlength" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea maxlength="12"}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).find( 'textarea' ).attr( 'maxlength' ), '12', 'Textarea maxlength attribute is expected value' ); }); test( '"placeholder" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea placeholder="placeholder text"}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).find( 'textarea' ).attr( 'placeholder' ), 'placeholder text', 'Textarea placeholder attribute is expected value' ); }); test( '"readonly" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea readonly=true}} {{/sl-textarea}} ` ); assert.ok( this.$( '>:first-child' ).find( 'textarea' ).prop( 'readonly' ), 'Textarea is readonly as expected' ); }); test( '"rows" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea rows="4"}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).find( 'textarea' ).attr( 'rows' ), '4', 'Textarea rows attribute is expected value' ); }); test( '"helpText" is rendered if populated', function( assert ) { this.set( 'helpText', 'Help Text' ); this.render( hbs` {{#sl-textarea helpText=helpText}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).find( '.help-block' ).prop( 'tagName' ), 'P', 'Help text block is rendered as a <p>' ); assert.strictEqual( Ember.$.trim( this.$( '>:first-child' ).find( '.help-block' ).text() ), this.get( 'helpText' ), 'Help text block text is expected value' ); }); test( '"optional" and "required" elements are rendered if populated along with "label" property', function( assert ) { this.render( hbs` {{#sl-textarea label='Test Label' optional=true required=true}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).find( 'label > .text-info' ).prop( 'tagName' ), 'SMALL', "Label's text-info <small> is rendered" ); assert.strictEqual( this.$( '>:first-child' ).find( 'label > .text-danger' ).prop( 'tagName' ), 'SMALL', "Label's text-danger <small> is rendered" ); }); test( 'If "label" property is not populated, "optional" and "required" elements are not rendered even if populated', function( assert ) { this.render( hbs` {{#sl-textarea optional=true required=true}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).find( 'label > .text-info' ).length, 0, "Label's text-info is not rendered" ); assert.strictEqual( this.$( '>:first-child' ).find( 'label > .text-danger' ).length, 0, "Label's text-danger is not rendered" ); } ); test( 'If "label" property is not populated, label element is not rendered', function( assert ) { this.render( hbs` {{#sl-textarea label=""}} {{/sl-textarea}} ` ); assert.strictEqual( Ember.typeOf( this.$( '>:first-child' ).find( 'label' ).prop( 'for' ) ), 'undefined', 'Label element is not rendered' ); }); test( 'If "label" property is populated, label element is rendered', function( assert ) { this.set( 'label', 'test' ); this.render( hbs` {{#sl-textarea label="test"}} {{/sl-textarea}} ` ); const label = this.$( 'label[for="' + this.$( '>:first-child' ).find( 'textarea' ).prop( 'id' ) + '"]' ); assert.strictEqual( label.length, 1, 'Label is present' ); assert.strictEqual( Ember.$.trim( label.text() ), this.get( 'label' ), 'Label text is expected value' ); }); test( 'If "label" property is populated, "for" attribute is expected value', function( assert ) { this.set( 'label', 'Test Label' ); this.render( hbs` {{#sl-textarea label=label}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).find( 'label' ).prop( 'for' ), this.$( '>:first-child' ).find( 'textarea' ).prop( 'id' ), 'Label "for" property matches textarea\'s "id" property' ); }); test( '"selectionStart" is supported', function( assert ) { this.render( hbs` {{#sl-textarea selectionStart=2 value="testValue"}} {{/sl-textarea}} ` ); this.$( '>:first-child' ).find( 'textarea' ).get( 0 ).setSelectionRange( 2, 8 ); assert.strictEqual( this.$( '>:first-child' ).find( 'textarea' ).prop( 'selectionStart' ), 2, 'Textarea "selectionStart" property is expected value' ); }); test( '"selectionEnd" is supported', function( assert ) { this.render( hbs` {{#sl-textarea selectionEnd=8 value="testValue"}} {{/sl-textarea}} ` ); this.$( '>:first-child' ).find( 'textarea' ).get( 0 ).setSelectionRange( 2, 8 ); assert.strictEqual( this.$( '>:first-child' ).find( 'textarea' ).prop( 'selectionEnd' ), 8, 'Textarea "selectionEnd" property is expected value' ); }); // This test requires full browser support skip( 'selectionDirection is supported' );
tests/integration/components/sl-textarea-test.js
import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; import { skip } from 'qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent( 'sl-textarea', 'Integration | Component | sl textarea', { integration: true }); test( 'Default classes are applied', function( assert ) { this.render( hbs` {{#sl-textarea}} {{/sl-textarea}} ` ); assert.equal( this.$( '>:first-child' ).prop( 'class' ), [ 'ember-view form-group sl-textarea' ], 'Rendered component has expected classes' ); }); test( '"value" property is supported', function( assert ) { this.set( 'value', 'testBoundValue' ); this.render( hbs` {{#sl-textarea value=value}} {{/sl-textarea}} ` ); assert.equal( this.$( '>:first-child' ).find( 'textarea' ).val(), this.get( 'value' ), 'Text area value is expected value' ); }); test( '"wrap" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea wrap="hard"}} {{/sl-textarea}} ` ); assert.equal( this.$( '>:first-child' ).find( 'textarea' ).attr( 'wrap' ), 'hard', 'Textarea wrap attribute is expected value' ); }); test( '"tabindex" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea tabindex="2"}} {{/sl-textarea}} ` ); assert.equal( this.$( '>:first-child' ).find( 'textarea' ).attr( 'tabindex' ), '2', 'Textarea tabindex attribute is expected value' ); }); test( '"spellcheck" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea spellcheck=true}} {{/sl-textarea}} ` ); assert.equal( this.$( '>:first-child' ).find( 'textarea' ).attr( 'spellcheck' ), 'true', 'Textarea spellcheck attribute is expected value' ); }); test( '"autofocus" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea autofocus=true}} {{/sl-textarea}} ` ); assert.equal( this.$( '>:first-child' ).find( 'textarea' ).attr( 'autofocus' ), 'autofocus', 'Textarea autofocus attribute is present' ); }); test( '"cols" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea cols="8"}} {{/sl-textarea}} ` ); assert.equal( this.$( '>:first-child' ).find( 'textarea' ).attr( 'cols' ), '8', 'Textarea cols attribute is expected value' ); }); test( '"disabled" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea disabled=true}} {{/sl-textarea}} ` ); assert.ok( this.$( '>:first-child' ).find( 'textarea' ).is( ':disabled' ), 'Textarea is disabled as expected' ); }); test( '"maxlength" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea maxlength="12"}} {{/sl-textarea}} ` ); assert.equal( this.$( '>:first-child' ).find( 'textarea' ).attr( 'maxlength' ), '12', 'Textarea maxlength attribute is expected value' ); }); test( '"placeholder" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea placeholder="placeholder text"}} {{/sl-textarea}} ` ); assert.equal( this.$( '>:first-child' ).find( 'textarea' ).attr( 'placeholder' ), 'placeholder text', 'Textarea placeholder attribute is expected value' ); }); test( '"readonly" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea readonly=true}} {{/sl-textarea}} ` ); assert.ok( this.$( '>:first-child' ).find( 'textarea' ).prop( 'readonly' ), 'Textarea is readonly as expected' ); }); test( '"rows" property is supported', function( assert ) { this.render( hbs` {{#sl-textarea rows="4"}} {{/sl-textarea}} ` ); assert.equal( this.$( '>:first-child' ).find( 'textarea' ).attr( 'rows' ), '4', 'Textarea rows attribute is expected value' ); }); test( '"helpText" is rendered if populated', function( assert ) { this.set( 'helpText', 'Help Text' ); this.render( hbs` {{#sl-textarea helpText=helpText}} {{/sl-textarea}} ` ); assert.equal( this.$( '>:first-child' ).find( '.help-block' ).prop( 'tagName' ), 'P', 'Help text block is rendered as a <p>' ); assert.equal( Ember.$.trim( this.$( '>:first-child' ).find( '.help-block' ).text() ), this.get( 'helpText' ), 'Help text block text is expected value' ); }); test( '"optional" and "required" elements are rendered if populated along with "label" property', function( assert ) { this.render( hbs` {{#sl-textarea label='Test Label' optional=true required=true}} {{/sl-textarea}} ` ); assert.equal( this.$( '>:first-child' ).find( 'label > .text-info' ).prop( 'tagName' ), 'SMALL', "Label's text-info <small> is rendered" ); assert.equal( this.$( '>:first-child' ).find( 'label > .text-danger' ).prop( 'tagName' ), 'SMALL', "Label's text-danger <small> is rendered" ); }); test( 'If "label" property is not populated, "optional" and "required" elements are not rendered even if populated', function( assert ) { this.render( hbs` {{#sl-textarea optional=true required=true}} {{/sl-textarea}} ` ); assert.strictEqual( this.$( '>:first-child' ).find( 'label > .text-info' ).length, 0, "Label's text-info is not rendered" ); assert.strictEqual( this.$( '>:first-child' ).find( 'label > .text-danger' ).length, 0, "Label's text-danger is not rendered" ); } ); test( 'If "label" property is not populated, label element is not rendered', function( assert ) { this.render( hbs` {{#sl-textarea label=""}} {{/sl-textarea}} ` ); assert.equal( Ember.typeOf( this.$( '>:first-child' ).find( 'label' ).prop( 'for' ) ), 'undefined', 'Label element is not rendered' ); }); test( 'If "label" property is populated, label element is rendered', function( assert ) { this.set( 'label', 'test' ); this.render( hbs` {{#sl-textarea label="test"}} {{/sl-textarea}} ` ); const label = this.$( 'label[for="' + this.$( '>:first-child' ).find( 'textarea' ).prop( 'id' ) + '"]' ); assert.equal( label.length, 1, 'Label is present' ); assert.equal( Ember.$.trim( label.text() ), this.get( 'label' ), 'Label text is expected value' ); }); test( 'If "label" property is populated, "for" attribute is expected value', function( assert ) { this.set( 'label', 'Test Label' ); this.render( hbs` {{#sl-textarea label=label}} {{/sl-textarea}} ` ); assert.equal( this.$( '>:first-child' ).find( 'label' ).prop( 'for' ), this.$( '>:first-child' ).find( 'textarea' ).prop( 'id' ), 'Label "for" property matches textarea\'s "id" property' ); }); test( '"selectionStart" is supported', function( assert ) { this.render( hbs` {{#sl-textarea selectionStart=2 value="testValue"}} {{/sl-textarea}} ` ); this.$( '>:first-child' ).find( 'textarea' ).get( 0 ).setSelectionRange( 2, 8 ); assert.equal( this.$( '>:first-child' ).find( 'textarea' ).prop( 'selectionStart' ), 2, 'Textarea "selectionStart" property is expected value' ); }); test( '"selectionEnd" is supported', function( assert ) { this.render( hbs` {{#sl-textarea selectionEnd=8 value="testValue"}} {{/sl-textarea}} ` ); this.$( '>:first-child' ).find( 'textarea' ).get( 0 ).setSelectionRange( 2, 8 ); assert.equal( this.$( '>:first-child' ).find( 'textarea' ).prop( 'selectionEnd' ), 8, 'Textarea "selectionEnd" property is expected value' ); }); // This test requires full browser support skip( 'selectionDirection is supported' );
fixed strict equal assertions and fixed array test for default classes
tests/integration/components/sl-textarea-test.js
fixed strict equal assertions and fixed array test for default classes
<ide><path>ests/integration/components/sl-textarea-test.js <ide> {{/sl-textarea}} <ide> ` ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).prop( 'class' ), <del> [ 'ember-view form-group sl-textarea' ], <add> 'ember-view form-group sl-textarea', <ide> 'Rendered component has expected classes' <ide> ); <ide> }); <ide> {{/sl-textarea}} <ide> ` ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( 'textarea' ).val(), <ide> this.get( 'value' ), <ide> 'Text area value is expected value' <ide> {{/sl-textarea}} <ide> ` ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( 'textarea' ).attr( 'wrap' ), <ide> 'hard', <ide> 'Textarea wrap attribute is expected value' <ide> {{/sl-textarea}} <ide> ` ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( 'textarea' ).attr( 'tabindex' ), <ide> '2', <ide> 'Textarea tabindex attribute is expected value' <ide> {{/sl-textarea}} <ide> ` ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( 'textarea' ).attr( 'spellcheck' ), <ide> 'true', <ide> 'Textarea spellcheck attribute is expected value' <ide> {{#sl-textarea autofocus=true}} <ide> {{/sl-textarea}} <ide> ` ); <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( 'textarea' ).attr( 'autofocus' ), <ide> 'autofocus', <ide> 'Textarea autofocus attribute is present' <ide> {{/sl-textarea}} <ide> ` ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( 'textarea' ).attr( 'cols' ), <ide> '8', <ide> 'Textarea cols attribute is expected value' <ide> {{/sl-textarea}} <ide> ` ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( 'textarea' ).attr( 'maxlength' ), <ide> '12', <ide> 'Textarea maxlength attribute is expected value' <ide> {{/sl-textarea}} <ide> ` ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( 'textarea' ).attr( 'placeholder' ), <ide> 'placeholder text', <ide> 'Textarea placeholder attribute is expected value' <ide> {{/sl-textarea}} <ide> ` ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( 'textarea' ).attr( 'rows' ), <ide> '4', <ide> 'Textarea rows attribute is expected value' <ide> {{/sl-textarea}} <ide> ` ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( '.help-block' ).prop( 'tagName' ), <ide> 'P', <ide> 'Help text block is rendered as a <p>' <ide> ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> Ember.$.trim( this.$( '>:first-child' ).find( '.help-block' ).text() ), <ide> this.get( 'helpText' ), <ide> 'Help text block text is expected value' <ide> {{/sl-textarea}} <ide> ` ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( 'label > .text-info' ).prop( 'tagName' ), <ide> 'SMALL', <ide> "Label's text-info <small> is rendered" <ide> ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( 'label > .text-danger' ).prop( 'tagName' ), <ide> 'SMALL', <ide> "Label's text-danger <small> is rendered" <ide> {{#sl-textarea label=""}} <ide> {{/sl-textarea}} <ide> ` ); <del> assert.equal( <add> assert.strictEqual( <ide> Ember.typeOf( this.$( '>:first-child' ).find( 'label' ).prop( 'for' ) ), <ide> 'undefined', <ide> 'Label element is not rendered' <ide> 'label[for="' + this.$( '>:first-child' ).find( 'textarea' ).prop( 'id' ) + '"]' <ide> ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> label.length, <ide> 1, <ide> 'Label is present' <ide> ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> Ember.$.trim( label.text() ), <ide> this.get( 'label' ), <ide> 'Label text is expected value' <ide> {{/sl-textarea}} <ide> ` ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( 'label' ).prop( 'for' ), <ide> this.$( '>:first-child' ).find( 'textarea' ).prop( 'id' ), <ide> 'Label "for" property matches textarea\'s "id" property' <ide> ` ); <ide> this.$( '>:first-child' ).find( 'textarea' ).get( 0 ).setSelectionRange( 2, 8 ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( 'textarea' ).prop( 'selectionStart' ), <ide> 2, <ide> 'Textarea "selectionStart" property is expected value' <ide> <ide> this.$( '>:first-child' ).find( 'textarea' ).get( 0 ).setSelectionRange( 2, 8 ); <ide> <del> assert.equal( <add> assert.strictEqual( <ide> this.$( '>:first-child' ).find( 'textarea' ).prop( 'selectionEnd' ), <ide> 8, <ide> 'Textarea "selectionEnd" property is expected value'
JavaScript
apache-2.0
df8f6e934cd5f4edebaf150c35d33a8bbfec748b
0
ox-it/moxie-js-client,ox-it/moxie-js-client,ox-it/moxie-js-client,ox-it/moxie-js-client
define(["app", "backbone", "places/models/POIModel", "places/views/CategoriesView", "places/views/SearchView", "places/views/DetailView", "places/collections/POICollection", "backbone.subroute"], function(app, Backbone, POI, CategoriesView, SearchView, DetailView, POIs){ var pois = new POIs(); var PlacesRouter = Backbone.SubRoute.extend({ // All of your Backbone Routes (add more) routes: { "": "categories", "categories": "categories", "categories/*category_name": "categories", "search": "search", ":id": "detail" }, categories: function(category_name) { // Navigate to the list of categories (root view of places) categoriesView = new CategoriesView({category_name: category_name}); app.showView(categoriesView); }, search: function(params) { var layout = app.getLayout('MapBrowseLayout'); searchView = new SearchView({ collection: pois, params: params }); layout.setView('.content-browse', searchView); layout.getView('.content-map').setCollection(pois); searchView.render(); }, showDetail: function(poi) { var layout = app.getLayout('MapBrowseLayout'); var detailView = new DetailView({ model: poi }); layout.setView('.content-browse', detailView); layout.getView('.content-map').setCollection(new POIs([poi])); detailView.render(); }, detail: function(id) { var poi = pois.get(id); if (poi) { this.showDetail(poi); } else { poi = new POI({id: id}); poi.fetch({success: _.bind(function(model, response, options) { pois.add(model); this.showDetail(model); }, this) }); } } }); // Returns the Router class return PlacesRouter; });
app/places/router.js
define(["app", "backbone", "places/models/POIModel", "places/views/CategoriesView", "places/views/SearchView", "places/views/MapView", "places/views/DetailView", "places/collections/POICollection", "hbs!places/templates/list-map-layout", "backbone.subroute"], function(app, Backbone, POI, CategoriesView, SearchView, MapView, DetailView, POIs, ListMapTemplate){ var pois = new POIs(); var PlacesRouter = Backbone.SubRoute.extend({ // All of your Backbone Routes (add more) routes: { "": "categories", "categories": "categories", "categories/*category_name": "categories", "search": "search", ":id": "detail" }, categories: function(category_name) { // Navigate to the list of categories (root view of places) categoriesView = new CategoriesView({category_name: category_name}); app.showView(categoriesView); }, search: function(params) { mapView = new MapView({ collection: pois }); searchView = new SearchView({ collection: pois, params: params }); var layout = new Backbone.Layout({ template: ListMapTemplate, views: { ".content-detail": mapView, "#list": searchView }, afterRender: function() { that = this; pois.on("change:selected", function(poi) { that.setView("#list", new DetailView({model: poi})).render(); }); } }); app.showView(layout, {back: true}); mapView.invalidateMapSize(); }, detail: function(id, params) { detailView = new DetailView({ model: POI, params: params, poid: id }); app.showView(detailView); detailView.invalidateMapSize(); } }); // Returns the Router class return PlacesRouter; });
Controllers for Places search and detail views Fetch objects from server and applying the correct layouts
app/places/router.js
Controllers for Places search and detail views
<ide><path>pp/places/router.js <del>define(["app", "backbone", "places/models/POIModel", "places/views/CategoriesView", "places/views/SearchView", "places/views/MapView", "places/views/DetailView", "places/collections/POICollection", "hbs!places/templates/list-map-layout", "backbone.subroute"], function(app, Backbone, POI, CategoriesView, SearchView, MapView, DetailView, POIs, ListMapTemplate){ <add>define(["app", "backbone", "places/models/POIModel", "places/views/CategoriesView", "places/views/SearchView", "places/views/DetailView", "places/collections/POICollection", "backbone.subroute"], function(app, Backbone, POI, CategoriesView, SearchView, DetailView, POIs){ <ide> <ide> var pois = new POIs(); <ide> var PlacesRouter = Backbone.SubRoute.extend({ <ide> }, <ide> <ide> search: function(params) { <del> mapView = new MapView({ <del> collection: pois <del> }); <add> var layout = app.getLayout('MapBrowseLayout'); <ide> searchView = new SearchView({ <ide> collection: pois, <ide> params: params <ide> }); <del> var layout = new Backbone.Layout({ <del> template: ListMapTemplate, <del> views: { <del> ".content-detail": mapView, <del> "#list": searchView <del> }, <del> afterRender: function() { <del> that = this; <del> pois.on("change:selected", function(poi) { <del> that.setView("#list", new DetailView({model: poi})).render(); <del> }); <del> } <del> }); <del> app.showView(layout, {back: true}); <del> mapView.invalidateMapSize(); <add> layout.setView('.content-browse', searchView); <add> layout.getView('.content-map').setCollection(pois); <add> searchView.render(); <ide> }, <ide> <del> detail: function(id, params) { <del> detailView = new DetailView({ <del> model: POI, <del> params: params, <del> poid: id <add> showDetail: function(poi) { <add> var layout = app.getLayout('MapBrowseLayout'); <add> var detailView = new DetailView({ <add> model: poi <ide> }); <del> app.showView(detailView); <del> detailView.invalidateMapSize(); <add> layout.setView('.content-browse', detailView); <add> layout.getView('.content-map').setCollection(new POIs([poi])); <add> detailView.render(); <add> }, <add> <add> detail: function(id) { <add> var poi = pois.get(id); <add> if (poi) { <add> this.showDetail(poi); <add> } else { <add> poi = new POI({id: id}); <add> poi.fetch({success: _.bind(function(model, response, options) { <add> pois.add(model); <add> this.showDetail(model); <add> }, this) }); <add> } <ide> } <ide> <ide> });
JavaScript
lgpl-2.1
22326a3782256eefeb250af59ea02dfb64a28bbe
0
brunobuzzi/orbeon-forms,evlist/orbeon-forms,tanbo800/orbeon-forms,ajw625/orbeon-forms,joansmith/orbeon-forms,brunobuzzi/orbeon-forms,evlist/orbeon-forms,wesley1001/orbeon-forms,orbeon/orbeon-forms,martinluther/orbeon-forms,ajw625/orbeon-forms,ajw625/orbeon-forms,orbeon/orbeon-forms,tanbo800/orbeon-forms,evlist/orbeon-forms,wesley1001/orbeon-forms,joansmith/orbeon-forms,martinluther/orbeon-forms,joansmith/orbeon-forms,brunobuzzi/orbeon-forms,wesley1001/orbeon-forms,orbeon/orbeon-forms,joansmith/orbeon-forms,martinluther/orbeon-forms,martinluther/orbeon-forms,evlist/orbeon-forms,wesley1001/orbeon-forms,evlist/orbeon-forms,orbeon/orbeon-forms,brunobuzzi/orbeon-forms,tanbo800/orbeon-forms,tanbo800/orbeon-forms,ajw625/orbeon-forms
/** * Copyright (C) 2009 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 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 Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ /* * JavaScript implementation for the datatable component (new generation) * */ /** * Implementation of datatable constructor. Creates column resizers. * * @method ORBEON.widgets.datatable * @param element * {DOM Element} The DOM element that contains the table. * @param index * {integer} Index (position) of the table in the document. Currently * not used, but might be useful to generate IDs. */ ORBEON.widgets.datatable = function (element, index, innerTableWidth) { YAHOO.log("Creating datatable index " + index, "info") // Store useful stuff as properties this.table = element; this.header = this.table; this.headerRow = this.header.getElementsByTagName('thead')[0].getElementsByTagName('tr')[0]; this.headerColumns = this.headerRow.getElementsByTagName('th'); this.bodyRows = this.table.getElementsByTagName('tbody')[0].getElementsByTagName('tr'); this.bodyColumns = this.bodyRows[2].getElementsByTagName('td'); var plainId = this.table.getAttribute('id'); this.id = plainId.substring(0, plainId.length - '-table'.length); var width = ORBEON.widgets.datatable.utils.getStyle(this.table, 'width', 'auto'); var pxWidth = this.table.clientWidth; if (width.indexOf('%') != - 1) { // Convert % into px... width = pxWidth + 'px'; } this.height = ORBEON.widgets.datatable.utils.getStyle(this.table, 'height', 'auto'); this.scrollV = YAHOO.util.Dom.hasClass(this.table, 'fr-scrollV'); this.scrollH = YAHOO.util.Dom.hasClass(this.table, 'fr-scrollH'); this.scroll = this.scrollV || this.scrollH; this.headBodySplit = this.scroll; this.hasFixedWidthContainer = width != 'auto'; this.hasFixedWidthTable = this.hasFixedWidthContainer && ! this.scrollH; // Create a global container this.container = document.createElement('div'); YAHOO.util.Dom.addClass(this.container, 'yui-dt'); YAHOO.util.Dom.addClass(this.container, 'yui-dt-scrollable'); // Create a container for the header (or the whole table if there is no // scrolling) this.headerContainer = document.createElement('div'); YAHOO.util.Dom.addClass(this.headerContainer, 'yui-dt-hd'); // Assemble all that stuff this.table.parentNode.replaceChild(this.container, this.table); this.container.appendChild(this.headerContainer); this.headerContainer.appendChild(this.header); // See how big the table would be without its size restriction if (this.scrollH) { YAHOO.util.Dom.setStyle(this.table, 'width', 'auto'); } if (this.scrollV) { YAHOO.util.Dom.setStyle(this.table, 'height', 'auto'); } this.tableWidth = this.table.clientWidth; if (this.tableWidth < pxWidth) { this.tableWidth = pxWidth; } this.tableHeight = this.table.clientHeight; if (this.scrollH) { if (pxWidth > this.tableWidth) { // Can be the case if table width was expressed as % this.tableWidth = pxWidth; } if (innerTableWidth != null) { YAHOO.util.Dom.setStyle(this.table, 'width', innerTableWidth); this.tableWidth = this.table.clientWidth; } else { this.tableWidth = this.optimizeWidth(this.tableWidth, this.getTableHeightForWidth(this.tableWidth), 2500, this.getTableHeightForWidth(2500)) + 50; } } else if (this.scrollV) { if (this.hasFixedWidthTable) { width = this.tableWidth + 'px'; this.tableWidth = this.tableWidth - 19; } else { width = (this.tableWidth + 19) + 'px'; } } else { width = this.tableWidth + 'px'; } YAHOO.util.Dom.setStyle(this.table, 'width', this.tableWidth + 'px'); if (this.scrollH && ! this.scrollV && this.height == 'auto' && YAHOO.env.ua.ie > 0 && YAHOO.env.ua.ie < 8) { this.height = (this.tableHeight + 22) + 'px'; } this.thead = YAHOO.util.Selector.query('thead', this.table, true); this.tbody = YAHOO.util.Selector.query('tbody', this.table, true); // Resize the container YAHOO.util.Dom.setStyle(this.container, 'width', width); if (this.height != 'auto') { YAHOO.util.Dom.setStyle(this.container, 'height', this.height); } // Resize the header container YAHOO.util.Dom.setStyle(this.headerContainer, 'width', width); if (this.height != 'auto' && this.headBodySplit) { YAHOO.util.Dom.setStyle(this.headerContainer, 'height', this.thead.rows[0].clientHeight + 'px'); } else if (! this.headBodySplit && this.height == 'auto') { YAHOO.util.Dom.setStyle(this.headerContainer, 'border', '1px solid #7F7F7F') } // Store the column widths before any split var columnWidths = []; for (var j = 0; j < this.headerColumns.length; j++) { columnWidths[j] = this.headerColumns[j].clientWidth; } // Split when needed this.headerScrollWidth = this.tableWidth; if (this.headBodySplit) { // Create a container for the body this.bodyContainer = document.createElement('div'); YAHOO.util.Dom.setStyle(this.bodyContainer, 'width', width); YAHOO.util.Dom.addClass(this.bodyContainer, 'yui-dt-bd'); // Duplicate the table to populate the body this.table = this.header.cloneNode(true); ORBEON.widgets.datatable.removeIdAttributes(this.table); // Move the tbody elements to keep event handler bindings in the visible // tbody var tBody = YAHOO.util.Selector.query('tbody', this.header, true); this.header.removeChild(tBody); this.table.replaceChild(tBody, YAHOO.util.Selector.query('tbody', this.table, true)); // Add an intermediary div to the header to compensate the scroll bar width when needed this.headerScrollContainer = document.createElement('div'); this.headerContainer.appendChild(this.headerScrollContainer); this.headerContainer.removeChild(this.header); this.headerScrollContainer.appendChild(this.header); this.headerScrollWidth = this.tableWidth + 20; this.headerScrollContainer.style.width = this.headerScrollWidth + 'px'; // Do more resizing if (this.height != 'auto') { YAHOO.util.Dom.setStyle(this.bodyContainer, 'height', (this.container.clientHeight - this.thead.rows[0].clientHeight - 5) + 'px'); } // And more assembly this.container.appendChild(this.bodyContainer); this.bodyContainer.appendChild(this.table); } this.width = this.container.clientWidth; if (this.scrollH) { YAHOO.util.Event.addListener(this.bodyContainer, 'scroll', ORBEON.widgets.datatable.scrollHandler, this, true); } this.colResizers =[]; this.colSorters =[]; for (var j = 0; j < this.headerColumns.length; j++) { var headerColumn = this.headerColumns[j]; if (! YAHOO.util.Dom.hasClass(headerColumn, 'fr-datatable-scrollbar-space')) { var childDiv = YAHOO.util.Selector.query('div', headerColumn, true); var colResizer = null; if (YAHOO.util.Dom.hasClass(this.headerColumns[j], 'yui-dt-resizeable')) { colResizer = new ORBEON.widgets.datatable.colResizer(j, this.headerColumns[j], this) this.colResizers[j] = colResizer; } var width = (columnWidths[j] - 20) + 'px'; var rule; // See _setColumnWidth in YUI datatable.js... if (YAHOO.env.ua.ie == 0) { // This is a hack! We need to remove the prefix to match classes added in XSLT! var className = '.dt-' + this.id.substring(this.id.lastIndexOf('$') + 1) + '-col-' + (j + 1); if (! this.styleElt) { this.styleElt = document.createElement('style'); this.styleElt.type = 'text/css'; document.getElementsByTagName('head').item(0).appendChild(this.styleElt); } if (this.styleElt) { if (this.styleElt.styleSheet && this.styleElt.styleSheet.addRule) { this.styleElt.styleSheet.addRule(classname, 'width:' + width); rule = this.styleElt.styleSheet.rules[ this.styleElt.styleSheet.rules.length - 1]; } else if (this.styleElt.sheet && this.styleElt.sheet.insertRule) { this.styleElt.sheet.insertRule(className + ' {width:' + width + ';}', this.styleElt.sheet.cssRules.length); rule = this.styleElt.sheet.cssRules[ this.styleElt.sheet.cssRules.length - 1]; } } if (rule && YAHOO.util.Dom.hasClass(this.headerColumns[j], 'yui-dt-resizeable')) { colResizer.setRule(rule); } } if (! rule) { var style = childDiv.style; style.width = width; var styles =[style]; for (var k = 0; k < this.bodyRows.length; k++) { row = this.bodyRows[k]; if (row.cells.length > j && ! YAHOO.util.Dom.hasClass(row, 'xforms-repeat-template')) { var div = YAHOO.util.Selector.query('div', row.cells[j], true); if (div != undefined) { style = div.style; style.width = width; styles[styles.length] = style; } } } if (YAHOO.util.Dom.hasClass(this.headerColumns[j], 'yui-dt-resizeable')) { colResizer.setStyleArray(styles); } } if (YAHOO.util.Dom.hasClass(this.headerColumns[j], 'yui-dt-sortable')) { this.colSorters[ this.colSorters.length] = new ORBEON.widgets.datatable.colSorter(this.headerColumns[j]); } } } // Now that the table has been properly sized, reconsider its // "resizeability" if (this.hasFixedWidthContainer && this.hasFixedWidthTable) { // These are fixed width tables without horizontal scroll bars // and as we don't know how to resize their columns properly, // we'd better consider that as variable width this.hasFixedWidthContainer = false; this.hasFixedWidthTable = false; } } ORBEON.widgets.datatable.prototype.getTableHeightForWidth = function (width) { this.table.style.width = width + 'px'; return this.table.clientHeight; } ORBEON.widgets.datatable.prototype.optimizeWidth = function (w1, h1, w2, h2) { if (h1 == h2 || (w2 - w1 < 50)) { return w1; } var w = Math.round((w1 + w2) / 2); var h = this.getTableHeightForWidth(w); if (h == h2) { return this.optimizeWidth(w1, h1, w, h); } else { return this.optimizeWidth(w, h, w2, h2); } } ORBEON.widgets.datatable.prototype.adjustWidth = function (deltaX, index) { if (! this.hasFixedWidthContainer) { this.width += deltaX; YAHOO.util.Dom.setStyle(this.container, 'width', this.width + 'px'); YAHOO.util.Dom.setStyle(this.headerContainer, 'width', this.width + 'px'); if (this.headBodySplit) { YAHOO.util.Dom.setStyle(this.bodyContainer, 'width', this.width + 'px'); } } if (! this.hasFixedWidthTable) { this.tableWidth += deltaX; this.headerScrollWidth += deltaX; if (this.headBodySplit) { YAHOO.util.Dom.setStyle(this.headerScrollContainer, 'width', this.headerScrollWidth + 'px'); YAHOO.util.Dom.setStyle(this.header, 'width', this.tableWidth + 'px'); YAHOO.util.Dom.setStyle(this.table, 'width', this.tableWidth + 'px'); } } } ORBEON.widgets.datatable.prototype.rewriteColumnsWidths = function () { for (var icol = 0; icol < this.headerColumns.length; icol++) { var headerColumn = this.headerColumns[icol]; var divs = YAHOO.util.Dom.getElementsByClassName('yui-dt-liner', 'div', headerColumn); if (divs.length > 0) { var div = divs[0]; if (div != undefined && div.style.width != "") { var width = div.style.width; var styles =[div.style]; for (var irow = 0; irow < this.bodyRows.length; irow++) { var row = this.bodyRows[irow]; if (row.cells.length > icol) { var cell = row.cells[icol]; var cellDivs = YAHOO.util.Dom.getElementsByClassName('yui-dt-liner', 'div', cell); if (cellDivs.length > 0) { var cellDiv = cellDivs[0]; if (cellDiv != undefined) { cellDiv.style.width = width; styles[styles.length] = cellDiv.style; } } } } var colResizer = this.colResizers[icol]; if (colResizer != undefined) { colResizer.setStyleArray(styles); } } } } } ORBEON.widgets.datatable.scrollHandler = function (e) { //alert('scrolling'); this.headerContainer.scrollLeft = this.bodyContainer.scrollLeft; } ORBEON.widgets.datatable.utils =[]; ORBEON.widgets.datatable.utils.getStyle = function (elt, property, defolt) { if (elt.style[property] == '') { return defolt; } return elt.style[property]; } ORBEON.widgets.datatable.utils.freezeWidth = function (elt) { YAHOO.util.Dom.setStyle(elt, 'width', elt.clientWidth + 'px'); } ORBEON.widgets.datatable.colSorter = function (th) { var liner = YAHOO.util.Selector.query('div.yui-dt-liner', th, true); YAHOO.util.Event.addListener(liner, "click", function (ev) { var a = YAHOO.util.Selector.query('a.xforms-trigger:not(.xforms-disabled)', liner, true); if (YAHOO.util.Event.getTarget(ev) != a) { ORBEON.xforms.Document.dispatchEvent(a.id, "DOMActivate"); } }); } /** * Implementation of datatable.colResizer constructor. Creates the YAHOO.util.DD object. * * @method ORBEON.widgets.datatable.colResizer * @param col {DOM Element} The th DOM element. */ ORBEON.widgets.datatable.colResizer = function (index, th, datatable) { this.index = index; this.th = th; this.datatable = datatable; this.rule = null; this.styles = null; this.resizerliner = document.createElement('div'); YAHOO.util.Dom.addClass(this.resizerliner, 'yui-dt-resizerliner'); this.liner = YAHOO.util.Selector.query('div', this.th, true); this.th.replaceChild(this.resizerliner, this.liner); this.resizerliner.appendChild(this.liner); this.resizer = document.createElement('div'); YAHOO.util.Dom.addClass(this.resizer, 'yui-dt-resizer'); this.resizer.style.left = 'auto'; this.resizer.style.right = '0pt'; this.resizer.style.top = 'auto'; this.resizer.style.bottom = '0pt'; this.resizer.style.height = '25px'; this.resizerliner.appendChild(this.resizer); this.init(this.resizer, this.resizer, { dragOnly: true, dragElId: this.resizer.id }); this.setYConstraint(0, 0); this.initFrame(); this.delta = 7; } YAHOO.extend(ORBEON.widgets.datatable.colResizer, YAHOO.util.DDProxy, { ///////////////////////////////////////////////////////////////////////////// // // Public methods // // /////////////////////////////////////////////////////////////////////////// setStyleArray: function (styles) { this.styles = styles; }, setRule: function (rule) { this.rule = rule; }, ///////////////////////////////////////////////////////////////////////////// // // Public DOM event handlers // // /////////////////////////////////////////////////////////////////////////// /** * Handles mousedown events on the Column resizer. * * @method onMouseDown * @param e * {string} The mousedown event */ onMouseDown: function (ev) { this.resetConstraints(); this.width = this.liner.clientWidth; // this.resizerX = YAHOO.util.Dom.getX(this.resizer); this.resizerX = YAHOO.util.Event.getXY(ev)[0]; }, /** * Handles mouseup events on the Column resizer. * Reset style left property so that the resizer finds its place * if it had lost it! * * @method onMouseUp * @param e * {string} The mousedown event */ onMouseUp: function (ev) { this.resizer.style.left = "auto"; }, /** * Handles drag events on the Column resizer. * * @method onDrag * @param e {string} The drag event */ onDrag: function (ev) { var newX = YAHOO.util.Event.getXY(ev)[0]; this.datatable.table.style.display = 'none'; var deltaX = newX - this.resizerX; this.resizerX = newX; var width = this.width + deltaX; var widthStyle = (width - 20) + 'px'; // TODO : determine 20 from // padding // If different and non null, try to set it if (width > 20 && width != this.width) { this.datatable.adjustWidth(deltaX, this.index); if (this.rule) { this.rule.style.width = widthStyle; } else { for (var i = 0; i < this.styles.length; i++) { this.styles[i].width = widthStyle; } } this.width = width; } this.datatable.table.style.display = ''; } }); ORBEON.widgets.datatable.removeIdAttributes = function (element, skipSelf) { if (! skipSelf) { element.removeAttribute('id'); } for (var i = 0; i < element.childNodes.length; i++) { var node = element.childNodes[i]; if (node.nodeType == 1) { ORBEON.widgets.datatable.removeIdAttributes(node); } } } ORBEON.widgets.datatable.init = function (target, innerTableWidth) { // Initializes a datatable (called by xforms-enabled events) var container = target.parentNode.parentNode; var id = container.id; if (! YAHOO.util.Dom.hasClass(target, 'xforms-disabled')) { if (ORBEON.widgets.datatable.datatables[id] == undefined) { var table = YAHOO.util.Selector.query('table', target.parentNode, false)[0]; ORBEON.widgets.datatable.datatables[id] = new ORBEON.widgets.datatable(table, id, innerTableWidth); } else { ORBEON.widgets.datatable.datatables[id].rewriteColumnsWidths(); } } } // Comment/uncomment in normal/debug mode... //var myLogReader = new YAHOO.widget.LogReader(); ORBEON.widgets.datatable.datatables = { };
src/resources-packaged/xbl/orbeon/datatable/datatable.js
/** * Copyright (C) 2009 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 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 Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ /* * JavaScript implementation for the datatable component (new generation) * */ /** * Implementation of datatable constructor. Creates column resizers. * * @method ORBEON.widgets.datatable * @param element * {DOM Element} The DOM element that contains the table. * @param index * {integer} Index (position) of the table in the document. Currently * not used, but might be useful to generate IDs. */ ORBEON.widgets.datatable = function (element, index, innerTableWidth) { YAHOO.log("Creating datatable index " + index, "info") // Store useful stuff as properties this.table = element; this.header = this.table; this.headerRow = this.header.getElementsByTagName('thead')[0].getElementsByTagName('tr')[0]; this.headerColumns = this.headerRow.getElementsByTagName('th'); this.bodyRows = this.table.getElementsByTagName('tbody')[0].getElementsByTagName('tr'); this.bodyColumns = this.bodyRows[2].getElementsByTagName('td'); var plainId = this.table.getAttribute('id'); this.id = plainId.substring(0, plainId.length - '-table'.length); var width = ORBEON.widgets.datatable.utils.getStyle(this.table, 'width', 'auto'); var pxWidth = this.table.clientWidth; if (width.indexOf('%') != - 1) { // Convert % into px... width = pxWidth + 'px'; } this.height = ORBEON.widgets.datatable.utils.getStyle(this.table, 'height', 'auto'); this.scrollV = YAHOO.util.Dom.hasClass(this.table, 'fr-scrollV'); this.scrollH = YAHOO.util.Dom.hasClass(this.table, 'fr-scrollH'); this.scroll = this.scrollV || this.scrollH; this.headBodySplit = this.scroll; this.hasFixedWidthContainer = width != 'auto'; this.hasFixedWidthTable = this.hasFixedWidthContainer && ! this.scrollH; // Create a global container this.container = document.createElement('div'); YAHOO.util.Dom.addClass(this.container, 'yui-dt'); YAHOO.util.Dom.addClass(this.container, 'yui-dt-scrollable'); // Create a container for the header (or the whole table if there is no // scrolling) this.headerContainer = document.createElement('div'); YAHOO.util.Dom.addClass(this.headerContainer, 'yui-dt-hd'); // Assemble all that stuff this.table.parentNode.replaceChild(this.container, this.table); this.container.appendChild(this.headerContainer); this.headerContainer.appendChild(this.header); // See how big the table would be without its size restriction if (this.scrollH) { YAHOO.util.Dom.setStyle(this.table, 'width', 'auto'); } if (this.scrollV) { YAHOO.util.Dom.setStyle(this.table, 'height', 'auto'); } this.tableWidth = this.table.clientWidth; if (this.tableWidth < pxWidth) { this.tableWidth = pxWidth; } this.tableHeight = this.table.clientHeight; if (this.scrollH) { if (pxWidth > this.tableWidth) { // Can be the case if table width was expressed as % this.tableWidth = pxWidth; } if (innerTableWidth != null) { YAHOO.util.Dom.setStyle(this.table, 'width', innerTableWidth); this.tableWidth = this.table.clientWidth; } else { this.tableWidth = this.optimizeWidth(this.tableWidth, this.getTableHeightForWidth(this.tableWidth), 2500, this.getTableHeightForWidth(2500)) + 50; } } else if (this.scrollV) { if (this.hasFixedWidthTable) { width = this.tableWidth + 'px'; this.tableWidth = this.tableWidth - 19; } else { width = (this.tableWidth + 19) + 'px'; } } else { width = this.tableWidth + 'px'; } YAHOO.util.Dom.setStyle(this.table, 'width', this.tableWidth + 'px'); if (this.scrollH && ! this.scrollV && this.height == 'auto' && YAHOO.env.ua.ie > 0 && YAHOO.env.ua.ie < 8) { this.height = (this.tableHeight + 22) + 'px'; } this.thead = YAHOO.util.Selector.query('thead', this.table, true); this.tbody = YAHOO.util.Selector.query('tbody', this.table, true); // Resize the container YAHOO.util.Dom.setStyle(this.container, 'width', width); if (this.height != 'auto') { YAHOO.util.Dom.setStyle(this.container, 'height', this.height); } // Resize the header container YAHOO.util.Dom.setStyle(this.headerContainer, 'width', width); if (this.height != 'auto' && this.headBodySplit) { YAHOO.util.Dom.setStyle(this.headerContainer, 'height', this.thead.rows[0].clientHeight + 'px'); } else if (! this.headBodySplit && this.height == 'auto') { YAHOO.util.Dom.setStyle(this.headerContainer, 'border', '1px solid #7F7F7F') } // Store the column widths before any split var columnWidths = []; for (var j = 0; j < this.headerColumns.length; j++) { columnWidths[j] = this.headerColumns[j].clientWidth; } // Split when needed this.headerScrollWidth = this.tableWidth; if (this.headBodySplit) { // Create a container for the body this.bodyContainer = document.createElement('div'); YAHOO.util.Dom.setStyle(this.bodyContainer, 'width', width); YAHOO.util.Dom.addClass(this.bodyContainer, 'yui-dt-bd'); // Duplicate the table to populate the body this.table = this.header.cloneNode(true); ORBEON.widgets.datatable.removeIdAttributes(this.table); // Move the tbody elements to keep event handler bindings in the visible // tbody var tBody = YAHOO.util.Selector.query('tbody', this.header, true); this.header.removeChild(tBody); this.table.replaceChild(tBody, YAHOO.util.Selector.query('tbody', this.table, true)); // Add an intermediary div to the header to compensate the scroll bar width when needed this.headerScrollContainer = document.createElement('div'); this.headerContainer.appendChild(this.headerScrollContainer); this.headerContainer.removeChild(this.header); this.headerScrollContainer.appendChild(this.header); this.headerScrollWidth = this.tableWidth + 20; this.headerScrollContainer.style.width = this.headerScrollWidth + 'px'; // Do more resizing if (this.height != 'auto') { YAHOO.util.Dom.setStyle(this.bodyContainer, 'height', (this.container.clientHeight - this.thead.rows[0].clientHeight - 5) + 'px'); } // And more assembly this.container.appendChild(this.bodyContainer); this.bodyContainer.appendChild(this.table); } this.width = this.container.clientWidth; if (this.scrollH) { YAHOO.util.Event.addListener(this.bodyContainer, 'scroll', ORBEON.widgets.datatable.scrollHandler, this, true); } this.colResizers =[]; this.colSorters =[]; for (var j = 0; j < this.headerColumns.length; j++) { var headerColumn = this.headerColumns[j]; if (! YAHOO.util.Dom.hasClass(headerColumn, 'fr-datatable-scrollbar-space')) { var childDiv = YAHOO.util.Selector.query('div', headerColumn, true); var colResizer = null; if (YAHOO.util.Dom.hasClass(this.headerColumns[j], 'yui-dt-resizeable')) { colResizer = new ORBEON.widgets.datatable.colResizer(j, this.headerColumns[j], this) this.colResizers[ this.colResizers.length] = colResizer; } var width = (columnWidths[j] - 20) + 'px'; var rule; // See _setColumnWidth in YUI datatable.js... if (YAHOO.env.ua.ie == 0) { // This is a hack! We need to remove the prefix to match classes added in XSLT! var className = '.dt-' + this.id.substring(this.id.lastIndexOf('$') + 1) + '-col-' + (j + 1); if (! this.styleElt) { this.styleElt = document.createElement('style'); this.styleElt.type = 'text/css'; document.getElementsByTagName('head').item(0).appendChild(this.styleElt); } if (this.styleElt) { if (this.styleElt.styleSheet && this.styleElt.styleSheet.addRule) { this.styleElt.styleSheet.addRule(classname, 'width:' + width); rule = this.styleElt.styleSheet.rules[ this.styleElt.styleSheet.rules.length - 1]; } else if (this.styleElt.sheet && this.styleElt.sheet.insertRule) { this.styleElt.sheet.insertRule(className + ' {width:' + width + ';}', this.styleElt.sheet.cssRules.length); rule = this.styleElt.sheet.cssRules[ this.styleElt.sheet.cssRules.length - 1]; } } if (rule && YAHOO.util.Dom.hasClass(this.headerColumns[j], 'yui-dt-resizeable')) { colResizer.setRule(rule); } } if (! rule) { var style = childDiv.style; style.width = width; var styles =[style]; for (var k = 0; k < this.bodyRows.length; k++) { row = this.bodyRows[k]; if (row.cells.length > j && ! YAHOO.util.Dom.hasClass(row, 'xforms-repeat-template')) { var div = YAHOO.util.Selector.query('div', row.cells[j], true); if (div != undefined) { style = div.style; style.width = width; styles[styles.length] = style; } } } if (YAHOO.util.Dom.hasClass(this.headerColumns[j], 'yui-dt-resizeable')) { colResizer.setStyleArray(styles); } } if (YAHOO.util.Dom.hasClass(this.headerColumns[j], 'yui-dt-sortable')) { this.colSorters[ this.colSorters.length] = new ORBEON.widgets.datatable.colSorter(this.headerColumns[j]); } } } // Now that the table has been properly sized, reconsider its // "resizeability" if (this.hasFixedWidthContainer && this.hasFixedWidthTable) { // These are fixed width tables without horizontal scroll bars // and as we don't know how to resize their columns properly, // we'd better consider that as variable width this.hasFixedWidthContainer = false; this.hasFixedWidthTable = false; } } ORBEON.widgets.datatable.prototype.getTableHeightForWidth = function (width) { this.table.style.width = width + 'px'; return this.table.clientHeight; } ORBEON.widgets.datatable.prototype.optimizeWidth = function (w1, h1, w2, h2) { if (h1 == h2 || (w2 - w1 < 50)) { return w1; } var w = Math.round((w1 + w2) / 2); var h = this.getTableHeightForWidth(w); if (h == h2) { return this.optimizeWidth(w1, h1, w, h); } else { return this.optimizeWidth(w, h, w2, h2); } } ORBEON.widgets.datatable.prototype.adjustWidth = function (deltaX, index) { if (! this.hasFixedWidthContainer) { this.width += deltaX; YAHOO.util.Dom.setStyle(this.container, 'width', this.width + 'px'); YAHOO.util.Dom.setStyle(this.headerContainer, 'width', this.width + 'px'); if (this.headBodySplit) { YAHOO.util.Dom.setStyle(this.bodyContainer, 'width', this.width + 'px'); } } if (! this.hasFixedWidthTable) { this.tableWidth += deltaX; this.headerScrollWidth += deltaX; if (this.headBodySplit) { YAHOO.util.Dom.setStyle(this.headerScrollContainer, 'width', this.headerScrollWidth + 'px'); YAHOO.util.Dom.setStyle(this.header, 'width', this.tableWidth + 'px'); YAHOO.util.Dom.setStyle(this.table, 'width', this.tableWidth + 'px'); } } } ORBEON.widgets.datatable.prototype.rewriteColumnsWidths = function () { for (var icol = 0; icol < this.headerColumns.length; icol++) { var headerColumn = this.headerColumns[icol]; var divs = YAHOO.util.Dom.getElementsByClassName('yui-dt-liner', 'div', headerColumn); if (divs.length > 0) { var div = divs[0]; if (div != undefined && div.style.width != "") { var width = div.style.width; for (var irow = 0; irow < this.bodyRows.length; irow++) { var row = this.bodyRows[irow]; if (row.cells.length > icol) { var cell = row.cells[icol]; var cellDivs = YAHOO.util.Dom.getElementsByClassName('yui-dt-liner', 'div', cell); if (cellDivs.length > 0) { var cellDiv = cellDivs[0]; if (cellDiv != undefined) { cellDiv.style.width = width; } } } } } } } } ORBEON.widgets.datatable.scrollHandler = function (e) { //alert('scrolling'); this.headerContainer.scrollLeft = this.bodyContainer.scrollLeft; } ORBEON.widgets.datatable.utils =[]; ORBEON.widgets.datatable.utils.getStyle = function (elt, property, defolt) { if (elt.style[property] == '') { return defolt; } return elt.style[property]; } ORBEON.widgets.datatable.utils.freezeWidth = function (elt) { YAHOO.util.Dom.setStyle(elt, 'width', elt.clientWidth + 'px'); } ORBEON.widgets.datatable.colSorter = function (th) { var liner = YAHOO.util.Selector.query('div.yui-dt-liner', th, true); YAHOO.util.Event.addListener(liner, "click", function (ev) { var a = YAHOO.util.Selector.query('a.xforms-trigger:not(.xforms-disabled)', liner, true); if (YAHOO.util.Event.getTarget(ev) != a) { ORBEON.xforms.Document.dispatchEvent(a.id, "DOMActivate"); } }); } /** * Implementation of datatable.colResizer constructor. Creates the YAHOO.util.DD object. * * @method ORBEON.widgets.datatable.colResizer * @param col {DOM Element} The th DOM element. */ ORBEON.widgets.datatable.colResizer = function (index, th, datatable) { this.index = index; this.th = th; this.datatable = datatable; this.rule = null; this.styles = null; this.resizerliner = document.createElement('div'); YAHOO.util.Dom.addClass(this.resizerliner, 'yui-dt-resizerliner'); this.liner = YAHOO.util.Selector.query('div', this.th, true); this.th.replaceChild(this.resizerliner, this.liner); this.resizerliner.appendChild(this.liner); this.resizer = document.createElement('div'); YAHOO.util.Dom.addClass(this.resizer, 'yui-dt-resizer'); this.resizer.style.left = 'auto'; this.resizer.style.right = '0pt'; this.resizer.style.top = 'auto'; this.resizer.style.bottom = '0pt'; this.resizer.style.height = '25px'; this.resizerliner.appendChild(this.resizer); this.init(this.resizer, this.resizer, { dragOnly: true, dragElId: this.resizer.id }); this.setYConstraint(0, 0); this.initFrame(); this.delta = 7; } YAHOO.extend(ORBEON.widgets.datatable.colResizer, YAHOO.util.DDProxy, { ///////////////////////////////////////////////////////////////////////////// // // Public methods // // /////////////////////////////////////////////////////////////////////////// setStyleArray: function (styles) { this.styles = styles; }, setRule: function (rule) { this.rule = rule; }, ///////////////////////////////////////////////////////////////////////////// // // Public DOM event handlers // // /////////////////////////////////////////////////////////////////////////// /** * Handles mousedown events on the Column resizer. * * @method onMouseDown * @param e * {string} The mousedown event */ onMouseDown: function (ev) { this.resetConstraints(); this.width = this.liner.clientWidth; // this.resizerX = YAHOO.util.Dom.getX(this.resizer); this.resizerX = YAHOO.util.Event.getXY(ev)[0]; }, /** * Handles mouseup events on the Column resizer. * Reset style left property so that the resizer finds its place * if it had lost it! * * @method onMouseUp * @param e * {string} The mousedown event */ onMouseUp: function (ev) { this.resizer.style.left = "auto"; }, /** * Handles drag events on the Column resizer. * * @method onDrag * @param e {string} The drag event */ onDrag: function (ev) { var newX = YAHOO.util.Event.getXY(ev)[0]; this.datatable.table.style.display = 'none'; var deltaX = newX - this.resizerX; this.resizerX = newX; var width = this.width + deltaX; var widthStyle = (width - 20) + 'px'; // TODO : determine 20 from // padding // If different and non null, try to set it if (width > 20 && width != this.width) { this.datatable.adjustWidth(deltaX, this.index); if (this.rule) { this.rule.style.width = widthStyle; } else { for (var i = 0; i < this.styles.length; i++) { this.styles[i].width = widthStyle; } } this.width = width; } this.datatable.table.style.display = ''; } }); ORBEON.widgets.datatable.removeIdAttributes = function (element, skipSelf) { if (! skipSelf) { element.removeAttribute('id'); } for (var i = 0; i < element.childNodes.length; i++) { var node = element.childNodes[i]; if (node.nodeType == 1) { ORBEON.widgets.datatable.removeIdAttributes(node); } } } ORBEON.widgets.datatable.init = function (target, innerTableWidth) { // Initializes a datatable (called by xforms-enabled events) var container = target.parentNode.parentNode; var id = container.id; if (! YAHOO.util.Dom.hasClass(target, 'xforms-disabled')) { if (ORBEON.widgets.datatable.datatables[id] == undefined) { var table = YAHOO.util.Selector.query('table', target.parentNode, false)[0]; ORBEON.widgets.datatable.datatables[id] = new ORBEON.widgets.datatable(table, id, innerTableWidth); } else { ORBEON.widgets.datatable.datatables[id].rewriteColumnsWidths(); } } } // Comment/uncomment in normal/debug mode... //var myLogReader = new YAHOO.widget.LogReader(); ORBEON.widgets.datatable.datatables = { };
Datatable component: after a datatable is disabled and enabled, we also need to reinitalize the style arrays for the column resizers.
src/resources-packaged/xbl/orbeon/datatable/datatable.js
Datatable component: after a datatable is disabled and enabled, we also need to reinitalize the style arrays for the column resizers.
<ide><path>rc/resources-packaged/xbl/orbeon/datatable/datatable.js <ide> var colResizer = null; <ide> if (YAHOO.util.Dom.hasClass(this.headerColumns[j], 'yui-dt-resizeable')) { <ide> colResizer = new ORBEON.widgets.datatable.colResizer(j, this.headerColumns[j], this) <del> this.colResizers[ this.colResizers.length] = colResizer; <add> this.colResizers[j] = colResizer; <ide> } <ide> <ide> var width = (columnWidths[j] - 20) + 'px'; <ide> var div = divs[0]; <ide> if (div != undefined && div.style.width != "") { <ide> var width = div.style.width; <add> var styles =[div.style]; <ide> for (var irow = 0; irow < this.bodyRows.length; irow++) { <ide> var row = this.bodyRows[irow]; <ide> if (row.cells.length > icol) { <ide> var cellDiv = cellDivs[0]; <ide> if (cellDiv != undefined) { <ide> cellDiv.style.width = width; <add> styles[styles.length] = cellDiv.style; <ide> } <ide> } <ide> } <add> } <add> var colResizer = this.colResizers[icol]; <add> if (colResizer != undefined) { <add> colResizer.setStyleArray(styles); <ide> } <ide> } <ide> }
Java
mit
error: pathspec '1.JavaSyntax/src/com/javarush/task/task08/task0805/Solution.java' did not match any file(s) known to git
d0d55adbcce47d472529459bd526185267b18b99
1
nphl/JavaRushTasks
package com.javarush.task.task08.task0805; import java.util.HashMap; import java.util.Map; /* На экране — значения! */ public class Solution { public static void main(String[] args) throws Exception { HashMap<String, String> map = new HashMap<String, String>(); map.put("Sim", "Sim"); map.put("Tom", "Tom"); map.put("Arbus", "Arbus"); map.put("Baby", "Baby"); map.put("Cat", "Cat"); map.put("Dog", "Dog"); map.put("Eat", "Eat"); map.put("Food", "Food"); map.put("Gevey", "Gevey"); map.put("Hugs", "Hugs"); printValues(map); } public static void printValues(Map<String, String> map) { for (Map.Entry<String, String> pair : map.entrySet()){ System.out.println(pair.getValue()); } } }
1.JavaSyntax/src/com/javarush/task/task08/task0805/Solution.java
Complete task0805
1.JavaSyntax/src/com/javarush/task/task08/task0805/Solution.java
Complete task0805
<ide><path>.JavaSyntax/src/com/javarush/task/task08/task0805/Solution.java <add>package com.javarush.task.task08.task0805; <add> <add>import java.util.HashMap; <add>import java.util.Map; <add> <add>/* <add>На экране — значения! <add>*/ <add> <add>public class Solution { <add> public static void main(String[] args) throws Exception { <add> HashMap<String, String> map = new HashMap<String, String>(); <add> map.put("Sim", "Sim"); <add> map.put("Tom", "Tom"); <add> map.put("Arbus", "Arbus"); <add> map.put("Baby", "Baby"); <add> map.put("Cat", "Cat"); <add> map.put("Dog", "Dog"); <add> map.put("Eat", "Eat"); <add> map.put("Food", "Food"); <add> map.put("Gevey", "Gevey"); <add> map.put("Hugs", "Hugs"); <add> <add> printValues(map); <add> } <add> <add> public static void printValues(Map<String, String> map) { <add> for (Map.Entry<String, String> pair : map.entrySet()){ <add> System.out.println(pair.getValue()); <add> } <add> } <add>}
JavaScript
bsd-3-clause
f3e452314a7bacaa78ea7caaae0ed6900d2ffcbc
0
uprisecampaigns/uprise-app,uprisecampaigns/uprise-app,uprisecampaigns/uprise-app
import React, { Component, PropTypes } from 'react'; import Drawer from 'material-ui/Drawer'; import MenuItem from 'material-ui/MenuItem'; import Divider from 'material-ui/Divider'; import Subheader from 'material-ui/Subheader'; import IconButton from 'material-ui/IconButton'; import Link from 'components/Link'; import s from './NavDrawer.scss'; function UserMenuItem (props) { const iconButtonStyle = { fontSize: '3rem' } const { itemClicked, user } = props; return ( <div className={s.userContainer}> <div className={s.userIconContainer}> <IconButton iconStyle={iconButtonStyle} iconClassName={[s.materialIcons, 'material-icons'].join(' ')} className={s.userIcon} onTouchTap={itemClicked} >account_box</IconButton> </div> <div className={s.accountInfoContainer}> <div className={s.nameContainer}> {user.first_name} {user.last_name} </div> <div className={s.emailContainer}> {user.email} </div> </div> </div> ); } class NavDrawer extends Component { constructor(props) { super(props); } static propTypes = { open: PropTypes.bool.isRequired, handleToggle: PropTypes.func.isRequired, onRequestChange: PropTypes.func.isRequired, userObject: PropTypes.object, loggedIn: PropTypes.bool.isRequired, logout: PropTypes.func.isRequired } itemClicked = (event) => { this.props.onRequestChange(false); } menuItems = [ { path: '/search', title: 'Search' }, { path: '/actions', title: 'Actions' }, { path: '/organize', title: 'Organize' }, ] accountMenuItems = [ { path: '/account/profile', title: 'Profile' }, { path: '/account/preferences', title: 'Preferences' }, { path: '/account/settings', title: 'Settings' }, ] bottomMenuItems = [ { path: '/account/help', title: 'Help' }, { path: '#', title: 'Logout', action: this.props.logout } ] renderNavItems = (item, index) => { const itemClicked = (event) => { if (typeof item.action === 'function') { item.action(event); } this.itemClicked(event); } return ( <div key={index}> <Link to={item.path} useAhref={false} onClick={itemClicked} > <MenuItem className={s.navMenuItem} primaryText={item.title} /> </Link> </div> ); } render() { const navItems = this.menuItems.map(this.renderNavItems); const accountNavItems = this.accountMenuItems.map(this.renderNavItems); const bottomNavItems = this.bottomMenuItems.map(this.renderNavItems); if (this.props.loggedIn) { return ( <Drawer open={this.props.open} onRequestChange={this.props.onRequestChange} className={s.drawer} docked={false} > <MenuItem primaryText={ <UserMenuItem itemClicked={this.itemClicked} user={this.props.userObject} /> } className={s.userMenuItem} /> {navItems} <Divider className={s.divider}/> <Subheader className={s.subheader}>Account</Subheader> {accountNavItems} <div className={s.bottomNavContainer}> {bottomNavItems} </div> </Drawer> ); } else { return ( <Drawer open={this.props.open} onRequestChange={this.props.onRequestChange} className={s.drawer} docked={false} > <Link to="/login" useAhref={false} onClick={this.itemClicked} > <MenuItem className={s.navMenuItem} primaryText="Login" /> </Link> </Drawer> ); } } } export default NavDrawer;
app/client/src/components/Layout/components/NavDrawerContainer/components/NavDrawer/NavDrawer.js
import React, { Component, PropTypes } from 'react'; import Drawer from 'material-ui/Drawer'; import MenuItem from 'material-ui/MenuItem'; import Divider from 'material-ui/Divider'; import Subheader from 'material-ui/Subheader'; import IconButton from 'material-ui/IconButton'; import Link from 'components/Link'; import s from './NavDrawer.scss'; function UserMenuItem (props) { const iconButtonStyle = { fontSize: '3rem' } const { itemClicked, user } = props; return ( <div className={s.userContainer}> <div className={s.userIconContainer}> <IconButton iconStyle={iconButtonStyle} iconClassName={[s.materialIcons, 'material-icons'].join(' ')} className={s.userIcon} onTouchTap={itemClicked} >account_box</IconButton> </div> <div className={s.accountInfoContainer}> <div className={s.nameContainer}> {user.first_name} {user.last_name} </div> <div className={s.emailContainer}> {user.email} </div> </div> </div> ); } class NavDrawer extends Component { constructor(props) { super(props); } static propTypes = { open: PropTypes.bool.isRequired, handleToggle: PropTypes.func.isRequired, onRequestChange: PropTypes.func.isRequired, userObject: PropTypes.object, loggedIn: PropTypes.bool.isRequired, logout: PropTypes.func.isRequired } itemClicked = (event) => { this.props.onRequestChange(false); } menuItems = [ { path: '/search', title: 'Search' }, { path: '/communications', title: 'Communications' }, { path: '/calendar', title: 'Calendar' }, { path: '/organize', title: 'Organize' }, ] accountMenuItems = [ { path: '/account/profile', title: 'Profile' }, { path: '/account/preferences', title: 'Preferences' }, { path: '/account/settings', title: 'Settings' }, ] bottomMenuItems = [ { path: '/account/help', title: 'Help' }, { path: '#', title: 'Logout', action: this.props.logout } ] renderNavItems = (item, index) => { const itemClicked = (event) => { if (typeof item.action === 'function') { item.action(event); } this.itemClicked(event); } return ( <div key={index}> <Link to={item.path} useAhref={false} onClick={itemClicked} > <MenuItem className={s.navMenuItem} primaryText={item.title} /> </Link> </div> ); } render() { const navItems = this.menuItems.map(this.renderNavItems); const accountNavItems = this.accountMenuItems.map(this.renderNavItems); const bottomNavItems = this.bottomMenuItems.map(this.renderNavItems); if (this.props.loggedIn) { return ( <Drawer open={this.props.open} onRequestChange={this.props.onRequestChange} className={s.drawer} docked={false} > <MenuItem primaryText={ <UserMenuItem itemClicked={this.itemClicked} user={this.props.userObject} /> } className={s.userMenuItem} /> {navItems} <Divider className={s.divider}/> <Subheader className={s.subheader}>Account</Subheader> {accountNavItems} <div className={s.bottomNavContainer}> {bottomNavItems} </div> </Drawer> ); } else { return ( <Drawer open={this.props.open} onRequestChange={this.props.onRequestChange} className={s.drawer} docked={false} > <Link to="/login" useAhref={false} onClick={this.itemClicked} > <MenuItem className={s.navMenuItem} primaryText="Login" /> </Link> </Drawer> ); } } } export default NavDrawer;
Adding 'actions' link to nav drawer.
app/client/src/components/Layout/components/NavDrawerContainer/components/NavDrawer/NavDrawer.js
Adding 'actions' link to nav drawer.
<ide><path>pp/client/src/components/Layout/components/NavDrawerContainer/components/NavDrawer/NavDrawer.js <ide> <ide> menuItems = [ <ide> { path: '/search', title: 'Search' }, <del> { path: '/communications', title: 'Communications' }, <del> { path: '/calendar', title: 'Calendar' }, <add> { path: '/actions', title: 'Actions' }, <ide> { path: '/organize', title: 'Organize' }, <ide> ] <ide>
Java
apache-2.0
fd23d6bb2f6c50f2a72bc6ef2934a4a8448fefbd
0
jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim
/* * JaamSim Discrete Event Simulation * Copyright (C) 2002-2011 Ausenco Engineering Canada Inc. * Copyright (C) 2016-2020 JaamSim Software Inc. * * 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. */ package com.jaamsim.ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Frame; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.FocusEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Rectangle2D; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.prefs.Preferences; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.swing.Box; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.JWindow; import javax.swing.KeyStroke; import javax.swing.SpinnerNumberModel; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import javax.swing.filechooser.FileNameExtensionFilter; import com.jaamsim.Commands.Command; import com.jaamsim.Commands.CoordinateCommand; import com.jaamsim.Commands.DefineCommand; import com.jaamsim.Commands.DefineViewCommand; import com.jaamsim.Commands.DeleteCommand; import com.jaamsim.Commands.KeywordCommand; import com.jaamsim.Commands.RenameCommand; import com.jaamsim.DisplayModels.TextModel; import com.jaamsim.Graphics.BillboardText; import com.jaamsim.Graphics.DirectedEntity; import com.jaamsim.Graphics.DisplayEntity; import com.jaamsim.Graphics.EntityLabel; import com.jaamsim.Graphics.FillEntity; import com.jaamsim.Graphics.LineEntity; import com.jaamsim.Graphics.OverlayEntity; import com.jaamsim.Graphics.OverlayText; import com.jaamsim.Graphics.Region; import com.jaamsim.Graphics.TextBasics; import com.jaamsim.Graphics.TextEntity; import com.jaamsim.Graphics.View; import com.jaamsim.ProbabilityDistributions.RandomStreamUser; import com.jaamsim.SubModels.CompoundEntity; import com.jaamsim.basicsim.Entity; import com.jaamsim.basicsim.ErrorException; import com.jaamsim.basicsim.GUIListener; import com.jaamsim.basicsim.JaamSimModel; import com.jaamsim.basicsim.Simulation; import com.jaamsim.controllers.RateLimiter; import com.jaamsim.controllers.RenderManager; import com.jaamsim.datatypes.IntegerVector; import com.jaamsim.events.EventManager; import com.jaamsim.events.EventTimeListener; import com.jaamsim.input.ColourInput; import com.jaamsim.input.Input; import com.jaamsim.input.InputAgent; import com.jaamsim.input.InputErrorException; import com.jaamsim.input.KeywordIndex; import com.jaamsim.input.Parser; import com.jaamsim.math.Color4d; import com.jaamsim.math.MathUtils; import com.jaamsim.math.Vec3d; import com.jaamsim.rng.MRG1999a; import com.jaamsim.units.DimensionlessUnit; import com.jaamsim.units.DistanceUnit; import com.jaamsim.units.TimeUnit; /** * The main window for a Graphical Simulation. It provides the controls for managing then * EventManager (run, pause, ...) and the graphics (zoom, pan, ...) */ public class GUIFrame extends OSFixJFrame implements EventTimeListener, GUIListener { private static GUIFrame instance; private static JaamSimModel sim; private static final ArrayList<JaamSimModel> simList = new ArrayList<>(); private static final AtomicLong modelCount = new AtomicLong(0); // number of JaamSimModels private final ArrayList<View> views = new ArrayList<>(); private int nextViewID = 1; // global shutdown flag static private AtomicBoolean shuttingDown; private JMenu fileMenu; private JMenu editMenu; private JMenu toolsMenu; private JMenu viewsMenu; private JMenu optionMenu; private JMenu unitsMenu; private JMenu windowMenu; private JMenu helpMenu; private JToggleButton snapToGrid; private JToggleButton xyzAxis; private JToggleButton grid; private JCheckBoxMenuItem alwaysTop; private JCheckBoxMenuItem graphicsDebug; private JMenuItem printInputItem; private JMenuItem saveConfigurationMenuItem; // "Save" private JLabel clockDisplay; private JLabel speedUpDisplay; private JLabel remainingDisplay; private JMenuItem undoMenuItem; private JMenuItem redoMenuItem; private JMenuItem copyMenuItem; private JMenuItem pasteMenuItem; private JMenuItem deleteMenuItem; private JToggleButton controlRealTime; private JSpinner spinner; private JButton fileSave; private JButton undo; private JButton redo; private JButton undoDropdown; private JButton redoDropdown; private final ArrayList<Command> undoList = new ArrayList<>(); private final ArrayList<Command> redoList = new ArrayList<>(); private JToggleButton showLabels; private JToggleButton showSubModels; private JToggleButton showLinks; private JToggleButton createLinks; private JButton nextButton; private JButton prevButton; private JToggleButton reverseButton; private JButton copyButton; private JButton pasteButton; private JToggleButton find; private JTextField dispModel; private JButton modelSelector; private JButton editDmButton; private JButton clearButton; private Entity selectedEntity; private ButtonGroup alignmentGroup; private JToggleButton alignLeft; private JToggleButton alignCentre; private JToggleButton alignRight; private JToggleButton bold; private JToggleButton italic; private JTextField font; private JButton fontSelector; private JTextField textHeight; private JButton largerText; private JButton smallerText; private ColorIcon colourIcon; private JButton fontColour; private JButton increaseZ; private JButton decreaseZ; private JToggleButton outline; private JSpinner lineWidth; private ColorIcon lineColourIcon; private JButton lineColour; private JToggleButton fill; private ColorIcon fillColourIcon; private JButton fillColour; private RoundToggleButton controlStartResume; private ImageIcon runPressedIcon; private ImageIcon pausePressedIcon; private RoundToggleButton controlStop; private JTextField pauseTime; private JTextField gridSpacing; private JLabel locatorPos; //JButton toolButtonIsometric; private JToggleButton lockViewXYPlane; private int lastValue = -1; private JProgressBar progressBar; private static ArrayList<Image> iconImages = new ArrayList<>(); private static final RateLimiter rateLimiter; private static boolean SAFE_GRAPHICS; // Collection of default window parameters int DEFAULT_GUI_WIDTH; int COL1_WIDTH; int COL2_WIDTH; int COL3_WIDTH; int COL4_WIDTH; int COL1_START; int COL2_START; int COL3_START; int COL4_START; int HALF_TOP; int HALF_BOTTOM; int TOP_START; int BOTTOM_START; int LOWER_HEIGHT; int LOWER_START; int VIEW_HEIGHT; int VIEW_WIDTH; int VIEW_OFFSET = 50; private static final String LAST_USED_FOLDER = ""; private static final String LAST_USED_3D_FOLDER = "3D_FOLDER"; private static final String LAST_USED_IMAGE_FOLDER = "IMAGE_FOLDER"; private static final String RUN_TOOLTIP = GUIFrame.formatToolTip("Run (space key)", "Starts or resumes the simulation run."); private static final String PAUSE_TOOLTIP = "<html><b>Pause</b></html>"; // Use a small tooltip for Pause so that it does not block the simulation time display static { try { if (OSFix.isWindows()) UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); else UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { LogBox.logLine("Unable to change look and feel."); } try { iconImages.clear(); Toolkit toolkit = Toolkit.getDefaultToolkit(); iconImages.add(toolkit.getImage(GUIFrame.class.getResource("/resources/images/icon-16.png"))); iconImages.add(toolkit.getImage(GUIFrame.class.getResource("/resources/images/icon-32.png"))); iconImages.add(toolkit.getImage(GUIFrame.class.getResource("/resources/images/icon-64.png"))); iconImages.add(toolkit.getImage(GUIFrame.class.getResource("/resources/images/icon-128.png"))); } catch (Exception e) { LogBox.logLine("Unable to load icon file."); } shuttingDown = new AtomicBoolean(false); rateLimiter = RateLimiter.create(60); } private GUIFrame() { super(); getContentPane().setLayout( new BorderLayout() ); setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ); // Initialize the working environment initializeMenus(); initializeButtonBar(); initializeMainToolBars(); this.setIconImages(GUIFrame.getWindowIcons()); //Set window size setResizable( true ); //FIXME should be false, but this causes the window to be sized // and positioned incorrectly in the Windows 7 Aero theme pack(); controlStartResume.requestFocusInWindow(); controlStartResume.setSelected( false ); controlStartResume.setEnabled( false ); controlStop.setSelected( false ); controlStop.setEnabled( false ); ToolTipManager.sharedInstance().setLightWeightPopupEnabled( false ); JPopupMenu.setDefaultLightWeightPopupEnabled( false ); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { close(); } @Override public void windowDeiconified(WindowEvent e) { showWindows(); } @Override public void windowIconified(WindowEvent e) { updateUI(); } @Override public void windowActivated(WindowEvent e) { showWindows(); } }); addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { if (sim.getSimulation() == null) return; sim.getSimulation().setControlPanelWidth(getSize().width); } @Override public void componentMoved(ComponentEvent e) { Simulation simulation = sim.getSimulation(); if (simulation == null) return; windowOffset = new Point(getLocation().x - initLocation.x, getLocation().y - initLocation.y); updateToolLocations(simulation); updateViewLocations(); } }); } private Point windowOffset = new Point(); private Point initLocation = new Point(getX(), getY()); // bypass the OSFix correction public Point getRelativeLocation(int x, int y) { return new Point(x - windowOffset.x, y - windowOffset.y); } public Point getGlobalLocation(int x, int y) { return new Point(x + windowOffset.x, y + windowOffset.y); } public static JaamSimModel getJaamSimModel() { return sim; } private static void setJaamSimModel(JaamSimModel sm) { if (sm == sim) return; if (!simList.contains(sm)) simList.add(sm); // Clear the listeners for the previous model if (sim != null) { sim.setTimeListener(null); sim.setGUIListener(null); } sim = sm; GUIFrame gui = getInstance(); if (gui == null) return; RenderManager.clear(); EntityPallet.update(); ObjectSelector.allowUpdate(); gui.resetViews(); gui.setTitle(sm); // Set the listeners for the new model sm.setTimeListener(gui); sm.setGUIListener(gui); // Pass the simulation time for the new model to the user interface gui.initSpeedUp(sm.getSimTime()); gui.tickUpdate(sm.getSimTicks()); gui.updateForSimulationState(sm.getSimState()); } public void setTitle(JaamSimModel sm) { String str = "JaamSim"; if (sm.getSimulation() != null) str = sm.getSimulation().getModelName(); setTitle(sm.toString() + " - " + str); } public void setTitle(JaamSimModel sm, int val) { String str = "JaamSim"; if (sm.getSimulation() != null) str = sm.getSimulation().getModelName(); String title = String.format("%d%% %s - %s", val, sim.toString(), str); setTitle(title); } private static JaamSimModel getNextJaamSimModel() { long num = modelCount.incrementAndGet(); return new JaamSimModel("Model" + num); } @Override public Dimension getPreferredSize() { Point fix = OSFix.getSizeAdustment(); return new Dimension(DEFAULT_GUI_WIDTH + fix.x, super.getPreferredSize().height); } public static synchronized GUIFrame getInstance() { return instance; } private static synchronized GUIFrame createInstance() { instance = new GUIFrame(); UIUpdater updater = new UIUpdater(instance); GUIFrame.registerCallback(new Runnable() { @Override public void run() { SwingUtilities.invokeLater(updater); } }); return instance; } public static final void registerCallback(Runnable r) { rateLimiter.registerCallback(r); } public static final void updateUI() { rateLimiter.queueUpdate(); } public void showWindows() { if (!RenderManager.isGood()) return; // Identity the view window that is active View activeView = RenderManager.inst().getActiveView(); // Re-open the view windows for (int i = 0; i < views.size(); i++) { View v = views.get(i); if (v != null && v.showWindow() && v != activeView) RenderManager.inst().createWindow(v); } // Re-open the active view window last if (activeView != null) RenderManager.inst().createWindow(activeView); // Re-open the tools showActiveTools(sim.getSimulation()); updateUI(); } /** * Perform exit window duties */ void close() { // check for unsaved changes if (sim.isSessionEdited()) { boolean confirmed = GUIFrame.showSaveChangesDialog(this); if (!confirmed) return; } sim.closeLogFile(); simList.remove(sim); if (simList.isEmpty()) GUIFrame.shutdown(0); setJaamSimModel(simList.get(0)); FrameBox.setSelectedEntity(sim.getSimulation(), false); } /** * Clears the simulation and user interface prior to loading a new model */ public void clear() { this.updateForSimulationState(JaamSimModel.SIM_STATE_LOADED); // Clear the buttons clearButtons(); clearUndoRedo(); } /** * Sets up the Control Panel's menu bar. */ private void initializeMenus() { // Set up the individual menus this.initializeFileMenu(); this.initializeEditMenu(); this.initializeToolsMenu(); this.initializeViewsMenu(); this.initializeOptionsMenu(); this.initializeUnitsMenu(); this.initializeWindowMenu(); this.initializeHelpMenu(); // Add the individual menu to the main menu JMenuBar mainMenuBar = new JMenuBar(); mainMenuBar.add( fileMenu ); mainMenuBar.add( editMenu ); mainMenuBar.add( toolsMenu ); mainMenuBar.add( viewsMenu ); mainMenuBar.add( optionMenu ); mainMenuBar.add( unitsMenu ); mainMenuBar.add( windowMenu ); mainMenuBar.add( helpMenu ); // Add main menu to the window setJMenuBar( mainMenuBar ); } // ****************************************************************************************************** // MENU BAR // ****************************************************************************************************** /** * Sets up the File menu in the Control Panel's menu bar. */ private void initializeFileMenu() { // File menu creation fileMenu = new JMenu( "File" ); fileMenu.setMnemonic(KeyEvent.VK_F); fileMenu.setEnabled( false ); // 1) "New" menu item JMenuItem newMenuItem = new JMenuItem( "New" ); newMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/New-16.png")) ); newMenuItem.setMnemonic(KeyEvent.VK_N); newMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)); newMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.newModel(); } } ); fileMenu.add( newMenuItem ); // 2) "Open" menu item JMenuItem configMenuItem = new JMenuItem( "Open..." ); configMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/Open-16.png")) ); configMenuItem.setMnemonic(KeyEvent.VK_O); configMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK)); configMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.load(); } } ); fileMenu.add( configMenuItem ); // 3) "Save" menu item saveConfigurationMenuItem = new JMenuItem( "Save" ); saveConfigurationMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/Save-16.png")) ); saveConfigurationMenuItem.setMnemonic(KeyEvent.VK_S); saveConfigurationMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)); saveConfigurationMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.save(); } } ); fileMenu.add( saveConfigurationMenuItem ); // 4) "Save As..." menu item JMenuItem saveConfigurationAsMenuItem = new JMenuItem( "Save As..." ); saveConfigurationAsMenuItem.setMnemonic(KeyEvent.VK_V); saveConfigurationAsMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.ALT_MASK + ActionEvent.CTRL_MASK)); saveConfigurationAsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.saveAs(); } } ); fileMenu.add( saveConfigurationAsMenuItem ); fileMenu.addSeparator(); // 5) "Import..." menu item JMenu importGraphicsMenuItem = new JMenu( "Import..." ); importGraphicsMenuItem.setMnemonic(KeyEvent.VK_I); JMenuItem importImages = new JMenuItem( "Images..." ); importImages.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { DisplayEntityFactory.importImages(GUIFrame.this); } } ); importGraphicsMenuItem.add( importImages ); JMenuItem import3D = new JMenuItem( "3D Assets..." ); import3D.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { DisplayEntityFactory.import3D(GUIFrame.this); } } ); importGraphicsMenuItem.add( import3D ); fileMenu.add( importGraphicsMenuItem ); // 6) "Print Input Report" menu item printInputItem = new JMenuItem( "Print Input Report" ); printInputItem.setMnemonic(KeyEvent.VK_I); printInputItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.printInputFileKeywords(sim); } } ); fileMenu.add( printInputItem ); // 7) "Exit" menu item JMenuItem exitMenuItem = new JMenuItem( "Exit" ); exitMenuItem.setMnemonic(KeyEvent.VK_X); exitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, ActionEvent.ALT_MASK)); exitMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { close(); } }); fileMenu.addSeparator(); fileMenu.add( exitMenuItem ); } /** * Sets up the Edit menu in the Control Panel's menu bar. */ private void initializeEditMenu() { // Edit menu creation editMenu = new JMenu( "Edit" ); editMenu.setMnemonic(KeyEvent.VK_E); // 1) "Undo" menu item undoMenuItem = new JMenuItem("Undo"); undoMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/Undo-16.png")) ); undoMenuItem.setMnemonic(KeyEvent.VK_U); undoMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_Z, ActionEvent.CTRL_MASK)); undoMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { undo(); } } ); editMenu.add( undoMenuItem ); // 2) "Redo" menu item redoMenuItem = new JMenuItem("Redo"); redoMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/Redo-16.png")) ); redoMenuItem.setMnemonic(KeyEvent.VK_R); redoMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_Y, ActionEvent.CTRL_MASK)); redoMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { redo(); } } ); editMenu.add( redoMenuItem ); editMenu.addSeparator(); // 3) "Copy" menu item copyMenuItem = new JMenuItem("Copy"); copyMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/Copy-16.png")) ); copyMenuItem.setMnemonic(KeyEvent.VK_C); copyMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_C, ActionEvent.CTRL_MASK)); copyMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (selectedEntity == null) return; copyToClipboard(selectedEntity); } } ); editMenu.add( copyMenuItem ); // 4) "Paste" menu item pasteMenuItem = new JMenuItem("Paste"); pasteMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/Paste-16.png")) ); pasteMenuItem.setMnemonic(KeyEvent.VK_P); pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_V, ActionEvent.CTRL_MASK)); pasteMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { pasteEntityFromClipboard(); } } ); editMenu.add( pasteMenuItem ); // 5) "Delete" menu item deleteMenuItem = new JMenuItem("Delete"); deleteMenuItem.setMnemonic(KeyEvent.VK_D); deleteMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_DELETE, 0)); deleteMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (selectedEntity == null) return; try { deleteEntity(selectedEntity); FrameBox.setSelectedEntity(null, false); } catch (ErrorException e) { GUIFrame.showErrorDialog("User Error", e.getMessage()); } } } ); editMenu.add( deleteMenuItem ); editMenu.addSeparator(); // 6) "Find" menu item JMenuItem findMenuItem = new JMenuItem("Find"); findMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/Find-16.png")) ); findMenuItem.setMnemonic(KeyEvent.VK_F); findMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_F, ActionEvent.CTRL_MASK)); findMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { FindBox.getInstance().showDialog(); } } ); editMenu.add( findMenuItem ); } /** * Sets up the Tools menu in the Control Panel's menu bar. */ private void initializeToolsMenu() { // Tools menu creation toolsMenu = new JMenu( "Tools" ); toolsMenu.setMnemonic(KeyEvent.VK_T); // 1) "Show Basic Tools" menu item JMenuItem showBasicToolsMenuItem = new JMenuItem( "Show Basic Tools" ); showBasicToolsMenuItem.setMnemonic(KeyEvent.VK_B); showBasicToolsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { EntityPallet.getInstance().toFront(); ObjectSelector.getInstance().toFront(); EditBox.getInstance().toFront(); OutputBox.getInstance().toFront(); KeywordIndex[] kws = new KeywordIndex[4]; kws[0] = InputAgent.formatBoolean("ShowModelBuilder", true); kws[1] = InputAgent.formatBoolean("ShowObjectSelector", true); kws[2] = InputAgent.formatBoolean("ShowInputEditor", true); kws[3] = InputAgent.formatBoolean("ShowOutputViewer", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kws)); } } ); toolsMenu.add( showBasicToolsMenuItem ); // 2) "Close All Tools" menu item JMenuItem closeAllToolsMenuItem = new JMenuItem( "Close All Tools" ); closeAllToolsMenuItem.setMnemonic(KeyEvent.VK_C); closeAllToolsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { KeywordIndex[] kws = new KeywordIndex[7]; kws[0] = InputAgent.formatBoolean("ShowModelBuilder", false); kws[1] = InputAgent.formatBoolean("ShowObjectSelector", false); kws[2] = InputAgent.formatBoolean("ShowInputEditor", false); kws[3] = InputAgent.formatBoolean("ShowOutputViewer", false); kws[4] = InputAgent.formatBoolean("ShowPropertyViewer", false); kws[5] = InputAgent.formatBoolean("ShowLogViewer", false); kws[6] = InputAgent.formatBoolean("ShowEventViewer", false); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kws)); } } ); toolsMenu.add( closeAllToolsMenuItem ); // 3) "Model Builder" menu item JMenuItem objectPalletMenuItem = new JMenuItem( "Model Builder" ); objectPalletMenuItem.setMnemonic(KeyEvent.VK_O); objectPalletMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { EntityPallet.getInstance().toFront(); KeywordIndex kw = InputAgent.formatBoolean("ShowModelBuilder", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } ); toolsMenu.addSeparator(); toolsMenu.add( objectPalletMenuItem ); // 4) "Object Selector" menu item JMenuItem objectSelectorMenuItem = new JMenuItem( "Object Selector" ); objectSelectorMenuItem.setMnemonic(KeyEvent.VK_S); objectSelectorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ObjectSelector.getInstance().toFront(); KeywordIndex kw = InputAgent.formatBoolean("ShowObjectSelector", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } ); toolsMenu.add( objectSelectorMenuItem ); // 5) "Input Editor" menu item JMenuItem inputEditorMenuItem = new JMenuItem( "Input Editor" ); inputEditorMenuItem.setMnemonic(KeyEvent.VK_I); inputEditorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { EditBox.getInstance().toFront(); KeywordIndex kw = InputAgent.formatBoolean("ShowInputEditor", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } ); toolsMenu.add( inputEditorMenuItem ); // 6) "Output Viewer" menu item JMenuItem outputMenuItem = new JMenuItem( "Output Viewer" ); outputMenuItem.setMnemonic(KeyEvent.VK_U); outputMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { OutputBox.getInstance().toFront(); KeywordIndex kw = InputAgent.formatBoolean("ShowOutputViewer", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } ); toolsMenu.add( outputMenuItem ); // 7) "Property Viewer" menu item JMenuItem propertiesMenuItem = new JMenuItem( "Property Viewer" ); propertiesMenuItem.setMnemonic(KeyEvent.VK_P); propertiesMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PropertyBox.getInstance().toFront(); KeywordIndex kw = InputAgent.formatBoolean("ShowPropertyViewer", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } ); toolsMenu.add( propertiesMenuItem ); // 8) "Log Viewer" menu item JMenuItem logMenuItem = new JMenuItem( "Log Viewer" ); logMenuItem.setMnemonic(KeyEvent.VK_L); logMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { LogBox.getInstance().toFront(); KeywordIndex kw = InputAgent.formatBoolean("ShowLogViewer", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } ); toolsMenu.add( logMenuItem ); // 9) "Event Viewer" menu item JMenuItem eventsMenuItem = new JMenuItem( "Event Viewer" ); eventsMenuItem.setMnemonic(KeyEvent.VK_E); eventsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { EventViewer.getInstance().toFront(); KeywordIndex kw = InputAgent.formatBoolean("ShowEventViewer", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } ); toolsMenu.add( eventsMenuItem ); // 10) "Reset Positions and Sizes" menu item JMenuItem resetItem = new JMenuItem( "Reset Positions and Sizes" ); resetItem.setMnemonic(KeyEvent.VK_R); resetItem.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { sim.getSimulation().resetWindowPositionsAndSizes(); } } ); toolsMenu.addSeparator(); toolsMenu.add( resetItem ); } /** * Sets up the Views menu in the Control Panel's menu bar. */ private void initializeViewsMenu() { viewsMenu = new JMenu("Views"); viewsMenu.setMnemonic(KeyEvent.VK_V); viewsMenu.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { // 1) Select from the available view windows for (View view : getInstance().getViews()) { JMenuItem item = new JMenuItem(view.getName()); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { if (RenderManager.canInitialize()) { RenderManager.initialize(SAFE_GRAPHICS); } else { // A fatal error has occurred, don't try to initialize again return; } } KeywordIndex kw = InputAgent.formatBoolean("ShowWindow", true); InputAgent.storeAndExecute(new KeywordCommand(view, kw)); FrameBox.setSelectedEntity(view, false); } }); viewsMenu.add(item); } // 2) "Define New View" menu item JMenuItem defineItem = new JMenuItem("Define New View"); defineItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { if (RenderManager.canInitialize()) { RenderManager.initialize(SAFE_GRAPHICS); } else { // A fatal error has occurred, don't try to initialize again return; } } String name = InputAgent.getUniqueName(sim, "View", ""); IntegerVector winPos = null; Vec3d pos = null; Vec3d center = null; ArrayList<View> viewList = getInstance().getViews(); if (!viewList.isEmpty()) { View lastView = viewList.get(viewList.size() - 1); winPos = (IntegerVector) lastView.getInput("WindowPosition").getValue(); winPos = new IntegerVector(winPos); winPos.set(0, winPos.get(0) + VIEW_OFFSET); pos = lastView.getViewPosition(); center = lastView.getViewCenter(); } InputAgent.storeAndExecute(new DefineViewCommand(sim, name, pos, center, winPos)); } }); viewsMenu.addSeparator(); viewsMenu.add(defineItem); // 3) "Reset Positions and Sizes" menu item JMenuItem resetItem = new JMenuItem( "Reset Positions and Sizes" ); resetItem.setMnemonic(KeyEvent.VK_R); resetItem.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { for (View v : getInstance().getViews()) { KeywordIndex posKw = InputAgent.formatArgs("WindowPosition"); KeywordIndex sizeKw = InputAgent.formatArgs("WindowSize"); InputAgent.storeAndExecute(new KeywordCommand(v, posKw, sizeKw)); } } } ); viewsMenu.addSeparator(); viewsMenu.add(resetItem); } @Override public void menuCanceled(MenuEvent arg0) { } @Override public void menuDeselected(MenuEvent arg0) { viewsMenu.removeAll(); } }); } /** * Sets up the Options menu in the Control Panel's menu bar. */ private void initializeOptionsMenu() { optionMenu = new JMenu( "Options" ); optionMenu.setMnemonic(KeyEvent.VK_O); // 1) "Always on top" check box alwaysTop = new JCheckBoxMenuItem( "Always on top", false ); alwaysTop.setMnemonic(KeyEvent.VK_A); optionMenu.add( alwaysTop ); alwaysTop.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { if( GUIFrame.this.isAlwaysOnTop() ) { GUIFrame.this.setAlwaysOnTop( false ); } else { GUIFrame.this.setAlwaysOnTop( true ); } } } ); // 2) "Graphics Debug Info" check box graphicsDebug = new JCheckBoxMenuItem( "Graphics Debug Info", false ); graphicsDebug.setMnemonic(KeyEvent.VK_D); optionMenu.add( graphicsDebug ); graphicsDebug.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RenderManager.setDebugInfo(((JCheckBoxMenuItem)e.getSource()).getState()); } }); } /** * Sets up the Units menu in the Control Panel's menu bar. */ private void initializeUnitsMenu() { unitsMenu = new JMenu( "Units" ); unitsMenu.setMnemonic(KeyEvent.VK_U); unitsMenu.addMenuListener( new MenuListener() { @Override public void menuCanceled(MenuEvent arg0) {} @Override public void menuDeselected(MenuEvent arg0) { unitsMenu.removeAll(); } @Override public void menuSelected(MenuEvent arg0) { UnitsSelector.populateMenu(unitsMenu); unitsMenu.setVisible(true); } }); } /** * Sets up the Windows menu in the Control Panel's menu bar. */ private void initializeWindowMenu() { windowMenu = new JMenu( "Window" ); windowMenu.setMnemonic(KeyEvent.VK_W); windowMenu.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { for (JaamSimModel sm : simList) { JRadioButtonMenuItem item = new JRadioButtonMenuItem(sm.toString()); if (sm == sim) item.setSelected(true); item.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { setJaamSimModel(sm); FrameBox.setSelectedEntity(sm.getSimulation(), false); } } ); windowMenu.add( item ); } } @Override public void menuCanceled(MenuEvent arg0) { } @Override public void menuDeselected(MenuEvent arg0) { windowMenu.removeAll(); } }); } /** * Sets up the Help menu in the Control Panel's menu bar. */ private void initializeHelpMenu() { // Help menu creation helpMenu = new JMenu( "Help" ); helpMenu.setMnemonic(KeyEvent.VK_H); // 1) "About" menu item JMenuItem aboutMenu = new JMenuItem( "About" ); aboutMenu.setMnemonic(KeyEvent.VK_A); aboutMenu.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { AboutBox about = new AboutBox(); about.setLocationRelativeTo(null); about.setVisible(true); } } ); helpMenu.add( aboutMenu ); // 2) "Help" menu item JMenuItem helpItem = new JMenuItem( "Help" ); helpItem.setMnemonic(KeyEvent.VK_H); helpItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); helpItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { String topic = ""; if (selectedEntity != null) topic = selectedEntity.getObjectType().getName(); HelpBox.getInstance().showDialog(topic); } } ); helpMenu.add( helpItem ); } /** * Returns the pixel length of the string with specified font */ private static int getPixelWidthOfString_ForFont(String str, Font font) { FontMetrics metrics = new FontMetrics(font) {}; Rectangle2D bounds = metrics.getStringBounds(str, null); return (int)bounds.getWidth(); } // ****************************************************************************************************** // BUTTON BAR // ****************************************************************************************************** /** * Sets up the Control Panel's button bar. */ public void initializeButtonBar() { Insets noMargin = new Insets( 0, 0, 0, 0 ); Insets smallMargin = new Insets( 1, 1, 1, 1 ); Dimension separatorDim = new Dimension(11, 20); Dimension gapDim = new Dimension(5, separatorDim.height); JToolBar buttonBar = new JToolBar(); buttonBar.setMargin( smallMargin ); buttonBar.setFloatable(false); buttonBar.setLayout( new FlowLayout( FlowLayout.LEFT, 0, 0 ) ); getContentPane().add( buttonBar, BorderLayout.NORTH ); // File new, open, and save buttons buttonBar.add(Box.createRigidArea(gapDim)); addFileNewButton(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addFileOpenButton(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addFileSaveButton(buttonBar, noMargin); // Undo and redo buttons buttonBar.addSeparator(separatorDim); addUndoButtons(buttonBar, noMargin); // 2D, axes, and grid buttons buttonBar.addSeparator(separatorDim); add2dButton(buttonBar, smallMargin); buttonBar.add(Box.createRigidArea(gapDim)); addShowAxesButton(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addShowGridButton(buttonBar, noMargin); // Show labels button buttonBar.add(Box.createRigidArea(gapDim)); addShowLabelsButton(buttonBar, noMargin); // Show sub-models button buttonBar.add(Box.createRigidArea(gapDim)); addShowSubModelsButton(buttonBar, noMargin); // Snap-to-grid button and field buttonBar.addSeparator(separatorDim); addSnapToGridButton(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addSnapToGridField(buttonBar, noMargin); // Show and create links buttons buttonBar.addSeparator(separatorDim); addShowLinksButton(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addCreateLinksButton(buttonBar, noMargin); // Previous and Next buttons buttonBar.add(Box.createRigidArea(gapDim)); addPreviousButton(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addNextButton(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addReverseButton(buttonBar, noMargin); // Show Copy and Paste buttons buttonBar.addSeparator(separatorDim); addCopyButton(buttonBar, noMargin); addPasteButton(buttonBar, noMargin); // Show Entity Finder button buttonBar.add(Box.createRigidArea(gapDim)); addEntityFinderButton(buttonBar, noMargin); // DisplayModel field and button buttonBar.addSeparator(separatorDim); addDisplayModelSelector(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addEditDisplayModelButton(buttonBar, noMargin); // Clear formatting button buttonBar.add(Box.createRigidArea(gapDim)); addClearFormattingButton(buttonBar, noMargin); // Font selector and text height field buttonBar.addSeparator(separatorDim); addFontSelector(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addTextHeightField(buttonBar, noMargin); // Larger and smaller text height buttons buttonBar.add(Box.createRigidArea(gapDim)); addTextHeightButtons(buttonBar, noMargin); // Bold and Italic buttons buttonBar.add(Box.createRigidArea(gapDim)); addFontStyleButtons(buttonBar, noMargin); // Font colour button buttonBar.add(Box.createRigidArea(gapDim)); addFontColourButton(buttonBar, noMargin); // Text alignment buttons buttonBar.add(Box.createRigidArea(gapDim)); addTextAlignmentButtons(buttonBar, noMargin); // Z-coordinate buttons buttonBar.addSeparator(separatorDim); addZButtons(buttonBar, noMargin); // Line buttons buttonBar.addSeparator(separatorDim); addOutlineButton(buttonBar, noMargin); addLineWidthSpinner(buttonBar, noMargin); addLineColourButton(buttonBar, noMargin); // Fill buttons buttonBar.addSeparator(separatorDim); addFillButton(buttonBar, noMargin); addFillColourButton(buttonBar, noMargin); } private void addFileNewButton(JToolBar buttonBar, Insets margin) { JButton fileNew = new JButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/New-16.png")) ); fileNew.setMargin(margin); fileNew.setFocusPainted(false); fileNew.setToolTipText(formatToolTip("New (Ctrl+N)", "Starts a new model.")); fileNew.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.newModel(); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( fileNew ); } private void addFileOpenButton(JToolBar buttonBar, Insets margin) { JButton fileOpen = new JButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/Open-16.png")) ); fileOpen.setMargin(margin); fileOpen.setFocusPainted(false); fileOpen.setToolTipText(formatToolTip("Open... (Ctrl+O)", "Opens a model.")); fileOpen.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.load(); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( fileOpen ); } private void addFileSaveButton(JToolBar buttonBar, Insets margin) { fileSave = new JButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/Save-16.png")) ); fileSave.setMargin(margin); fileSave.setFocusPainted(false); fileSave.setToolTipText(formatToolTip("Save (Ctrl+S)", "Saves the present model.")); fileSave.setEnabled(false); fileSave.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.save(); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( fileSave ); } private void addUndoButtons(JToolBar buttonBar, Insets margin) { // Undo button undo = new JButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/Undo-16.png")) ); undo.setMargin(margin); undo.setFocusPainted(false); undo.setRequestFocusEnabled(false); undo.setToolTipText(formatToolTip("Undo (Ctrl+Z)", "Reverses the last change to the model.")); undo.setEnabled(!undoList.isEmpty()); undo.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { undo(); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( undo ); // Undo Dropdown Menu undoDropdown = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/dropdown.png"))); undoDropdown.setMargin(margin); undoDropdown.setFocusPainted(false); undoDropdown.setRequestFocusEnabled(false); undoDropdown.setEnabled(!undoList.isEmpty()); undoDropdown.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ScrollablePopupMenu menu = new ScrollablePopupMenu("UndoMenu"); synchronized (undoList) { for (int i = 1; i <= undoList.size(); i++) { Command cmd = undoList.get(undoList.size() - i); final int num = i; JMenuItem item = new JMenuItem(cmd.toString()); item.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { undo(num); controlStartResume.requestFocusInWindow(); } } ); menu.add(item); } menu.show(undoDropdown, 0, undoDropdown.getHeight()); } } } ); buttonBar.add( undoDropdown ); // Redo button redo = new JButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/Redo-16.png")) ); redo.setMargin(margin); redo.setFocusPainted(false); redo.setRequestFocusEnabled(false); redo.setToolTipText(formatToolTip("Redo (Ctrl+Y)", "Re-performs the last change to the model that was undone.")); redo.setEnabled(!redoList.isEmpty()); redo.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { redo(); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( redo ); // Redo Dropdown Menu redoDropdown = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/dropdown.png"))); redoDropdown.setMargin(margin); redoDropdown.setFocusPainted(false); redoDropdown.setRequestFocusEnabled(false); redoDropdown.setEnabled(!redoList.isEmpty()); redoDropdown.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ScrollablePopupMenu menu = new ScrollablePopupMenu("RedoMenu"); synchronized (undoList) { for (int i = 1; i <= redoList.size(); i++) { Command cmd = redoList.get(redoList.size() - i); final int num = i; JMenuItem item = new JMenuItem(cmd.toString()); item.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { redo(num); controlStartResume.requestFocusInWindow(); } } ); menu.add(item); } menu.show(redoDropdown, 0, redoDropdown.getHeight()); } } } ); buttonBar.add( redoDropdown ); } private void add2dButton(JToolBar buttonBar, Insets margin) { lockViewXYPlane = new JToggleButton( "2D" ); lockViewXYPlane.setMargin(margin); lockViewXYPlane.setFocusPainted(false); lockViewXYPlane.setRequestFocusEnabled(false); lockViewXYPlane.setToolTipText(formatToolTip("2D View", "Sets the camera position to show a bird's eye view of the 3D scene.")); lockViewXYPlane.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { boolean bLock2D = (((JToggleButton)event.getSource()).isSelected()); if (RenderManager.isGood()) { View currentView = RenderManager.inst().getActiveView(); if (currentView != null) { currentView.setLock2D(bLock2D); } } controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( lockViewXYPlane ); } private void addShowAxesButton(JToolBar buttonBar, Insets margin) { xyzAxis = new JToggleButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/Axes-16.png")) ); xyzAxis.setMargin(margin); xyzAxis.setFocusPainted(false); xyzAxis.setRequestFocusEnabled(false); xyzAxis.setToolTipText(formatToolTip("Show Axes", "Shows the unit vectors for the x, y, and z axes.")); xyzAxis.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { DisplayEntity ent = (DisplayEntity) sim.getNamedEntity("XYZ-Axis"); if (ent != null) { KeywordIndex kw = InputAgent.formatBoolean("Show", xyzAxis.isSelected()); InputAgent.storeAndExecute(new KeywordCommand(ent, kw)); } controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( xyzAxis ); } private void addShowGridButton(JToolBar buttonBar, Insets margin) { grid = new JToggleButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/Grid-16.png")) ); grid.setMargin(margin); grid.setFocusPainted(false); grid.setRequestFocusEnabled(false); grid.setToolTipText(formatToolTip("Show Grid", "Shows the coordinate grid on the x-y plane.")); grid.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { DisplayEntity ent = (DisplayEntity) sim.getNamedEntity("XY-Grid"); if (ent == null && sim.getNamedEntity("Grid100x100") != null) { InputAgent.storeAndExecute(new DefineCommand(sim, DisplayEntity.class, "XY-Grid")); ent = (DisplayEntity) sim.getNamedEntity("XY-Grid"); KeywordIndex dmKw = InputAgent.formatArgs("DisplayModel", "Grid100x100"); KeywordIndex sizeKw = InputAgent.formatArgs("Size", "100", "100", "0", "m"); InputAgent.storeAndExecute(new KeywordCommand(ent, dmKw, sizeKw)); grid.setSelected(true); } if (ent != null) { KeywordIndex kw = InputAgent.formatBoolean("Show", grid.isSelected()); InputAgent.storeAndExecute(new KeywordCommand(ent, kw)); } controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( grid ); } private void addShowLabelsButton(JToolBar buttonBar, Insets margin) { showLabels = new JToggleButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/ShowLabels-16.png")) ); showLabels.setMargin(margin); showLabels.setFocusPainted(false); showLabels.setRequestFocusEnabled(false); showLabels.setToolTipText(formatToolTip("Show Labels", "Displays the label for every entity in the model.")); showLabels.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { boolean bool = showLabels.isSelected(); KeywordIndex kw = InputAgent.formatBoolean("ShowLabels", bool); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); setShowLabels(bool); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( showLabels ); } private void addShowSubModelsButton(JToolBar buttonBar, Insets margin) { showSubModels = new JToggleButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/ShowSubModels-16.png")) ); showSubModels.setMargin(margin); showSubModels.setFocusPainted(false); showSubModels.setRequestFocusEnabled(false); showSubModels.setToolTipText(formatToolTip("Show SubModels", "Displays the components of each sub-model.")); showSubModels.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { boolean bool = showSubModels.isSelected(); KeywordIndex kw = InputAgent.formatBoolean("ShowSubModels", bool); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); setShowSubModels(bool); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( showSubModels ); } private void addSnapToGridButton(JToolBar buttonBar, Insets margin) { snapToGrid = new JToggleButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/Snap-16.png")) ); snapToGrid.setMargin(margin); snapToGrid.setFocusPainted(false); snapToGrid.setRequestFocusEnabled(false); snapToGrid.setToolTipText(formatToolTip("Snap to Grid", "During repositioning, objects are forced to the nearest grid point.")); snapToGrid.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { KeywordIndex kw = InputAgent.formatBoolean("SnapToGrid", snapToGrid.isSelected()); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); gridSpacing.setEnabled(snapToGrid.isSelected()); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( snapToGrid ); } private void addSnapToGridField(JToolBar buttonBar, Insets margin) { gridSpacing = new JTextField("1000000 m") { @Override protected void processFocusEvent(FocusEvent fe) { if (fe.getID() == FocusEvent.FOCUS_LOST) { GUIFrame.this.setSnapGridSpacing(this.getText().trim()); } else if (fe.getID() == FocusEvent.FOCUS_GAINED) { gridSpacing.selectAll(); } super.processFocusEvent( fe ); } }; gridSpacing.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { GUIFrame.this.setSnapGridSpacing(gridSpacing.getText().trim()); controlStartResume.requestFocusInWindow(); } }); gridSpacing.setMaximumSize(gridSpacing.getPreferredSize()); int hght = snapToGrid.getPreferredSize().height; gridSpacing.setPreferredSize(new Dimension(gridSpacing.getPreferredSize().width, hght)); gridSpacing.setHorizontalAlignment(JTextField.RIGHT); gridSpacing.setToolTipText(formatToolTip("Snap Grid Spacing", "Distance between adjacent grid points, e.g. 0.1 m, 10 km, etc.")); gridSpacing.setEnabled(snapToGrid.isSelected()); buttonBar.add(gridSpacing); } private void addShowLinksButton(JToolBar buttonBar, Insets margin) { showLinks = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/ShowLinks-16.png"))); showLinks.setToolTipText(formatToolTip("Show Entity Flow", "When selected, arrows are shown between objects to indicate the flow of entities.")); showLinks.setMargin(margin); showLinks.setFocusPainted(false); showLinks.setRequestFocusEnabled(false); showLinks.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { boolean bShow = (((JToggleButton)event.getSource()).isSelected()); KeywordIndex kw = InputAgent.formatBoolean("ShowEntityFlow", bShow); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); setShowEntityFlow(bShow); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( showLinks ); } private void addCreateLinksButton(JToolBar buttonBar, Insets margin) { createLinks = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/MakeLinks-16.png"))); createLinks.setToolTipText(formatToolTip("Create Entity Links", "When this is enabled, entities are linked when selection is changed.")); createLinks.setMargin(margin); createLinks.setFocusPainted(false); createLinks.setRequestFocusEnabled(false); createLinks.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { boolean bCreate = (((JToggleButton)event.getSource()).isSelected()); if (RenderManager.isGood()) { if (bCreate) { FrameBox.setSelectedEntity(null, false); if (!showLinks.isSelected()) showLinks.doClick(); } RenderManager.inst().setCreateLinks(bCreate); } controlStartResume.requestFocusInWindow(); } }); buttonBar.add( createLinks ); } private void addPreviousButton(JToolBar buttonBar, Insets margin) { prevButton = new JButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/Previous-16.png"))); prevButton.setToolTipText(formatToolTip("Previous", "Selects the previous object in the chain of linked objects.")); prevButton.setMargin(margin); prevButton.setFocusPainted(false); prevButton.setRequestFocusEnabled(false); prevButton.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (createLinks.isSelected()) createLinks.doClick(); if (selectedEntity != null && selectedEntity instanceof DisplayEntity) { DisplayEntity selectedDEnt = (DisplayEntity) selectedEntity; boolean dir = !reverseButton.isSelected(); ArrayList<DirectedEntity> list = selectedDEnt.getPreviousList(dir); if (list.isEmpty()) return; if (list.size() == 1) { setSelectedDEnt(list.get(0)); return; } ScrollablePopupMenu menu = new ScrollablePopupMenu(); for (DirectedEntity de : list) { JMenuItem item = new JMenuItem(de.toString()); item.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { setSelectedDEnt(de); controlStartResume.requestFocusInWindow(); } } ); menu.add(item); } menu.show(prevButton, 0, prevButton.getHeight()); } } }); buttonBar.add( prevButton ); } private void addNextButton(JToolBar buttonBar, Insets margin) { nextButton = new JButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/Next-16.png"))); nextButton.setToolTipText(formatToolTip("Next", "Selects the next object in the chain of linked objects.")); nextButton.setMargin(margin); nextButton.setFocusPainted(false); nextButton.setRequestFocusEnabled(false); nextButton.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (createLinks.isSelected()) createLinks.doClick(); if (selectedEntity != null && selectedEntity instanceof DisplayEntity) { DisplayEntity selectedDEnt = (DisplayEntity) selectedEntity; boolean dir = !reverseButton.isSelected(); ArrayList<DirectedEntity> list = selectedDEnt.getNextList(dir); if (list.isEmpty()) return; if (list.size() == 1) { setSelectedDEnt(list.get(0)); return; } ScrollablePopupMenu menu = new ScrollablePopupMenu(); for (DirectedEntity de : list) { JMenuItem item = new JMenuItem(de.toString()); item.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { setSelectedDEnt(de); controlStartResume.requestFocusInWindow(); } } ); menu.add(item); } menu.show(nextButton, 0, nextButton.getHeight()); } } }); buttonBar.add( nextButton ); } private void setSelectedDEnt(DirectedEntity de) { FrameBox.setSelectedEntity(de.entity, false); if (!reverseButton.isSelected() == de.direction) return; reverseButton.doClick(); } private void addReverseButton(JToolBar buttonBar, Insets margin) { reverseButton = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/Reverse-16.png"))); reverseButton.setToolTipText(formatToolTip("Reverse Direction", "When enabled, the link arrows are shown for entities travelling in the reverse " + "direction, and the Next and Previous buttons select the next/previous links " + "for that direction.")); reverseButton.setMargin(margin); reverseButton.setFocusPainted(false); reverseButton.setRequestFocusEnabled(false); reverseButton.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (createLinks.isSelected()) createLinks.doClick(); boolean bool = (((JToggleButton)event.getSource()).isSelected()); if (RenderManager.isGood()) { RenderManager.inst().setLinkDirection(!bool); RenderManager.redraw(); } updateUI(); } }); // Reverse button is not needed in the open source JaamSim //buttonBar.add( reverseButton ); } private void addCopyButton(JToolBar buttonBar, Insets margin) { copyButton = new JButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/Copy-16.png"))); copyButton.setToolTipText(formatToolTip("Copy (Ctrl+C)", "Copies the selected entity to the clipboard.")); copyButton.setMargin(margin); copyButton.setFocusPainted(false); copyButton.setRequestFocusEnabled(false); copyButton.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (selectedEntity != null) copyToClipboard(selectedEntity); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( copyButton ); } private void addPasteButton(JToolBar buttonBar, Insets margin) { pasteButton = new JButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/Paste-16.png"))); pasteButton.setToolTipText(formatToolTip("Paste (Ctrl+V)", "Pastes a copy of an entity from the clipboard to the location of the most recent " + "mouse click.")); pasteButton.setMargin(margin); pasteButton.setFocusPainted(false); pasteButton.setRequestFocusEnabled(false); pasteButton.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { pasteEntityFromClipboard(); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( pasteButton ); } private void addEntityFinderButton(JToolBar buttonBar, Insets margin) { find = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/Find-16.png"))); find.setToolTipText(formatToolTip("Entity Finder (Ctrl+F)", "Searches for an entity with a given name.")); find.setMargin(margin); find.setFocusPainted(false); find.setRequestFocusEnabled(false); find.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (find.isSelected()) { FindBox.getInstance().showDialog(); } else { FindBox.getInstance().setVisible(false); } controlStartResume.requestFocusInWindow(); } }); buttonBar.add( find ); } private void addDisplayModelSelector(JToolBar buttonBar, Insets margin) { dispModel = new JTextField(""); dispModel.setEditable(false); dispModel.setHorizontalAlignment(JTextField.CENTER); dispModel.setPreferredSize(new Dimension(120, fileSave.getPreferredSize().height)); dispModel.setToolTipText(formatToolTip("DisplayModel", "Sets the default appearance of the entity. " + "A DisplayModel is analogous to a text style in a word processor.")); buttonBar.add(dispModel); modelSelector = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/dropdown.png"))); modelSelector.setMargin(margin); modelSelector.setFocusPainted(false); modelSelector.setRequestFocusEnabled(false); modelSelector.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof DisplayEntity)) return; DisplayEntity dispEnt = (DisplayEntity) selectedEntity; if (!dispEnt.isDisplayModelNominal() || dispEnt.getDisplayModelList().size() != 1) return; final String presentModelName = dispEnt.getDisplayModelList().get(0).getName(); Input<?> in = dispEnt.getInput("DisplayModel"); ArrayList<String> choices = in.getValidOptions(selectedEntity); PreviewablePopupMenu menu = new PreviewablePopupMenu(presentModelName, choices, true) { @Override public void setValue(String str) { dispModel.setText(str); KeywordIndex kw = InputAgent.formatArgs("DisplayModel", str); InputAgent.storeAndExecute(new KeywordCommand(dispEnt, kw)); controlStartResume.requestFocusInWindow(); } }; menu.show(dispModel, 0, dispModel.getPreferredSize().height); } }); buttonBar.add(modelSelector); } private void addEditDisplayModelButton(JToolBar buttonBar, Insets margin) { editDmButton = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/Edit-16.png"))); editDmButton.setToolTipText(formatToolTip("Edit DisplayModel", "Selects the present DisplayModel so that its inputs can be edited.")); editDmButton.setMargin(margin); editDmButton.setFocusPainted(false); editDmButton.setRequestFocusEnabled(false); editDmButton.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof DisplayEntity)) return; DisplayEntity dEnt = (DisplayEntity) selectedEntity; if (dEnt.getDisplayModelList().size() != 1) return; FrameBox.setSelectedEntity(dEnt.getDisplayModelList().get(0), false); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( editDmButton ); } private void addClearFormattingButton(JToolBar buttonBar, Insets margin) { clearButton = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/Clear-16.png"))); clearButton.setToolTipText(formatToolTip("Clear Formatting", "Resets the format inputs for the selected Entity or DisplayModel to their default " + "values.")); clearButton.setMargin(margin); clearButton.setFocusPainted(false); clearButton.setRequestFocusEnabled(false); clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (selectedEntity == null) return; ArrayList<KeywordIndex> kwList = new ArrayList<>(); for (Input<?> in : selectedEntity.getEditableInputs()) { String cat = in.getCategory(); if (in.isDefault() || !cat.equals(Entity.FORMAT) && !cat.equals(Entity.FONT)) continue; KeywordIndex kw = InputAgent.formatArgs(in.getKeyword()); kwList.add(kw); } if (kwList.isEmpty()) return; KeywordIndex[] kws = new KeywordIndex[kwList.size()]; kwList.toArray(kws); InputAgent.storeAndExecute(new KeywordCommand(selectedEntity, kws)); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( clearButton ); } private void addTextAlignmentButtons(JToolBar buttonBar, Insets margin) { ActionListener alignListener = new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof TextBasics)) return; TextBasics textEnt = (TextBasics) selectedEntity; Vec3d align = textEnt.getAlignment(); double prevAlign = align.x; align.x = alignLeft.isSelected() ? -0.5d : align.x; align.x = alignCentre.isSelected() ? 0.0d : align.x; align.x = alignRight.isSelected() ? 0.5d : align.x; if (align.x == textEnt.getAlignment().x) return; KeywordIndex kw = sim.formatVec3dInput("Alignment", align, DimensionlessUnit.class); Vec3d pos = textEnt.getPosition(); Vec3d size = textEnt.getSize(); pos.x += (align.x - prevAlign) * size.x; KeywordIndex posKw = sim.formatVec3dInput("Position", pos, DistanceUnit.class); InputAgent.storeAndExecute(new KeywordCommand(textEnt, kw, posKw)); controlStartResume.requestFocusInWindow(); } }; alignLeft = new JToggleButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/AlignLeft-16.png"))); alignLeft.setMargin(margin); alignLeft.setFocusPainted(false); alignLeft.setRequestFocusEnabled(false); alignLeft.setToolTipText(formatToolTip("Align Left", "Aligns the text to the left margin.")); alignLeft.addActionListener( alignListener ); alignCentre = new JToggleButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/AlignCentre-16.png"))); alignCentre.setMargin(margin); alignCentre.setFocusPainted(false); alignCentre.setRequestFocusEnabled(false); alignCentre.setToolTipText(formatToolTip("Align Centre", "Centres the text between the right and left margins.")); alignCentre.addActionListener( alignListener ); alignRight = new JToggleButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/AlignRight-16.png"))); alignRight.setMargin(margin); alignRight.setFocusPainted(false); alignRight.setRequestFocusEnabled(false); alignRight.setToolTipText(formatToolTip("Align Right", "Aligns the text to the right margin.")); alignRight.addActionListener( alignListener ); alignmentGroup = new ButtonGroup(); alignmentGroup.add(alignLeft); alignmentGroup.add(alignCentre); alignmentGroup.add(alignRight); buttonBar.add( alignLeft ); buttonBar.add( alignCentre ); buttonBar.add( alignRight ); } private void addFontStyleButtons(JToolBar buttonBar, Insets margin) { ActionListener alignmentListener = new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof TextEntity)) return; TextEntity textEnt = (TextEntity) selectedEntity; if (textEnt.isBold() == bold.isSelected() && textEnt.isItalic() && italic.isSelected()) return; ArrayList<String> stylesList = new ArrayList<>(2); if (bold.isSelected()) stylesList.add("BOLD"); if (italic.isSelected()) stylesList.add("ITALIC"); String[] styles = stylesList.toArray(new String[stylesList.size()]); KeywordIndex kw = InputAgent.formatArgs("FontStyle", styles); InputAgent.storeAndExecute(new KeywordCommand((Entity)textEnt, kw)); controlStartResume.requestFocusInWindow(); } }; bold = new JToggleButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/Bold-16.png"))); bold.setMargin(margin); bold.setFocusPainted(false); bold.setRequestFocusEnabled(false); bold.setToolTipText(formatToolTip("Bold", "Makes the text bold.")); bold.addActionListener( alignmentListener ); italic = new JToggleButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/Italic-16.png"))); italic.setMargin(margin); italic.setFocusPainted(false); italic.setRequestFocusEnabled(false); italic.setToolTipText(formatToolTip("Italic", "Italicizes the text.")); italic.addActionListener( alignmentListener ); buttonBar.add( bold ); buttonBar.add( italic ); } private void addFontSelector(JToolBar buttonBar, Insets margin) { font = new JTextField(""); font.setEditable(false); font.setHorizontalAlignment(JTextField.CENTER); font.setPreferredSize(new Dimension(120, fileSave.getPreferredSize().height)); font.setToolTipText(formatToolTip("Font", "Sets the font for the text.")); buttonBar.add(font); fontSelector = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/dropdown.png"))); fontSelector.setMargin(margin); fontSelector.setFocusPainted(false); fontSelector.setRequestFocusEnabled(false); fontSelector.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof TextEntity)) return; final TextEntity textEnt = (TextEntity) selectedEntity; final String presentFontName = textEnt.getFontName(); ArrayList<String> valuesInUse = GUIFrame.getFontsInUse(sim); ArrayList<String> choices = TextModel.validFontNames; PreviewablePopupMenu fontMenu = new PreviewablePopupMenu(presentFontName, valuesInUse, choices, true) { @Override public void setValue(String str) { font.setText(str); String name = Parser.addQuotesIfNeeded(str); KeywordIndex kw = InputAgent.formatInput("FontName", name); InputAgent.storeAndExecute(new KeywordCommand(selectedEntity, kw)); controlStartResume.requestFocusInWindow(); } }; fontMenu.show(font, 0, font.getPreferredSize().height); } }); buttonBar.add(fontSelector); } private void addTextHeightField(JToolBar buttonBar, Insets margin) { textHeight = new JTextField("1000000 m") { @Override protected void processFocusEvent(FocusEvent fe) { if (fe.getID() == FocusEvent.FOCUS_LOST) { GUIFrame.this.setTextHeight(this.getText().trim()); } super.processFocusEvent( fe ); } }; textHeight.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { GUIFrame.this.setTextHeight(textHeight.getText().trim()); controlStartResume.requestFocusInWindow(); } }); textHeight.setMaximumSize(textHeight.getPreferredSize()); textHeight.setPreferredSize(new Dimension(textHeight.getPreferredSize().width, fileSave.getPreferredSize().height)); textHeight.setHorizontalAlignment(JTextField.RIGHT); textHeight.setToolTipText(formatToolTip("Text Height", "Sets the height of the text, e.g. 0.1 m, 200 cm, etc.")); buttonBar.add(textHeight); } private void addTextHeightButtons(JToolBar buttonBar, Insets margin) { ActionListener textHeightListener = new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof TextEntity)) return; TextEntity textEnt = (TextEntity) selectedEntity; double height = textEnt.getTextHeight(); double spacing = sim.getSimulation().getSnapGridSpacing(); if (textEnt instanceof OverlayText || textEnt instanceof BillboardText) spacing = 1.0d; height = Math.round(height/spacing) * spacing; if (event.getActionCommand().equals("LargerText")) { height += spacing; } else if (event.getActionCommand().equals("SmallerText")) { height -= spacing; height = Math.max(spacing, height); } String format = "%.1f m"; if (textEnt instanceof OverlayText || textEnt instanceof BillboardText) format = "%.0f"; String str = String.format(format, height); textHeight.setText(str); KeywordIndex kw = InputAgent.formatInput("TextHeight", str); InputAgent.storeAndExecute(new KeywordCommand((Entity)textEnt, kw)); controlStartResume.requestFocusInWindow(); } }; largerText = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/LargerText-16.png"))); largerText.setMargin(margin); largerText.setFocusPainted(false); largerText.setRequestFocusEnabled(false); largerText.setToolTipText(formatToolTip("Larger Text", "Increases the text height to the next higher multiple of the snap grid spacing.")); largerText.setActionCommand("LargerText"); largerText.addActionListener( textHeightListener ); smallerText = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/SmallerText-16.png"))); smallerText.setMargin(margin); smallerText.setFocusPainted(false); smallerText.setRequestFocusEnabled(false); smallerText.setToolTipText(formatToolTip("Smaller Text", "Decreases the text height to the next lower multiple of the snap grid spacing.")); smallerText.setActionCommand("SmallerText"); smallerText.addActionListener( textHeightListener ); buttonBar.add( largerText ); buttonBar.add( smallerText ); } private void addFontColourButton(JToolBar buttonBar, Insets margin) { colourIcon = new ColorIcon(16, 16); colourIcon.setFillColor(Color.LIGHT_GRAY); colourIcon.setOutlineColor(Color.LIGHT_GRAY); fontColour = new JButton(colourIcon); fontColour.setMargin(margin); fontColour.setFocusPainted(false); fontColour.setRequestFocusEnabled(false); fontColour.setToolTipText(formatToolTip("Font Colour", "Sets the colour of the text.")); fontColour.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof TextEntity)) return; final TextEntity textEnt = (TextEntity) selectedEntity; final Color4d presentColour = textEnt.getFontColor(); ArrayList<Color4d> coloursInUse = GUIFrame.getFontColoursInUse(sim); ColourMenu fontMenu = new ColourMenu(presentColour, coloursInUse, true) { @Override public void setColour(String colStr) { KeywordIndex kw = InputAgent.formatInput("FontColour", colStr); InputAgent.storeAndExecute(new KeywordCommand(selectedEntity, kw)); controlStartResume.requestFocusInWindow(); } }; fontMenu.show(fontColour, 0, fontColour.getPreferredSize().height); } }); buttonBar.add( fontColour ); } private void addZButtons(JToolBar buttonBar, Insets margin) { ActionListener actionListener = new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof DisplayEntity) || selectedEntity instanceof OverlayEntity) return; DisplayEntity dispEnt = (DisplayEntity) selectedEntity; double delta = sim.getSimulation().getSnapGridSpacing()/100.0d; Vec3d pos = dispEnt.getPosition(); ArrayList<Vec3d> points = dispEnt.getPoints(); Vec3d offset = new Vec3d(); if (event.getActionCommand().equals("Up")) { pos.z += delta; offset.z += delta; } else if (event.getActionCommand().equals("Down")) { pos.z -= delta; offset.z -= delta; } // Normal object KeywordIndex posKw = sim.formatVec3dInput("Position", pos, DistanceUnit.class); if (!dispEnt.usePointsInput()) { InputAgent.storeAndExecute(new KeywordCommand(dispEnt, posKw)); controlStartResume.requestFocusInWindow(); return; } // Polyline object KeywordIndex ptsKw = sim.formatPointsInputs("Points", points, offset); InputAgent.storeAndExecute(new KeywordCommand(dispEnt, posKw, ptsKw)); controlStartResume.requestFocusInWindow(); } }; increaseZ = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/PlusZ-16.png"))); increaseZ.setMargin(margin); increaseZ.setFocusPainted(false); increaseZ.setRequestFocusEnabled(false); increaseZ.setToolTipText(formatToolTip("Move Up", "Increases the selected object's z-coordinate by one hundredth of the snap-grid " + "spacing. By moving the object closer to the camera, it will appear on top of " + "other objects with smaller z-coordinates.")); increaseZ.setActionCommand("Up"); increaseZ.addActionListener( actionListener ); decreaseZ = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/MinusZ-16.png"))); decreaseZ.setMargin(margin); decreaseZ.setFocusPainted(false); decreaseZ.setRequestFocusEnabled(false); decreaseZ.setToolTipText(formatToolTip("Move Down", "Decreases the selected object's z-coordinate by one hundredth of the snap-grid " + "spacing. By moving the object farther from the camera, it will appear below " + "other objects with larger z-coordinates.")); decreaseZ.setActionCommand("Down"); decreaseZ.addActionListener( actionListener ); buttonBar.add( increaseZ ); buttonBar.add( decreaseZ ); } private void addOutlineButton(JToolBar buttonBar, Insets margin) { outline = new JToggleButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/Outline-16.png"))); outline.setMargin(margin); outline.setFocusPainted(false); outline.setRequestFocusEnabled(false); outline.setToolTipText(formatToolTip("Show Outline", "Shows the outline.")); outline.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof LineEntity)) return; LineEntity lineEnt = (LineEntity) selectedEntity; lineWidth.setEnabled(outline.isSelected()); lineColour.setEnabled(outline.isSelected()); if (lineEnt.isOutlined() == outline.isSelected()) return; KeywordIndex kw = InputAgent.formatBoolean("Outlined", outline.isSelected()); InputAgent.storeAndExecute(new KeywordCommand((Entity)lineEnt, kw)); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( outline ); } private void addLineWidthSpinner(JToolBar buttonBar, Insets margin) { SpinnerNumberModel numberModel = new SpinnerNumberModel(1, 1, 10, 1); lineWidth = new JSpinner(numberModel); lineWidth.addChangeListener(new ChangeListener() { @Override public void stateChanged( ChangeEvent e ) { if (!(selectedEntity instanceof LineEntity)) return; LineEntity lineEnt = (LineEntity) selectedEntity; int val = (int) lineWidth.getValue(); if (val == lineEnt.getLineWidth()) return; KeywordIndex kw = InputAgent.formatIntegers("LineWidth", val); InputAgent.storeAndExecute(new KeywordCommand((Entity)lineEnt, kw)); } }); lineWidth.setToolTipText(formatToolTip("Line Width", "Sets the width of the line in pixels.")); buttonBar.add( lineWidth ); } private void addLineColourButton(JToolBar buttonBar, Insets margin) { lineColourIcon = new ColorIcon(16, 16); lineColourIcon.setFillColor(Color.LIGHT_GRAY); lineColourIcon.setOutlineColor(Color.LIGHT_GRAY); lineColour = new JButton(lineColourIcon); lineColour.setMargin(margin); lineColour.setFocusPainted(false); lineColour.setRequestFocusEnabled(false); lineColour.setToolTipText(formatToolTip("Line Colour", "Sets the colour of the line.")); lineColour.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof LineEntity)) return; final LineEntity lineEnt = (LineEntity) selectedEntity; final Color4d presentColour = lineEnt.getLineColour(); ArrayList<Color4d> coloursInUse = GUIFrame.getLineColoursInUse(sim); ColourMenu menu = new ColourMenu(presentColour, coloursInUse, true) { @Override public void setColour(String colStr) { KeywordIndex kw = InputAgent.formatInput("LineColour", colStr); InputAgent.storeAndExecute(new KeywordCommand(selectedEntity, kw)); controlStartResume.requestFocusInWindow(); } }; menu.show(lineColour, 0, lineColour.getPreferredSize().height); } }); buttonBar.add( lineColour ); } private void addFillButton(JToolBar buttonBar, Insets margin) { fill = new JToggleButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/Fill-16.png"))); fill.setMargin(margin); fill.setFocusPainted(false); fill.setRequestFocusEnabled(false); fill.setToolTipText(formatToolTip("Show Fill", "Fills the entity with the selected colour.")); fill.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof FillEntity)) return; FillEntity fillEnt = (FillEntity) selectedEntity; fillColour.setEnabled(fill.isSelected()); if (fillEnt.isFilled() == fill.isSelected()) return; KeywordIndex kw = InputAgent.formatBoolean("Filled", fill.isSelected()); InputAgent.storeAndExecute(new KeywordCommand((Entity)fillEnt, kw)); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( fill ); } private void addFillColourButton(JToolBar buttonBar, Insets margin) { fillColourIcon = new ColorIcon(16, 16); fillColourIcon.setFillColor(Color.LIGHT_GRAY); fillColourIcon.setOutlineColor(Color.LIGHT_GRAY); fillColour = new JButton(fillColourIcon); fillColour.setMargin(margin); fillColour.setFocusPainted(false); fillColour.setRequestFocusEnabled(false); fillColour.setToolTipText(formatToolTip("Fill Colour", "Sets the colour of the fill.")); fillColour.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof FillEntity)) return; final FillEntity fillEnt = (FillEntity) selectedEntity; final Color4d presentColour = fillEnt.getFillColour(); ArrayList<Color4d> coloursInUse = GUIFrame.getFillColoursInUse(sim); ColourMenu menu = new ColourMenu(presentColour, coloursInUse, true) { @Override public void setColour(String colStr) { KeywordIndex kw = InputAgent.formatInput("FillColour", colStr); InputAgent.storeAndExecute(new KeywordCommand(selectedEntity, kw)); controlStartResume.requestFocusInWindow(); } }; menu.show(fillColour, 0, fillColour.getPreferredSize().height); } }); buttonBar.add( fillColour ); } // ****************************************************************************************************** // TOOL BAR // ****************************************************************************************************** /** * Sets up the Control Panel's main tool bar. */ public void initializeMainToolBars() { // Insets used in setting the tool bar components Insets noMargin = new Insets( 0, 0, 0, 0 ); Insets smallMargin = new Insets( 1, 1, 1, 1 ); // Initialize the main tool bar JToolBar mainToolBar = new JToolBar(); mainToolBar.setMargin( smallMargin ); mainToolBar.setFloatable(false); mainToolBar.setLayout( new FlowLayout( FlowLayout.LEFT, 0, 0 ) ); // Add the main tool bar to the display getContentPane().add( mainToolBar, BorderLayout.SOUTH ); // Run/pause button addRunButton(mainToolBar, noMargin); Dimension separatorDim = new Dimension(11, controlStartResume.getPreferredSize().height); Dimension gapDim = new Dimension(5, separatorDim.height); // Reset button mainToolBar.add(Box.createRigidArea(gapDim)); addResetButton(mainToolBar, noMargin); // Real time button mainToolBar.addSeparator(separatorDim); addRealTimeButton(mainToolBar, smallMargin); // Speed multiplier spinner mainToolBar.add(Box.createRigidArea(gapDim)); addSpeedMultiplier(mainToolBar, noMargin); // Pause time field mainToolBar.addSeparator(separatorDim); mainToolBar.add(new JLabel("Pause Time:")); mainToolBar.add(Box.createRigidArea(gapDim)); addPauseTime(mainToolBar, noMargin); // Simulation time display mainToolBar.addSeparator(separatorDim); addSimulationTime(mainToolBar, noMargin); // Run progress bar mainToolBar.add(Box.createRigidArea(gapDim)); addRunProgress(mainToolBar, noMargin); // Remaining time display mainToolBar.add(Box.createRigidArea(gapDim)); addRemainingTime(mainToolBar, noMargin); // Achieved speed multiplier mainToolBar.addSeparator(separatorDim); mainToolBar.add(new JLabel("Speed:")); addAchievedSpeedMultiplier(mainToolBar, noMargin); // Cursor position mainToolBar.addSeparator(separatorDim); mainToolBar.add(new JLabel("Position:")); addCursorPosition(mainToolBar, noMargin); } private void addRunButton(JToolBar mainToolBar, Insets margin) { runPressedIcon = new ImageIcon(GUIFrame.class.getResource("/resources/images/run-pressed-24.png")); pausePressedIcon = new ImageIcon(GUIFrame.class.getResource("/resources/images/pause-pressed-24.png")); controlStartResume = new RoundToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/run-24.png"))); controlStartResume.setRolloverEnabled(true); controlStartResume.setRolloverIcon(new ImageIcon(GUIFrame.class.getResource("/resources/images/run-rollover-24.png"))); controlStartResume.setPressedIcon(runPressedIcon); controlStartResume.setSelectedIcon( new ImageIcon(GUIFrame.class.getResource("/resources/images/pause-24.png"))); controlStartResume.setRolloverSelectedIcon( new ImageIcon(GUIFrame.class.getResource("/resources/images/pause-rollover-24.png"))); controlStartResume.setToolTipText(RUN_TOOLTIP); controlStartResume.setMargin(margin); controlStartResume.setEnabled( false ); controlStartResume.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { JToggleButton startResume = (JToggleButton)event.getSource(); startResume.setEnabled(false); if(startResume.isSelected()) { boolean bool = GUIFrame.this.startSimulation(); if (bool) { controlStartResume.setPressedIcon(pausePressedIcon); } else { startResume.setSelected(false); startResume.setEnabled(true); } } else { GUIFrame.this.pauseSimulation(); controlStartResume.setPressedIcon(runPressedIcon); } controlStartResume.requestFocusInWindow(); } } ); mainToolBar.add( controlStartResume ); // Listen for keyboard shortcuts for simulation speed controlStartResume.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_PERIOD) { // same as the '>' key if (!spinner.isEnabled()) return; spinner.setValue(spinner.getNextValue()); return; } if (e.getKeyCode() == KeyEvent.VK_COMMA) { // same as the '<' key if (!spinner.isEnabled()) return; spinner.setValue(spinner.getPreviousValue()); return; } } @Override public void keyReleased(KeyEvent e) {} }); } private void addResetButton(JToolBar mainToolBar, Insets margin) { controlStop = new RoundToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/reset-16.png"))); controlStop.setToolTipText(formatToolTip("Reset", "Resets the simulation run time to zero.")); controlStop.setPressedIcon(new ImageIcon(GUIFrame.class.getResource("/resources/images/reset-pressed-16.png"))); controlStop.setRolloverEnabled( true ); controlStop.setRolloverIcon(new ImageIcon(GUIFrame.class.getResource("/resources/images/reset-rollover-16.png"))); controlStop.setMargin(margin); controlStop.setEnabled( false ); controlStop.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (sim.getSimState() == JaamSimModel.SIM_STATE_RUNNING) { GUIFrame.this.pauseSimulation(); } controlStartResume.requestFocusInWindow(); boolean confirmed = GUIFrame.showConfirmStopDialog(); if (!confirmed) return; GUIFrame.this.stopSimulation(); initSpeedUp(0.0d); tickUpdate(0L); } } ); mainToolBar.add( controlStop ); } private void addRealTimeButton(JToolBar mainToolBar, Insets margin) { controlRealTime = new JToggleButton( " Real Time " ); controlRealTime.setToolTipText(formatToolTip("Real Time Mode", "When selected, the simulation runs at a fixed multiple of wall clock time.")); controlRealTime.setMargin(margin); controlRealTime.setFocusPainted(false); controlRealTime.setRequestFocusEnabled(false); controlRealTime.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { boolean bool = ((JToggleButton)event.getSource()).isSelected(); KeywordIndex kw = InputAgent.formatBoolean("RealTime", bool); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); controlStartResume.requestFocusInWindow(); } }); mainToolBar.add( controlRealTime ); } private void addSpeedMultiplier(JToolBar mainToolBar, Insets margin) { SpinnerNumberModel numberModel = new SpinnerModel(Simulation.DEFAULT_REAL_TIME_FACTOR, Simulation.MIN_REAL_TIME_FACTOR, Simulation.MAX_REAL_TIME_FACTOR, 1); spinner = new JSpinner(numberModel); // show up to 6 decimal places JSpinner.NumberEditor numberEditor = new JSpinner.NumberEditor(spinner,"0.######"); spinner.setEditor(numberEditor); // make sure spinner TextField is no wider than 9 digits int diff = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().getPreferredSize().width - getPixelWidthOfString_ForFont("9", spinner.getFont()) * 9; Dimension dim = spinner.getPreferredSize(); dim.width -= diff; spinner.setPreferredSize(dim); spinner.addChangeListener(new ChangeListener() { @Override public void stateChanged( ChangeEvent e ) { Double val = (Double)((JSpinner)e.getSource()).getValue(); if (MathUtils.near(val, sim.getSimulation().getRealTimeFactor())) return; NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); DecimalFormat df = (DecimalFormat)nf; df.applyPattern("0.######"); KeywordIndex kw = InputAgent.formatArgs("RealTimeFactor", df.format(val)); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); controlStartResume.requestFocusInWindow(); } }); spinner.setToolTipText(formatToolTip("Speed Multiplier (&lt and &gt keys)", "Target ratio of simulation time to wall clock time when Real Time mode is selected.")); spinner.setEnabled(false); mainToolBar.add( spinner ); } private void addPauseTime(JToolBar mainToolBar, Insets margin) { pauseTime = new JTextField("0000-00-00T00:00:00") { @Override protected void processFocusEvent(FocusEvent fe) { if (fe.getID() == FocusEvent.FOCUS_LOST) { GUIFrame.this.setPauseTime(this.getText()); } else if (fe.getID() == FocusEvent.FOCUS_GAINED) { pauseTime.selectAll(); } super.processFocusEvent( fe ); } }; pauseTime.setPreferredSize(new Dimension(pauseTime.getPreferredSize().width, pauseTime.getPreferredSize().height)); pauseTime.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { GUIFrame.this.setPauseTime(pauseTime.getText()); controlStartResume.requestFocusInWindow(); } }); pauseTime.setText(""); pauseTime.setHorizontalAlignment(JTextField.RIGHT); pauseTime.setToolTipText(formatToolTip("Pause Time", "Time at which to pause the run, e.g. 3 h, 10 s, etc.")); mainToolBar.add(pauseTime); } private void addSimulationTime(JToolBar mainToolBar, Insets margin) { clockDisplay = new JLabel( "", JLabel.CENTER ); clockDisplay.setPreferredSize( new Dimension( 110, 16 ) ); clockDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); clockDisplay.setToolTipText(formatToolTip("Simulation Time", "The present simulation time")); mainToolBar.add( clockDisplay ); } private void addRunProgress(JToolBar mainToolBar, Insets margin) { progressBar = new JProgressBar( 0, 100 ); progressBar.setPreferredSize( new Dimension( 120, controlRealTime.getPreferredSize().height ) ); progressBar.setValue( 0 ); progressBar.setStringPainted( true ); progressBar.setToolTipText(formatToolTip("Run Progress", "Percent of the present simulation run that has been completed.")); mainToolBar.add( progressBar ); } private void addRemainingTime(JToolBar mainToolBar, Insets margin) { remainingDisplay = new JLabel( "", JLabel.CENTER ); remainingDisplay.setPreferredSize( new Dimension( 110, 16 ) ); remainingDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); remainingDisplay.setToolTipText(formatToolTip("Remaining Time", "The remaining time required to complete the present simulation run.")); mainToolBar.add( remainingDisplay ); } private void addAchievedSpeedMultiplier(JToolBar mainToolBar, Insets margin) { speedUpDisplay = new JLabel( "", JLabel.CENTER ); speedUpDisplay.setPreferredSize( new Dimension( 110, 16 ) ); speedUpDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); speedUpDisplay.setToolTipText(formatToolTip("Achieved Speed Multiplier", "The ratio of elapsed simulation time to elasped wall clock time that was achieved.")); mainToolBar.add( speedUpDisplay ); } private void addCursorPosition(JToolBar mainToolBar, Insets margin) { locatorPos = new JLabel( "", JLabel.CENTER ); locatorPos.setPreferredSize( new Dimension( 140, 16 ) ); locatorPos.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); locatorPos.setToolTipText(formatToolTip("Cursor Position", "The coordinates of the cursor on the x-y plane.")); mainToolBar.add( locatorPos ); } // ****************************************************************************************************** // RUN STATUS UPDATES // ****************************************************************************************************** private long resumeSystemTime; private long lastSystemTime; private double lastSimTime; private double speedUp; public void initSpeedUp(double simTime) { resumeSystemTime = System.currentTimeMillis(); lastSystemTime = resumeSystemTime; lastSimTime = simTime; } /** * Sets the values for the simulation time, run progress, speedup factor, * and remaining run time in the Control Panel's status bar. * * @param simTime - the present simulation time in seconds. */ void setClock(double simTime) { // Set the simulation time display String unit = getJaamSimModel().getDisplayedUnit(TimeUnit.class); double factor = getJaamSimModel().getDisplayedUnitFactor(TimeUnit.class); clockDisplay.setText(String.format("%,.2f %s", simTime/factor, unit)); // Set the run progress bar display long cTime = System.currentTimeMillis(); Simulation simulation = sim.getSimulation(); if (simulation == null) { setProgress(0); return; } double duration = simulation.getRunDuration() + simulation.getInitializationTime(); double timeElapsed = simTime - simulation.getStartTime(); int progress = (int)(timeElapsed * 100.0d / duration); this.setProgress(progress); // Do nothing further if the simulation is not executing events if (sim.getSimState() != JaamSimModel.SIM_STATE_RUNNING) return; // Set the speedup factor display if (cTime - lastSystemTime > 5000L || cTime - resumeSystemTime < 5000L) { long elapsedMillis = cTime - lastSystemTime; double elapsedSimTime = timeElapsed - lastSimTime; // Determine the speed-up factor speedUp = (elapsedSimTime * 1000.0d) / elapsedMillis; setSpeedUp(speedUp); if (elapsedMillis > 5000L) { lastSystemTime = cTime; lastSimTime = timeElapsed; } } // Set the remaining time display setRemaining( (duration - timeElapsed)/speedUp ); } /** * Displays the given value on the Control Panel's progress bar. * * @param val - the percent of the run that has completed. */ public void setProgress( int val ) { if (lastValue == val) return; progressBar.setValue( val ); progressBar.repaint(25); lastValue = val; if (sim.getSimState() >= JaamSimModel.SIM_STATE_CONFIGURED) { setTitle(sim, val); } } /** * Write the given value on the Control Panel's speed up factor box. * * @param val - the speed up factor to write. */ public void setSpeedUp( double val ) { if (val == 0.0) { speedUpDisplay.setText("-"); } else if (val >= 0.99) { speedUpDisplay.setText(String.format("%,.0f", val)); } else { speedUpDisplay.setText(String.format("%,.6f", val)); } } /** * Write the given value on the Control Panel's remaining run time box. * * @param val - the remaining run time in seconds. */ public void setRemaining( double val ) { if (val == 0.0) remainingDisplay.setText("-"); else if (val < 60.0) remainingDisplay.setText(String.format("%.0f seconds left", val)); else if (val < 3600.0) remainingDisplay.setText(String.format("%.1f minutes left", val/60.0)); else if (val < 3600.0*24.0) remainingDisplay.setText(String.format("%.1f hours left", val/3600.0)); else if (val < 3600.0*8760.0) remainingDisplay.setText(String.format("%.1f days left", val/(3600.0*24.0))); else remainingDisplay.setText(String.format("%.1f years left", val/(3600.0*8760.0))); } // ****************************************************************************************************** // SIMULATION CONTROLS // ****************************************************************************************************** /** * Starts or resumes the simulation run. * @return true if the simulation was started or resumed; false if cancel or close was selected */ public boolean startSimulation() { if (sim.getSimState() <= JaamSimModel.SIM_STATE_CONFIGURED) { boolean confirmed = true; if (sim.isSessionEdited()) { confirmed = GUIFrame.showSaveChangesDialog(this); } if (confirmed) { sim.start(); } return confirmed; } else if (sim.getSimState() == JaamSimModel.SIM_STATE_PAUSED) { sim.resume(sim.getSimulation().getPauseTime()); return true; } else throw new ErrorException( "Invalid Simulation State for Start/Resume" ); } /** * Pauses the simulation run. */ private void pauseSimulation() { if (sim.getSimState() == JaamSimModel.SIM_STATE_RUNNING) sim.pause(); else throw new ErrorException( "Invalid Simulation State for pause" ); } /** * Stops the simulation run. */ public void stopSimulation() { if (sim.getSimState() == JaamSimModel.SIM_STATE_RUNNING || sim.getSimState() == JaamSimModel.SIM_STATE_PAUSED || sim.getSimState() == JaamSimModel.SIM_STATE_ENDED) { sim.reset(); FrameBox.stop(); this.updateForSimulationState(JaamSimModel.SIM_STATE_CONFIGURED); } else throw new ErrorException( "Invalid Simulation State for stop" ); } public static void updateForSimState(int state) { GUIFrame inst = GUIFrame.getInstance(); if (inst == null) return; inst.updateForSimulationState(state); } /** * Sets the state of the simulation run to the given state value. * * @param state - an index that designates the state of the simulation run. */ void updateForSimulationState(int state) { sim.setSimState(state); switch (sim.getSimState()) { case JaamSimModel.SIM_STATE_LOADED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { if (fileMenu.getItem(i) == null) continue; fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < toolsMenu.getItemCount(); i++ ) { if (toolsMenu.getItem(i) == null) continue; toolsMenu.getItem(i).setEnabled(true); } speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); setSpeedUp(0); setRemaining(0); setProgress(0); controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText(RUN_TOOLTIP); controlStop.setEnabled( false ); controlStop.setSelected( false ); lockViewXYPlane.setEnabled( true ); progressBar.setEnabled( false ); break; case JaamSimModel.SIM_STATE_UNCONFIGURED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { if (fileMenu.getItem(i) == null) continue; fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < toolsMenu.getItemCount(); i++ ) { if (toolsMenu.getItem(i) == null) continue; toolsMenu.getItem(i).setEnabled(true); } speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); setSpeedUp(0); setRemaining(0); setProgress(0); controlStartResume.setEnabled( false ); controlStartResume.setSelected( false ); controlStop.setSelected( false ); controlStop.setEnabled( false ); lockViewXYPlane.setEnabled( true ); progressBar.setEnabled( false ); break; case JaamSimModel.SIM_STATE_CONFIGURED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { if (fileMenu.getItem(i) == null) continue; fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < toolsMenu.getItemCount(); i++ ) { if (toolsMenu.getItem(i) == null) continue; toolsMenu.getItem(i).setEnabled(true); } speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); setSpeedUp(0); setRemaining(0); setProgress(0); controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText(RUN_TOOLTIP); controlStop.setSelected( false ); controlStop.setEnabled( false ); lockViewXYPlane.setEnabled( true ); progressBar.setEnabled( true ); break; case JaamSimModel.SIM_STATE_RUNNING: speedUpDisplay.setEnabled( true ); remainingDisplay.setEnabled( true ); controlStartResume.setEnabled( true ); controlStartResume.setSelected( true ); controlStartResume.setToolTipText(PAUSE_TOOLTIP); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; case JaamSimModel.SIM_STATE_PAUSED: controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText(RUN_TOOLTIP); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; case JaamSimModel.SIM_STATE_ENDED: controlStartResume.setEnabled( false ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText(RUN_TOOLTIP); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; default: throw new ErrorException( "Unrecognized Graphics State" ); } fileMenu.setEnabled( true ); } @Override public void updateAll() { GUIFrame.updateUI(); } @Override public void updateObjectSelector() { ObjectSelector.allowUpdate(); GUIFrame.updateUI(); } @Override public void updateModelBuilder() { EntityPallet.update(); } private void clearButtons() { if (createLinks.isSelected()) createLinks.doClick(); if (reverseButton.isSelected()) reverseButton.doClick(); } public void updateControls() { Simulation simulation = sim.getSimulation(); if (simulation == null) return; updateControls(simulation); } public void updateControls(Simulation simulation) { updateSaveButton(); updateUndoButtons(); updateForRealTime(simulation.isRealTime(), simulation.getRealTimeFactor()); updateForPauseTime(simulation.getPauseTimeString()); update2dButton(); updateShowAxesButton(); updateShowGridButton(); updateNextPrevButtons(); updateFindButton(); updateFormatButtons(selectedEntity); updateForSnapToGrid(simulation.isSnapToGrid()); updateForSnapGridSpacing(simulation.getSnapGridSpacingString()); updateShowLabelsButton(simulation.isShowLabels()); updateShowSubModelsButton(simulation.isShowSubModels()); updateShowEntityFlowButton(simulation.isShowEntityFlow()); updateToolVisibilities(simulation); updateToolSizes(simulation); updateToolLocations(simulation); updateViewVisibilities(); updateViewSizes(); updateViewLocations(); setControlPanelWidth(simulation.getControlPanelWidth()); } private void updateSaveButton() { fileSave.setEnabled(sim.isSessionEdited()); } /** * updates RealTime button and Spinner */ private synchronized void updateForRealTime(boolean executeRT, double factorRT) { sim.getEventManager().setExecuteRealTime(executeRT, factorRT); controlRealTime.setSelected(executeRT); spinner.setValue(factorRT); spinner.setEnabled(executeRT); } /** * updates PauseTime entry */ private void updateForPauseTime(String str) { if (pauseTime.getText().equals(str) || pauseTime.isFocusOwner()) return; pauseTime.setText(str); } /** * Sets the PauseTime keyword for Simulation. * @param str - value to assign. */ private void setPauseTime(String str) { String prevVal = sim.getSimulation().getPauseTimeString(); if (prevVal.equals(str)) return; // If the time is in RFC8601 format, enclose in single quotes if (str.contains("-") || str.contains(":")) Parser.addQuotesIfNeeded(str); ArrayList<String> tokens = new ArrayList<>(); Parser.tokenize(tokens, str, true); // if we only got one token, and it isn't RFC8601 - add a unit if (tokens.size() == 1 && !tokens.get(0).contains("-") && !tokens.get(0).contains(":")) tokens.add(getJaamSimModel().getDisplayedUnit(TimeUnit.class)); try { // Parse the keyword inputs KeywordIndex kw = new KeywordIndex("PauseTime", tokens, null); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } catch (InputErrorException e) { pauseTime.setText(prevVal); GUIFrame.showErrorDialog("Input Error", e.getMessage()); } } /** * Assigns a new name to the given entity. * @param ent - entity to be renamed * @param newName - new absolute name for the entity */ @Override public void renameEntity(Entity ent, String newName) { // If the name has not changed, do nothing if (ent.getName().equals(newName)) return; // Check that the entity was defined AFTER the RecordEdits command if (!ent.isAdded()) throw new ErrorException("Cannot rename an entity that was defined before the RecordEdits command."); // Get the new local name String localName = newName; if (newName.contains(".")) { String[] names = newName.split("\\."); if (names.length == 0) throw new ErrorException(InputAgent.INP_ERR_BADNAME, localName); localName = names[names.length - 1]; names = Arrays.copyOf(names, names.length - 1); Entity parent = sim.getEntityFromNames(names); if (parent != ent.getParent()) throw new ErrorException("Cannot rename the entity's parent"); } // Check that the new name is valid if (!InputAgent.isValidName(localName)) throw new ErrorException(InputAgent.INP_ERR_BADNAME, localName); // Check that the new name does not conflict with another entity if (sim.getNamedEntity(newName) != null) throw new ErrorException(InputAgent.INP_ERR_DEFINEUSED, newName, sim.getNamedEntity(newName).getClass().getSimpleName()); // Rename the entity InputAgent.storeAndExecute(new RenameCommand(ent, newName)); } @Override public void deleteEntity(Entity ent) { if (ent.isGenerated()) throw new ErrorException("Cannot delete an entity that was generated by a simulation " + "object."); if (!ent.isAdded()) throw new ErrorException("Cannot delete an entity that was defined prior to " + "RecordEdits in the input file."); if (ent instanceof DisplayEntity && !((DisplayEntity) ent).isMovable()) throw new ErrorException("Cannot delete an entity that is not movable."); // Delete any child entities for (Entity child : ent.getChildren()) { if (child.isGenerated() || child instanceof EntityLabel) child.kill(); else deleteEntity(child); } // Region if (ent instanceof Region) { // Reset the Region input for the entities in this region KeywordIndex kw = InputAgent.formatArgs("Region"); for (DisplayEntity e : sim.getClonesOfIterator(DisplayEntity.class)) { if (e == ent || e.getInput("Region").getValue() != ent) continue; InputAgent.storeAndExecute(new CoordinateCommand(e, kw)); } } // DisplayEntity if (ent instanceof DisplayEntity) { DisplayEntity dEnt = (DisplayEntity) ent; // Kill the label EntityLabel label = EntityLabel.getLabel(dEnt); if (label != null) deleteEntity(label); // Reset the RelativeEntity input for entities KeywordIndex kw = InputAgent.formatArgs("RelativeEntity"); for (DisplayEntity e : sim.getClonesOfIterator(DisplayEntity.class)) { if (e == ent || e.getInput("RelativeEntity").getValue() != ent) continue; InputAgent.storeAndExecute(new CoordinateCommand(e, kw)); } } // Delete any references to this entity in the inputs to other entities for (Entity e : sim.getClonesOfIterator(Entity.class)) { if (e == ent) continue; ArrayList<KeywordIndex> oldKwList = new ArrayList<>(); ArrayList<KeywordIndex> newKwList = new ArrayList<>(); for (Input<?> in : e.getEditableInputs()) { ArrayList<String> oldTokens = in.getValueTokens(); boolean changed = in.removeReferences(ent); if (!changed) continue; KeywordIndex oldKw = new KeywordIndex(in.getKeyword(), oldTokens, null); KeywordIndex newKw = new KeywordIndex(in.getKeyword(), in.getValueTokens(), null); oldKwList.add(oldKw); newKwList.add(newKw); } // Reload any inputs that have changed so that redo/undo works correctly if (newKwList.isEmpty()) continue; KeywordIndex[] oldKws = new KeywordIndex[oldKwList.size()]; KeywordIndex[] newKws = new KeywordIndex[newKwList.size()]; oldKws = oldKwList.toArray(oldKws); newKws = newKwList.toArray(newKws); InputAgent.storeAndExecute(new KeywordCommand(e, 0, oldKws, newKws)); } // Execute the delete command InputAgent.storeAndExecute(new DeleteCommand(ent)); } @Override public void storeAndExecute(Command cmd) { synchronized (undoList) { if (!cmd.isChange()) return; // Execute the command and catch an error if it occurs cmd.execute(); // Attempt to merge the command with the previous one Command mergedCmd = null; if (!undoList.isEmpty()) { Command lastCmd = undoList.get(undoList.size() - 1); mergedCmd = lastCmd.tryMerge(cmd); } // If the new command can be combined, then change the entry for previous command if (mergedCmd != null) { if (mergedCmd.isChange()) undoList.set(undoList.size() - 1, mergedCmd); else undoList.remove(undoList.size() - 1); } // If the new command cannot be combined, then add it to the undo list else { undoList.add(cmd); } // Clear the re-do list redoList.clear(); } updateUI(); } public void undo() { synchronized (undoList) { if (undoList.isEmpty()) return; Command cmd = undoList.remove(undoList.size() - 1); redoList.add(cmd); cmd.undo(); } updateUI(); } public void redo() { synchronized (undoList) { if (redoList.isEmpty()) return; Command cmd = redoList.remove(redoList.size() - 1); undoList.add(cmd); cmd.execute(); } updateUI(); } public void undo(int n) { synchronized (undoList) { for (int i = 0; i < n; i++) { undo(); } } } public void redo(int n) { synchronized (undoList) { for (int i = 0; i < n; i++) { redo(); } } } public void invokeUndo() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { undo(); } }); } public void invokeRedo() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { redo(); } }); } public void updateUndoButtons() { synchronized (undoList) { undo.setEnabled(!undoList.isEmpty()); undoDropdown.setEnabled(!undoList.isEmpty()); undoMenuItem.setEnabled(!undoList.isEmpty()); redo.setEnabled(!redoList.isEmpty()); redoDropdown.setEnabled(!redoList.isEmpty()); redoMenuItem.setEnabled(!redoList.isEmpty()); } } public void clearUndoRedo() { synchronized (undoList) { undoList.clear(); redoList.clear(); } updateUI(); } private void updateForSnapGridSpacing(String str) { if (gridSpacing.getText().equals(str) || gridSpacing.hasFocus()) return; gridSpacing.setText(str); } private void setSnapGridSpacing(String str) { Input<?> in = sim.getSimulation().getInput("SnapGridSpacing"); String prevVal = in.getValueString(); if (prevVal.equals(str)) return; if (str.isEmpty()) { gridSpacing.setText(prevVal); return; } try { KeywordIndex kw = InputAgent.formatInput("SnapGridSpacing", str); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } catch (InputErrorException e) { gridSpacing.setText(prevVal); GUIFrame.showErrorDialog("Input Error", e.getMessage()); } } private void updateForSnapToGrid(boolean bool) { snapToGrid.setSelected(bool); gridSpacing.setEnabled(bool); } private void update2dButton() { if (!RenderManager.isGood()) return; View view = RenderManager.inst().getActiveView(); if (view == null) return; lockViewXYPlane.setSelected(view.is2DLocked()); } private void updateShowAxesButton() { DisplayEntity ent = (DisplayEntity) sim.getNamedEntity("XYZ-Axis"); xyzAxis.setSelected(ent != null && ent.getShow()); } private void updateShowGridButton() { DisplayEntity ent = (DisplayEntity) sim.getNamedEntity("XY-Grid"); grid.setSelected(ent != null && ent.getShow()); } private void updateNextPrevButtons() { if (selectedEntity != null && selectedEntity instanceof DisplayEntity) { boolean dir = !reverseButton.isSelected(); DisplayEntity selectedDEnt = (DisplayEntity) selectedEntity; prevButton.setEnabled(!selectedDEnt.getPreviousList(dir).isEmpty()); nextButton.setEnabled(!selectedDEnt.getNextList(dir).isEmpty()); return; } prevButton.setEnabled(false); nextButton.setEnabled(false); } private void updateFindButton() { boolean bool = FindBox.getInstance().isVisible(); find.setSelected(bool); } public static void setSelectedEntity(Entity ent) { if (instance == null) return; instance.setSelectedEnt(ent); } public void setSelectedEnt(Entity ent) { selectedEntity = ent; } private void updateFormatButtons(Entity ent) { updateEditButtons(ent); updateDisplayModelButtons(ent); updateClearFormattingButton(ent); updateTextButtons(ent); updateZButtons(ent); updateLineButtons(ent); updateFillButtons(ent); } private void updateEditButtons(Entity ent) { boolean bool = (ent != null && ent != sim.getSimulation()); copyButton.setEnabled(bool); copyMenuItem.setEnabled(bool); deleteMenuItem.setEnabled(bool); } public void updateDisplayModelButtons(Entity ent) { boolean bool = ent instanceof DisplayEntity && ((DisplayEntity)ent).isDisplayModelNominal() && ((DisplayEntity)ent).getDisplayModelList().size() == 1; dispModel.setEnabled(bool); modelSelector.setEnabled(bool); editDmButton.setEnabled(bool); if (!bool) { dispModel.setText(""); return; } DisplayEntity dispEnt = (DisplayEntity) ent; String name = dispEnt.getDisplayModelList().get(0).getName(); if (!dispModel.getText().equals(name)) dispModel.setText(name); } public void updateClearFormattingButton(Entity ent) { if (ent == null) { clearButton.setEnabled(false); return; } boolean bool = false; for (Input<?> in : ent.getEditableInputs()) { String cat = in.getCategory(); if (!cat.equals(Entity.FORMAT) && !cat.equals(Entity.FONT)) continue; if (!in.isDefault()) { bool = true; break; } } clearButton.setEnabled(bool); } private void updateTextButtons(Entity ent) { boolean bool = ent instanceof TextEntity; boolean isAlignable = bool && ent instanceof DisplayEntity && !(ent instanceof OverlayText) && !(ent instanceof BillboardText); alignLeft.setEnabled(isAlignable); alignCentre.setEnabled(isAlignable); alignRight.setEnabled(isAlignable); if (!isAlignable) { alignmentGroup.clearSelection(); } bold.setEnabled(bool); italic.setEnabled(bool); font.setEnabled(bool); fontSelector.setEnabled(bool); textHeight.setEnabled(bool); largerText.setEnabled(bool); smallerText.setEnabled(bool); fontColour.setEnabled(bool); if (!bool) { font.setText(""); textHeight.setText(null); bold.setSelected(false); italic.setSelected(false); colourIcon.setFillColor(Color.LIGHT_GRAY); colourIcon.setOutlineColor(Color.LIGHT_GRAY); return; } if (isAlignable) { int val = (int) Math.signum(((DisplayEntity) ent).getAlignment().x); alignLeft.setSelected(val == -1); alignCentre.setSelected(val == 0); alignRight.setSelected(val == 1); } TextEntity textEnt = (TextEntity) ent; bold.setSelected(textEnt.isBold()); italic.setSelected(textEnt.isItalic()); String fontName = textEnt.getFontName(); if (!font.getText().equals(fontName)) font.setText(fontName); updateTextHeight(textEnt.getTextHeightString()); Color4d col = textEnt.getFontColor(); colourIcon.setFillColor(new Color((float)col.r, (float)col.g, (float)col.b, (float)col.a)); colourIcon.setOutlineColor(Color.DARK_GRAY); fontColour.repaint(); } private void updateTextHeight(String str) { if (textHeight.getText().equals(str) || textHeight.hasFocus()) return; textHeight.setText(str); } private void updateZButtons(Entity ent) { boolean bool = ent instanceof DisplayEntity; bool = bool && !(ent instanceof OverlayEntity); bool = bool && !(ent instanceof BillboardText); increaseZ.setEnabled(bool); decreaseZ.setEnabled(bool); } private void updateLineButtons(Entity ent) { boolean bool = ent instanceof LineEntity; outline.setEnabled(bool && ent instanceof FillEntity); lineWidth.setEnabled(bool); lineColour.setEnabled(bool); if (!bool) { lineWidth.setValue(1); lineColourIcon.setFillColor(Color.LIGHT_GRAY); lineColourIcon.setOutlineColor(Color.LIGHT_GRAY); return; } LineEntity lineEnt = (LineEntity) ent; outline.setSelected(lineEnt.isOutlined()); lineWidth.setEnabled(lineEnt.isOutlined()); lineColour.setEnabled(lineEnt.isOutlined()); lineWidth.setValue(Integer.valueOf(lineEnt.getLineWidth())); Color4d col = lineEnt.getLineColour(); lineColourIcon.setFillColor(new Color((float)col.r, (float)col.g, (float)col.b, (float)col.a)); lineColourIcon.setOutlineColor(Color.DARK_GRAY); lineColour.repaint(); } private void updateFillButtons(Entity ent) { boolean bool = ent instanceof FillEntity; fill.setEnabled(bool); fillColour.setEnabled(bool); if (!bool) { fillColourIcon.setFillColor(Color.LIGHT_GRAY); fillColourIcon.setOutlineColor(Color.LIGHT_GRAY); return; } FillEntity fillEnt = (FillEntity) ent; fill.setSelected(fillEnt.isFilled()); fillColour.setEnabled(fillEnt.isFilled()); Color4d col = fillEnt.getFillColour(); fillColourIcon.setFillColor(new Color((float)col.r, (float)col.g, (float)col.b, (float)col.a)); fillColourIcon.setOutlineColor(Color.DARK_GRAY); fillColour.repaint(); } private void setTextHeight(String str) { if (!(selectedEntity instanceof TextEntity)) return; TextEntity textEnt = (TextEntity) selectedEntity; if (str.equals(textEnt.getTextHeightString())) return; try { KeywordIndex kw = InputAgent.formatInput("TextHeight", str); InputAgent.storeAndExecute(new KeywordCommand((Entity)textEnt, kw)); } catch (InputErrorException e) { textHeight.setText(textEnt.getTextHeightString()); GUIFrame.showErrorDialog("Input Error", e.getMessage()); } } public static ArrayList<Image> getWindowIcons() { return iconImages; } public void copyLocationToClipBoard(Vec3d pos) { String data = String.format("(%.3f, %.3f, %.3f)", pos.x, pos.y, pos.z); StringSelection stringSelection = new StringSelection(data); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents( stringSelection, null ); } public static void showLocatorPosition(Vec3d pos) { GUIFrame inst = GUIFrame.getInstance(); if (inst == null) return; inst.showLocator(pos); } private void showLocator(Vec3d pos) { if( pos == null ) { locatorPos.setText( "-" ); return; } String unit = getJaamSimModel().getDisplayedUnit(DistanceUnit.class); double factor = getJaamSimModel().getDisplayedUnitFactor(DistanceUnit.class); locatorPos.setText(String.format((Locale)null, "%.3f %.3f %.3f %s", pos.x/factor, pos.y/factor, pos.z/factor, unit)); } public void enableSave(boolean bool) { saveConfigurationMenuItem.setEnabled(bool); } /** * Sets variables used to determine the position and size of various * windows based on the size of the computer display being used. */ private void calcWindowDefaults() { Dimension guiSize = this.getSize(); Rectangle winSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); DEFAULT_GUI_WIDTH = winSize.width; COL1_WIDTH = 220; COL4_WIDTH = 520; int middleWidth = DEFAULT_GUI_WIDTH - COL1_WIDTH - COL4_WIDTH; COL2_WIDTH = Math.max(520, middleWidth / 2); COL3_WIDTH = Math.max(420, middleWidth - COL2_WIDTH); VIEW_WIDTH = DEFAULT_GUI_WIDTH - COL1_WIDTH; COL1_START = this.getX(); COL2_START = COL1_START + COL1_WIDTH; COL3_START = COL2_START + COL2_WIDTH; COL4_START = Math.min(COL3_START + COL3_WIDTH, winSize.width - COL4_WIDTH); HALF_TOP = (winSize.height - guiSize.height) / 2; HALF_BOTTOM = (winSize.height - guiSize.height - HALF_TOP); LOWER_HEIGHT = Math.min(250, (winSize.height - guiSize.height) / 3); VIEW_HEIGHT = winSize.height - guiSize.height - LOWER_HEIGHT; TOP_START = this.getY() + guiSize.height; BOTTOM_START = TOP_START + HALF_TOP; LOWER_START = TOP_START + VIEW_HEIGHT; } public void setShowLabels(boolean bool) { for (DisplayEntity ent : sim.getClonesOfIterator(DisplayEntity.class)) { if (!EntityLabel.canLabel(ent)) continue; EntityLabel.showTemporaryLabel(ent, bool); } } public void setShowSubModels(boolean bool) { for (CompoundEntity submodel : sim.getClonesOfIterator(CompoundEntity.class)) { submodel.showTemporaryComponents(bool); } } public void setShowEntityFlow(boolean bool) { if (!RenderManager.isGood()) return; RenderManager.inst().setShowLinks(bool); } private void updateShowLabelsButton(boolean bool) { if (showLabels.isSelected() == bool) return; showLabels.setSelected(bool); setShowLabels(bool); updateUI(); } private void updateShowSubModelsButton(boolean bool) { if (showSubModels.isSelected() == bool) return; showSubModels.setSelected(bool); setShowSubModels(bool); updateUI(); } private void updateShowEntityFlowButton(boolean bool) { if (showLinks.isSelected() == bool) return; showLinks.setSelected(bool); setShowEntityFlow(bool); updateUI(); } /** * Re-open any Tools windows that have been closed temporarily. */ public void showActiveTools(Simulation simulation) { EntityPallet.getInstance().setVisible(simulation.isModelBuilderVisible()); ObjectSelector.getInstance().setVisible(simulation.isObjectSelectorVisible()); EditBox.getInstance().setVisible(simulation.isInputEditorVisible()); OutputBox.getInstance().setVisible(simulation.isOutputViewerVisible()); PropertyBox.getInstance().setVisible(simulation.isPropertyViewerVisible()); LogBox.getInstance().setVisible(simulation.isLogViewerVisible()); if (!simulation.isEventViewerVisible()) { if (EventViewer.hasInstance()) EventViewer.getInstance().dispose(); return; } EventViewer.getInstance().setVisible(true); } /** * Closes all the Tools windows temporarily. */ public void closeAllTools() { EntityPallet.getInstance().setVisible(false); ObjectSelector.getInstance().setVisible(false); EditBox.getInstance().setVisible(false); OutputBox.getInstance().setVisible(false); PropertyBox.getInstance().setVisible(false); LogBox.getInstance().setVisible(false); if (EventViewer.hasInstance()) EventViewer.getInstance().setVisible(false); } public boolean isIconified() { return getExtendedState() == Frame.ICONIFIED; } private void updateToolVisibilities(Simulation simulation) { boolean iconified = isIconified(); setFrameVisibility(EntityPallet.getInstance(), !iconified && simulation.isModelBuilderVisible()); setFrameVisibility(ObjectSelector.getInstance(), !iconified && simulation.isObjectSelectorVisible()); setFrameVisibility(EditBox.getInstance(), !iconified && simulation.isInputEditorVisible()); setFrameVisibility(OutputBox.getInstance(), !iconified && simulation.isOutputViewerVisible()); setFrameVisibility(PropertyBox.getInstance(), !iconified && simulation.isPropertyViewerVisible()); setFrameVisibility(LogBox.getInstance(), !iconified && simulation.isLogViewerVisible()); if (!simulation.isEventViewerVisible()) { if (EventViewer.hasInstance()) EventViewer.getInstance().dispose(); return; } setFrameVisibility(EventViewer.getInstance(), !iconified); } private void setFrameVisibility(JFrame frame, boolean bool) { if (frame.isVisible() == bool) return; frame.setVisible(bool); if (bool) frame.toFront(); } public void updateToolSizes(Simulation simulation) { EntityPallet.getInstance().setSize(simulation.getModelBuilderSize().get(0), simulation.getModelBuilderSize().get(1)); ObjectSelector.getInstance().setSize(simulation.getObjectSelectorSize().get(0), simulation.getObjectSelectorSize().get(1)); EditBox.getInstance().setSize(simulation.getInputEditorSize().get(0), simulation.getInputEditorSize().get(1)); OutputBox.getInstance().setSize(simulation.getOutputViewerSize().get(0), simulation.getOutputViewerSize().get(1)); PropertyBox.getInstance().setSize(simulation.getPropertyViewerSize().get(0), simulation.getPropertyViewerSize().get(1)); LogBox.getInstance().setSize(simulation.getLogViewerSize().get(0), simulation.getLogViewerSize().get(1)); if (EventViewer.hasInstance()) { EventViewer.getInstance().setSize(simulation.getEventViewerSize().get(0), simulation.getEventViewerSize().get(1)); } } public void updateToolLocations(Simulation simulation) { setToolLocation(EntityPallet.getInstance(), simulation.getModelBuilderPos().get(0), simulation.getModelBuilderPos().get(1)); setToolLocation(ObjectSelector.getInstance(), simulation.getObjectSelectorPos().get(0), simulation.getObjectSelectorPos().get(1)); setToolLocation(EditBox.getInstance(), simulation.getInputEditorPos().get(0), simulation.getInputEditorPos().get(1)); setToolLocation(OutputBox.getInstance(), simulation.getOutputViewerPos().get(0), simulation.getOutputViewerPos().get(1)); setToolLocation(PropertyBox.getInstance(), simulation.getPropertyViewerPos().get(0), simulation.getPropertyViewerPos().get(1)); setToolLocation(LogBox.getInstance(), simulation.getLogViewerPos().get(0), simulation.getLogViewerPos().get(1)); if (EventViewer.hasInstance()) { setToolLocation(EventViewer.getInstance(), simulation.getEventViewerPos().get(0), simulation.getEventViewerPos().get(1)); } } public void setToolLocation(JFrame tool, int x, int y) { Point pt = getGlobalLocation(x, y); tool.setLocation(pt); } private void updateViewVisibilities() { if (!RenderManager.isGood()) return; boolean iconified = isIconified(); for (View v : views) { boolean isVisible = RenderManager.inst().isVisible(v); if (!iconified && v.showWindow()) { if (!isVisible) { RenderManager.inst().createWindow(v); } } else { if (isVisible) { RenderManager.inst().closeWindow(v); } } } } private void updateViewSizes() { for (View v : views) { final Frame window = RenderManager.getOpenWindowForView(v); if (window == null) continue; IntegerVector size = getWindowSize(v); window.setSize(size.get(0), size.get(1)); } } public void updateViewLocations() { for (View v : views) { final Frame window = RenderManager.getOpenWindowForView(v); if (window == null) continue; IntegerVector pos = getWindowPos(v); window.setLocation(pos.get(0), pos.get(1)); } } public void setControlPanelWidth(int width) { int height = getSize().height; setSize(width, height); } public void setWindowDefaults(Simulation simulation) { // Set the defaults from the AWT thread to avoid synchronization problems with updateUI and // the SizePosAdapter for the tool windows SwingUtilities.invokeLater(new Runnable() { @Override public void run() { simulation.setModelBuilderDefaults( COL1_START, TOP_START, COL1_WIDTH, HALF_TOP ); simulation.setObjectSelectorDefaults( COL1_START, BOTTOM_START, COL1_WIDTH, HALF_BOTTOM ); simulation.setInputEditorDefaults( COL2_START, LOWER_START, COL2_WIDTH, LOWER_HEIGHT); simulation.setOutputViewerDefaults( COL3_START, LOWER_START, COL3_WIDTH, LOWER_HEIGHT); simulation.setPropertyViewerDefaults( COL4_START, LOWER_START, COL4_WIDTH, LOWER_HEIGHT); simulation.setLogViewerDefaults( COL4_START, LOWER_START, COL4_WIDTH, LOWER_HEIGHT); simulation.setEventViewerDefaults( COL4_START, LOWER_START, COL4_WIDTH, LOWER_HEIGHT); simulation.setControlPanelWidthDefault(DEFAULT_GUI_WIDTH); View.setDefaultPosition(COL2_START, TOP_START); View.setDefaultSize(VIEW_WIDTH, VIEW_HEIGHT); updateControls(simulation); clearUndoRedo(); } }); } public ArrayList<View> getViews() { synchronized (views) { return views; } } @Override public void addView(View v) { synchronized (views) { views.add(v); } } @Override public void removeView(View v) { synchronized (views) { views.remove(v); } } @Override public void createWindow(View v) { if (!RenderManager.isGood()) return; RenderManager.inst().createWindow(v); } @Override public void closeWindow(View v) { if (!RenderManager.isGood()) return; RenderManager.inst().closeWindow(v); } @Override public int getNextViewID() { nextViewID++; return nextViewID; } private void resetViews() { synchronized (views) { views.clear(); for (View v : getJaamSimModel().getClonesOfIterator(View.class)) { views.add(v); } } } public IntegerVector getWindowPos(View v) { Point fix = OSFix.getLocationAdustment(); //FIXME IntegerVector ret = new IntegerVector(v.getWindowPos()); Point pt = getGlobalLocation(ret.get(0), ret.get(1)); ret.set(0, pt.x + fix.x); ret.set(1, pt.y + fix.y); return ret; } public IntegerVector getWindowSize(View v) { Point fix = OSFix.getSizeAdustment(); //FIXME IntegerVector ret = new IntegerVector(v.getWindowSize()); ret.addAt(fix.x, 0); ret.addAt(fix.y, 1); return ret; } public void setWindowPos(View v, int x, int y, int width, int height) { Point posFix = OSFix.getLocationAdustment(); Point sizeFix = OSFix.getSizeAdustment(); Point pt = getRelativeLocation(x - posFix.x, y - posFix.y); v.setWindowPos(pt.x, pt.y, width - sizeFix.x, height - sizeFix.y); } @Override public Vec3d getPOI(View v) { if (!RenderManager.isGood()) return new Vec3d(); return RenderManager.inst().getPOI(v); } // ****************************************************************************************************** // MAIN // ****************************************************************************************************** public static void main( String args[] ) { // Process the input arguments and filter out directives ArrayList<String> configFiles = new ArrayList<>(args.length); boolean batch = false; boolean minimize = false; boolean quiet = false; boolean scriptMode = false; boolean headless = false; for (String each : args) { // Batch mode if (each.equalsIgnoreCase("-b") || each.equalsIgnoreCase("-batch")) { batch = true; continue; } // Script mode (command line I/O) if (each.equalsIgnoreCase("-s") || each.equalsIgnoreCase("-script")) { scriptMode = true; continue; } // z-buffer offset if (each.equalsIgnoreCase("-z") || each.equalsIgnoreCase("-zbuffer")) { // Parse the option, but do nothing continue; } // Minimize model window if (each.equalsIgnoreCase("-m") || each.equalsIgnoreCase("-minimize")) { minimize = true; continue; } // Minimize model window if (each.equalsIgnoreCase("-h") || each.equalsIgnoreCase("-headless")) { headless = true; batch = true; continue; } // Do not open default windows if (each.equalsIgnoreCase("-q") || each.equalsIgnoreCase("-quiet")) { quiet = true; continue; } if (each.equalsIgnoreCase("-sg") || each.equalsIgnoreCase("-safe_graphics")) { SAFE_GRAPHICS = true; continue; } // Not a program directive, add to list of config files configFiles.add(each); } // If not running in batch mode, create the splash screen JWindow splashScreen = null; if (!batch) { URL splashImage = GUIFrame.class.getResource("/resources/images/splashscreen.png"); ImageIcon imageIcon = new ImageIcon(splashImage); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int splashX = (screen.width - imageIcon.getIconWidth()) / 2; int splashY = (screen.height - imageIcon.getIconHeight()) / 2; // Set the window's bounds, centering the window splashScreen = new JWindow(); splashScreen.setAlwaysOnTop(true); splashScreen.setBounds(splashX, splashY, imageIcon.getIconWidth(), imageIcon.getIconHeight()); // Build the splash screen splashScreen.getContentPane().add(new JLabel(imageIcon)); // Display it splashScreen.setVisible(true); } // create a graphic simulation LogBox.logLine("Loading Simulation Environment ... "); JaamSimModel simModel = getNextJaamSimModel(); simModel.autoLoad(); Simulation simulation = simModel.getSimulation(); GUIFrame gui = null; if (!headless) { gui = GUIFrame.createInstance(); } setJaamSimModel(simModel); if (!headless) { if (minimize) gui.setExtendedState(JFrame.ICONIFIED); // This is only here to initialize the static cache in the MRG1999a class to avoid future latency // when initializing other objects in drag+drop @SuppressWarnings("unused") MRG1999a cacher = new MRG1999a(); } if (!batch && !headless) { // Begin initializing the rendering system RenderManager.initialize(SAFE_GRAPHICS); } LogBox.logLine("Simulation Environment Loaded"); sim.setBatchRun(batch); sim.setScriptMode(scriptMode); // Show the Control Panel if (gui != null) { gui.setVisible(true); gui.calcWindowDefaults(); gui.setLocation(gui.getX(), gui.getY()); //FIXME remove when setLocation is fixed for Windows 10 gui.setWindowDefaults(simulation); } // Resolve all input arguments against the current working directory File user = new File(System.getProperty("user.dir")); // Process any configuration files passed on command line // (Multiple configuration files are not supported at present) for (int i = 0; i < configFiles.size(); i++) { //InputAgent.configure(gui, new File(configFiles.get(i))); File abs = new File((File)null, configFiles.get(i)); File loadFile; if (abs.exists()) loadFile = abs.getAbsoluteFile(); else loadFile = new File(user, configFiles.get(i)); Throwable t = GUIFrame.configure(loadFile); if (t != null) { // Hide the splash screen if (splashScreen != null) { splashScreen.dispose(); splashScreen = null; } handleConfigError(t, loadFile); } } // If in script mode, load a configuration file from standard in if (scriptMode) { BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); InputAgent.readBufferedStream(sim, buf, null, ""); } // If no configuration files were specified on the command line, then load the default configuration file if (configFiles.size() == 0 && !scriptMode) { // Load the default model from the AWT thread to avoid synchronization problems with updateUI and // setWindowDefaults SwingUtilities.invokeLater(new Runnable() { @Override public void run() { sim.setRecordEdits(true); InputAgent.loadDefault(sim); GUIFrame.updateForSimState(JaamSimModel.SIM_STATE_CONFIGURED); } }); } // If in batch or quiet mode, close the any tools that were opened if (quiet || batch) { if (gui != null) gui.closeAllTools(); } // Set RecordEdits mode (if it has not already been set in the configuration file) sim.setRecordEdits(true); // Start the model if in batch mode if (batch) { if (sim.getNumErrors() > 0) GUIFrame.shutdown(0); sim.start(); return; } // Hide the splash screen if (splashScreen != null) { splashScreen.dispose(); splashScreen = null; } // Bring the Control Panel to the front (along with any open Tools) if (gui != null) gui.toFront(); // Set the selected entity to the Simulation object FrameBox.setSelectedEntity(simulation, false); } /* * this class is created so the next value will be value * 2 and the * previous value will be value / 2 */ public static class SpinnerModel extends SpinnerNumberModel { private double value; public SpinnerModel( double val, double min, double max, double stepSize) { super(val, min, max, stepSize); } @Override public Object getPreviousValue() { value = this.getNumber().doubleValue() / 2.0; if (value >= 1.0) value = Math.floor(value); // Avoid going beyond limit Double min = (Double)this.getMinimum(); if (min.doubleValue() > value) { return min; } return value; } @Override public Object getNextValue() { value = this.getNumber().doubleValue() * 2.0; if (value >= 1.0) value = Math.floor(value); // Avoid going beyond limit Double max = (Double)this.getMaximum(); if (max.doubleValue() < value) { return max; } return value; } } public static boolean getShuttingDownFlag() { return shuttingDown.get(); } public static void shutdown(int errorCode) { shuttingDown.set(true); if (RenderManager.isGood()) { RenderManager.inst().shutdown(); } System.exit(errorCode); } @Override public void exit(int errorCode) { shutdown(errorCode); } volatile long simTicks; private static class UIUpdater implements Runnable { private final GUIFrame frame; UIUpdater(GUIFrame gui) { frame = gui; } @Override public void run() { EventManager evt = GUIFrame.getJaamSimModel().getEventManager(); double callBackTime = evt.ticksToSeconds(frame.simTicks); frame.setClock(callBackTime); frame.updateControls(); FrameBox.updateEntityValues(callBackTime); } } @Override public void tickUpdate(long tick) { if (tick == simTicks) return; simTicks = tick; RenderManager.updateTime(tick); GUIFrame.updateUI(); } @Override public void timeRunning() { EventManager evt = EventManager.current(); long tick = evt.getTicks(); boolean running = evt.isRunning(); if (running) { initSpeedUp(evt.ticksToSeconds(tick)); updateForSimulationState(JaamSimModel.SIM_STATE_RUNNING); } else { int state = JaamSimModel.SIM_STATE_PAUSED; if (!sim.getSimulation().canResume(simTicks)) state = JaamSimModel.SIM_STATE_ENDED; updateForSimulationState(state); } } @Override public void handleInputError(Throwable t, Entity ent) { InputAgent.logMessage(sim, "Validation Error - %s: %s", ent.getName(), t.getMessage()); GUIFrame.showErrorDialog("Input Error", "JaamSim has detected the following input error during validation:", String.format("%s: %-70s", ent.getName(), t.getMessage()), "The error must be corrected before the simulation can be started."); GUIFrame.updateForSimState(JaamSimModel.SIM_STATE_CONFIGURED); } @Override public void handleError(Throwable t) { if (t instanceof OutOfMemoryError) { OutOfMemoryError e = (OutOfMemoryError)t; InputAgent.logMessage(sim, "Out of Memory use the -Xmx flag during execution for more memory"); InputAgent.logMessage(sim, "Further debug information:"); InputAgent.logMessage(sim, "%s", e.getMessage()); InputAgent.logStackTrace(sim, t); GUIFrame.shutdown(1); return; } else { EventManager evt = EventManager.current(); long currentTick = evt.getTicks(); double curSec = evt.ticksToSeconds(currentTick); InputAgent.logMessage(sim, "EXCEPTION AT TIME: %f s", curSec); InputAgent.logMessage(sim, "%s", t.getMessage()); if (t.getCause() != null) { InputAgent.logMessage(sim, "Call Stack of original exception:"); InputAgent.logStackTrace(sim, t.getCause()); } InputAgent.logMessage(sim, "Thrown exception call stack:"); InputAgent.logStackTrace(sim, t); } String msg = t.getMessage(); if (msg == null) msg = "null"; String source = ""; int pos = -1; if (t instanceof InputErrorException) { source = ((InputErrorException) t).source; pos = ((InputErrorException) t).position; } if (t instanceof ErrorException) { source = ((ErrorException) t).source; pos = ((ErrorException) t).position; } GUIFrame.showErrorDialog("Runtime Error", source, pos, "JaamSim has detected the following runtime error condition:", msg, "Programmers can find more information by opening the Log Viewer.\n" + "The simulation run must be reset to zero simulation time before it " + "can be restarted."); } void newModel() { // Create the new JaamSimModel and load the default objects and inputs JaamSimModel simModel = getNextJaamSimModel(); simModel.autoLoad(); setWindowDefaults(simModel.getSimulation()); // Set the Control Panel to the new JaamSimModel and reset the user interface setJaamSimModel(simModel); clear(); // Load the default model sim.setRecordEdits(true); InputAgent.loadDefault(sim); FrameBox.setSelectedEntity(sim.getSimulation(), false); } void load() { LogBox.logLine("Loading..."); // Create a file chooser final JFileChooser chooser = new JFileChooser(getConfigFolder()); // Set the file extension filters chooser.setAcceptAllFileFilterUsed(true); FileNameExtensionFilter cfgFilter = new FileNameExtensionFilter("JaamSim Configuration File (*.cfg)", "CFG"); chooser.addChoosableFileFilter(cfgFilter); chooser.setFileFilter(cfgFilter); // Show the file chooser and wait for selection int returnVal = chooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File chosenfile = chooser.getSelectedFile(); // Delete the present JaamSimModel if it is unedited and unsaved if (sim.getConfigFile() == null && !sim.isSessionEdited()) simList.remove(sim); // Create the new JaamSimModel and load the default objects and inputs JaamSimModel simModel = new JaamSimModel(chosenfile.getName()); simModel.autoLoad(); setWindowDefaults(simModel.getSimulation()); // Set the Control Panel to the new JaamSimModel and reset the user interface setJaamSimModel(simModel); clear(); // Load the selected input file SwingUtilities.invokeLater(new Runnable() { @Override public void run() { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); sim.setRecordEdits(false); Throwable ret = GUIFrame.configure(chosenfile); if (ret != null) { setCursor(Cursor.getDefaultCursor()); handleConfigError(ret, chosenfile); } sim.setRecordEdits(true); resetViews(); FrameBox.setSelectedEntity(sim.getSimulation(), false); setCursor(Cursor.getDefaultCursor()); } }); setConfigFolder(chosenfile.getParent()); } } static Throwable configure(File file) { GUIFrame.updateForSimState(JaamSimModel.SIM_STATE_UNCONFIGURED); Throwable ret = null; try { sim.configure(file); } catch (Throwable t) { ret = t; } if (ret == null) LogBox.logLine("Configuration File Loaded"); else LogBox.logLine("Configuration File Loaded - errors found"); // show the present state in the user interface GUIFrame gui = GUIFrame.getInstance(); if (gui != null) { gui.setProgress(0); gui.setTitle(sim); gui.updateForSimulationState(JaamSimModel.SIM_STATE_CONFIGURED); gui.enableSave(sim.isRecordEditsFound()); } return ret; } static void handleConfigError(Throwable t, File file) { if (t instanceof InputErrorException) { InputAgent.logMessage(sim, "Input Error: %s", t.getMessage()); GUIFrame.showErrorOptionDialog("Input Error", String.format("Input errors were detected while loading file: '%s'\n\n" + "%s\n\n" + "Open '%s' with Log Viewer?", file.getName(), t.getMessage(), sim.getRunName() + ".log")); return; } InputAgent.logMessage(sim, "Fatal Error while loading file '%s': %s\n", file.getName(), t.getMessage()); GUIFrame.showErrorDialog("Fatal Error", String.format("A fatal error has occured while loading the file '%s':", file.getName()), t.getMessage(), ""); } /** * Saves the configuration file. * @param file = file to be saved */ private void setSaveFile(File file) { try { sim.save(file); // Set the title bar to match the new run name setTitle(sim); } catch (Exception e) { GUIFrame.showErrorDialog("File Error", e.getMessage()); } } boolean save() { LogBox.logLine("Saving..."); if( sim.getConfigFile() != null ) { setSaveFile(sim.getConfigFile()); updateUI(); return true; } boolean confirmed = saveAs(); return confirmed; } boolean saveAs() { LogBox.logLine("Save As..."); // Create a file chooser final JFileChooser chooser = new JFileChooser(getConfigFolder()); // Set the file extension filters chooser.setAcceptAllFileFilterUsed(true); FileNameExtensionFilter cfgFilter = new FileNameExtensionFilter("JaamSim Configuration File (*.cfg)", "CFG"); chooser.addChoosableFileFilter(cfgFilter); chooser.setFileFilter(cfgFilter); chooser.setSelectedFile(sim.getConfigFile()); // Show the file chooser and wait for selection int returnVal = chooser.showSaveDialog(this); if (returnVal != JFileChooser.APPROVE_OPTION) return false; File file = chooser.getSelectedFile(); // Add the file extension ".cfg" if needed String filePath = file.getPath(); filePath = filePath.trim(); if (file.getName().trim().indexOf('.') == -1) { filePath = filePath.concat(".cfg"); file = new File(filePath); } // Confirm overwrite if file already exists if (file.exists()) { boolean confirmed = GUIFrame.showSaveAsDialog(file.getName()); if (!confirmed) { return false; } } // Save the configuration file setSaveFile(file); setConfigFolder(file.getParent()); updateUI(); return true; } public void copyToClipboard(Entity ent) { if (ent == sim.getSimulation()) return; Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); clpbrd.setContents(new StringSelection(ent.getName()), null); } public Entity getEntityFromClipboard() { Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); try { String name = (String)clpbrd.getData(DataFlavor.stringFlavor); return sim.getNamedEntity(name); } catch (Throwable err) { return null; } } public void pasteEntityFromClipboard() { Entity ent = getEntityFromClipboard(); if (ent == null || ent == sim.getSimulation()) return; // Identify the region for the new entity Region region = null; if (selectedEntity != null && selectedEntity instanceof DisplayEntity && !(ent instanceof OverlayEntity)) { if (selectedEntity instanceof Region) region = (Region) selectedEntity; else region = ((DisplayEntity) selectedEntity).getCurrentRegion(); } // Create the new entity String copyName = ent.getName(); if (region != null && region.getParent() != sim.getSimulation()) copyName = region.getParent().getName() + "." + ent.getLocalName(); copyName = InputAgent.getUniqueName(sim, copyName, "_Copy"); InputAgent.storeAndExecute(new DefineCommand(sim, ent.getClass(), copyName)); // Copy the inputs Entity copiedEnt = sim.getNamedEntity(copyName); copiedEnt.copyInputs(ent); // Ensure that a random generator has a unique stream number if (copiedEnt instanceof RandomStreamUser) { RandomStreamUser rsu = (RandomStreamUser) copiedEnt; setUniqueRandomSeed(rsu); } // Set the region if (region != null) InputAgent.applyArgs(copiedEnt, "Region", region.getName()); // Set the position if (ent instanceof DisplayEntity) { DisplayEntity dEnt = (DisplayEntity) copiedEnt; // If an entity is not selected, paste the new entity at the point of interest if (selectedEntity == null || !(selectedEntity instanceof DisplayEntity) || selectedEntity instanceof Region) { if (RenderManager.isGood()) RenderManager.inst().dragEntityToMousePosition(dEnt); } // If an entity is selected, paste the new entity next to the selected one else { int x = 0; int y = 0; if (selectedEntity instanceof OverlayEntity) { OverlayEntity olEnt = (OverlayEntity) selectedEntity; x = olEnt.getScreenPosition().get(0) + 10; y = olEnt.getScreenPosition().get(1) + 10; } DisplayEntity selectedDispEnt = (DisplayEntity) selectedEntity; Vec3d pos = selectedDispEnt.getGlobalPosition(); pos.x += 0.5d * selectedDispEnt.getSize().x; pos.y -= 0.5d * selectedDispEnt.getSize().y; pos = dEnt.getLocalPosition(pos); if (sim.getSimulation().isSnapToGrid()) pos = sim.getSimulation().getSnapGridPosition(pos); try { dEnt.dragged(x, y, pos); } catch (InputErrorException e) {} } // Add a label if required if (sim.getSimulation().isShowLabels() && EntityLabel.canLabel(dEnt)) EntityLabel.showTemporaryLabel(dEnt, true); } // Copy the children copyChildren(ent, copiedEnt); // Select the new entity FrameBox.setSelectedEntity(copiedEnt, false); } public void copyChildren(Entity parent0, Entity parent1) { // Create the copied children for (Entity child : parent0.getChildren()) { if (child.isGenerated() || child instanceof EntityLabel) continue; // Construct the new child's name String localName = child.getLocalName(); String name = parent1.getName() + "." + localName; // Create the new child InputAgent.storeAndExecute(new DefineCommand(sim, child.getClass(), name)); // Add a label if necessary if (child instanceof DisplayEntity) { Entity copiedChild = parent1.getChild(localName); EntityLabel label = EntityLabel.getLabel((DisplayEntity) child); if (label != null) { EntityLabel newLabel = EntityLabel.createLabel((DisplayEntity) copiedChild); InputAgent.applyBoolean(newLabel, "Show", label.getShowInput()); newLabel.setShow(label.getShow()); } } } // Set the early and normal inputs for each child for (int seq = 0; seq < 2; seq++) { for (Entity child : parent0.getChildren()) { String localName = child.getLocalName(); Entity copiedChild = parent1.getChild(localName); copiedChild.copyInputs(child, seq, false); } } // Ensure that any random stream inputs have a unique stream number for (Entity copiedChild : parent1.getChildren()) { if (!(copiedChild instanceof RandomStreamUser)) continue; RandomStreamUser rsu = (RandomStreamUser) copiedChild; setUniqueRandomSeed(rsu); } // Copy each child's children for (Entity child : parent0.getChildren()) { String localName = child.getLocalName(); Entity copiedChild = parent1.getChild(localName); copyChildren(child, copiedChild); } } public void setUniqueRandomSeed(RandomStreamUser rsu) { Simulation simulation = sim.getSimulation(); int seed = rsu.getStreamNumber(); if (seed >= 0 && simulation.getRandomStreamUsers(seed).size() <= 1) return; seed = simulation.getLargestStreamNumber() + 1; String key = rsu.getStreamNumberKeyword(); InputAgent.applyIntegers((Entity) rsu, key, seed); } public void invokeNew() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { newModel(); } }); } public void invokeOpen() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { load(); } }); } public void invokeSave() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { save(); } }); } public void invokeSaveAs() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { saveAs(); } }); } public void invokeExit() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { close(); } }); } public void invokeCopy(Entity ent) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { copyToClipboard(ent); } }); } public void invokePaste() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { pasteEntityFromClipboard(); } }); } public void invokeFind() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { FindBox.getInstance().showDialog(); } }); } public void invokeHelp() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String topic = ""; if (selectedEntity != null) topic = selectedEntity.getObjectType().getName(); HelpBox.getInstance().showDialog(topic); } }); } public void invokeRunPause() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { controlStartResume.doClick(); } }); } public void invokeSimSpeedUp() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (!spinner.isEnabled()) return; spinner.setValue(spinner.getNextValue()); } }); } public void invokeSimSpeedDown() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (!spinner.isEnabled()) return; spinner.setValue(spinner.getPreviousValue()); } }); } public static String getConfigFolder() { Preferences prefs = Preferences.userRoot().node(instance.getClass().getName()); return prefs.get(LAST_USED_FOLDER, new File(".").getAbsolutePath()); } public static void setConfigFolder(String path) { Preferences prefs = Preferences.userRoot().node(instance.getClass().getName()); prefs.put(LAST_USED_FOLDER, path); } public static String getImageFolder() { Preferences prefs = Preferences.userRoot().node(instance.getClass().getName()); return prefs.get(LAST_USED_IMAGE_FOLDER, getConfigFolder()); } public static void setImageFolder(String path) { Preferences prefs = Preferences.userRoot().node(instance.getClass().getName()); prefs.put(LAST_USED_IMAGE_FOLDER, path); } public static String get3DFolder() { Preferences prefs = Preferences.userRoot().node(instance.getClass().getName()); return prefs.get(LAST_USED_3D_FOLDER, getConfigFolder()); } public static void set3DFolder(String path) { Preferences prefs = Preferences.userRoot().node(instance.getClass().getName()); prefs.put(LAST_USED_3D_FOLDER, path); } /** * Returns a list of the names of the files contained in the specified resource folder. * @param folder - name of the resource folder * @return names of the files in the folder */ public static ArrayList<String> getResourceFileNames(String folder) { ArrayList<String> ret = new ArrayList<>(); try { URI uri = GUIFrame.class.getResource(folder).toURI(); // When developing in an IDE if (uri.getScheme().equals("file")) { File dir = new File(uri.getPath()); for (File file : dir.listFiles()) { ret.add(file.getName()); } } // When running in a built jar or executable if (uri.getScheme().equals("jar")) { try { FileSystem fs = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap()); Path path = fs.getPath(folder); Stream<Path> walk = Files.walk(path, 1); for (Iterator<Path> it = walk.iterator(); it.hasNext();){ Path each = it.next(); String file = each.toString(); if (file.length() > folder.length()) { ret.add(file.substring(folder.length() + 1)); } } walk.close(); fs.close(); } catch (IOException e) {} } } catch (URISyntaxException e) {} return ret; } // ****************************************************************************************************** // DIALOG BOXES // ****************************************************************************************************** /** * Shows the "Confirm Save As" dialog box * @param fileName - name of the file to be saved * @return true if the file is to be overwritten. */ public static boolean showSaveAsDialog(String fileName) { int userOption = JOptionPane.showConfirmDialog(null, String.format("The file '%s' already exists.\n" + "Do you want to replace it?", fileName), "Confirm Save As", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); return (userOption == JOptionPane.YES_OPTION); } /** * Shows the "Confirm Stop" dialog box. * @return true if the run is to be stopped. */ public static boolean showConfirmStopDialog() { int userOption = JOptionPane.showConfirmDialog( null, "WARNING: Are you sure you want to reset the simulation time to 0?", "Confirm Reset", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); return (userOption == JOptionPane.YES_OPTION); } /** * Shows the "Save Changes" dialog box * @return true for any response other than Cancel or Close. */ public static boolean showSaveChangesDialog(GUIFrame gui) { String message; if (sim.getConfigFile() == null) message = "Do you want to save the changes you made?"; else message = String.format("Do you want to save the changes you made to '%s'?", sim.getConfigFile().getName()); Object[] options = {"Save", "Don't Save", "Cancel"}; int userOption = JOptionPane.showOptionDialog( null, message, "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if (userOption == JOptionPane.YES_OPTION) { boolean confirmed = gui.save(); return confirmed; } else if (userOption == JOptionPane.NO_OPTION) return true; return false; } private static String getErrorMessage(String source, int position, String pre, String message, String post) { StringBuilder sb = new StringBuilder(); sb.append("<html>"); // Initial text prior to the message if (!pre.isEmpty()) { sb.append(html_replace(pre)).append("<br><br>"); } // Error message if (!message.isEmpty()) { sb.append(html_replace(message)).append("<br>"); } // Append the source expression with the error shown in red if (source != null && !source.isEmpty()) { // Use the same font as the Input Builder so that the expression looks the same Font font = UIManager.getDefaults().getFont("TextArea.font"); String preStyle = String.format("<pre style=\"font-family: %s; font-size: %spt\">", font.getFamily(), font.getSize()); // Source expression sb.append(preStyle); sb.append(html_replace(source.substring(0, position))); sb.append("<font color=\"red\">"); sb.append(html_replace(source.substring(position))); sb.append("</font>"); sb.append("</pre>"); } // Final text after the message if (!post.isEmpty()) { if (source == null || source.isEmpty()) { sb.append("<br>"); } sb.append(html_replace(post)); } sb.append("</html>"); return sb.toString(); } /** * Displays the Error Message dialog box * @param title - text for the dialog box name * @param source - expression that cause the error (if applicable) * @param position - location of the error in the expression (if applicable) * @param pre - text to appear prior to the error message * @param message - error message * @param post - text to appear after the error message */ public static void showErrorDialog(String title, String source, int position, String pre, String message, String post) { if (sim == null || sim.isBatchRun()) GUIFrame.shutdown(1); JPanel panel = new JPanel(); panel.setLayout( new BorderLayout() ); // Use the standard font for dialog boxes Font messageFont = UIManager.getDefaults().getFont("OptionPane.messageFont"); // Message JTextPane msgPane = new JTextPane(); msgPane.setOpaque(false); msgPane.setFont(messageFont); msgPane.setText(pre + "\n\n" + message); panel.add(msgPane, BorderLayout.NORTH); // Source if (!source.isEmpty() && position != -1) { JTextPane srcPane = new JTextPane() { @Override public Dimension getPreferredScrollableViewportSize() { Dimension ret = getPreferredSize(); ret.width = Math.min(ret.width, 900); ret.height = Math.min(ret.height, 300); return ret; } }; srcPane.setContentType("text/html"); String msg = GUIFrame.getErrorMessage(source, position, "", "", ""); srcPane.setText(msg); JScrollPane scrollPane = new JScrollPane(srcPane); scrollPane.setBorder(new EmptyBorder(10, 0, 10, 0)); panel.add(scrollPane, BorderLayout.CENTER); } // Additional information JTextPane postPane = new JTextPane(); postPane.setOpaque(false); postPane.setFont(messageFont); postPane.setText(post); panel.add(postPane, BorderLayout.SOUTH); panel.setMinimumSize( new Dimension( 600, 300 ) ); JOptionPane.showMessageDialog(null, panel, title, JOptionPane.ERROR_MESSAGE); } public static void showErrorDialog(String title, String pre, String message, String post) { GUIFrame.showErrorDialog(title, "", -1, pre, message, post); } public static void showErrorDialog(String title, String message) { GUIFrame.showErrorDialog(title, "", -1, "", message, ""); } @Override public void invokeErrorDialogBox(String title, String msg) { GUIFrame.invokeErrorDialog(title, msg); } /** * Shows the Error Message dialog box from a non-Swing thread * @param title - text for the dialog box name * @param msg - error message */ public static void invokeErrorDialog(String title, String msg) { SwingUtilities.invokeLater(new RunnableError(title, msg)); } private static class RunnableError implements Runnable { private final String title; private final String message; public RunnableError(String t, String m) { title = t; message = m; } @Override public void run() { GUIFrame.showErrorDialog(title, message); } } /** * Shows the Error Message dialog box with option to open the Log Viewer * @param title - text for the dialog box name * @param msg - error message */ public static void showErrorOptionDialog(String title, String msg) { if (sim == null || sim.isBatchRun()) GUIFrame.shutdown(1); Object[] options = {"Yes", "No"}; int userOption = JOptionPane.showOptionDialog(null, msg, title, JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]); if (userOption == JOptionPane.YES_OPTION) { KeywordIndex kw = InputAgent.formatBoolean("ShowLogViewer", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } /** * Shows the Error Message dialog box for the Input Editor * @param title - text for the dialog box name * @param source - input text * @param pos - index of the error in the input text * @param pre - text to appear before the error message * @param msg - error message * @param post - text to appear after the error message * @return true if the input is to be re-edited */ public static boolean showErrorEditDialog(String title, String source, int pos, String pre, String msg, String post) { String message = GUIFrame.getErrorMessage(source, pos, pre, msg, post); String[] options = { "Edit", "Reset" }; int reply = JOptionPane.showOptionDialog(null, message, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]); return (reply == JOptionPane.OK_OPTION); } // ****************************************************************************************************** // TOOL TIPS // ****************************************************************************************************** private static final Pattern amp = Pattern.compile("&"); private static final Pattern lt = Pattern.compile("<"); private static final Pattern gt = Pattern.compile(">"); private static final Pattern br = Pattern.compile("\n"); public static final String html_replace(String str) { String desc = str; desc = amp.matcher(desc).replaceAll("&amp;"); desc = lt.matcher(desc).replaceAll("&lt;"); desc = gt.matcher(desc).replaceAll("&gt;"); desc = br.matcher(desc).replaceAll("<BR>"); return desc; } /** * Returns the HTML code for pop-up tooltips in the Model Builder and Control Panel. * @param name - name of the item whose tooltip is to be generated * @param desc - text describing the item's function * @return HTML for the tooltip */ public static String formatToolTip(String name, String desc) { return String.format("<html><p width=\"200px\"><b>%s</b><br>%s</p></html>", name, desc); } /** * Returns the HTML code for a keyword's pop-up tooltip in the Input Editor. * @param className - object whose keyword tooltip is to be displayed * @param keyword - name of the keyword * @param description - description of the keyword * @param exampleList - a list of examples that show how the keyword can be used * @return HTML for the tooltip */ public static String formatKeywordToolTip(String className, String keyword, String description, String validInputs, String... exampleList) { StringBuilder sb = new StringBuilder("<html><p width=\"350px\">"); // Keyword name String key = html_replace(keyword); sb.append("<b>").append(key).append("</b><br>"); // Description String desc = html_replace(description); sb.append(desc).append("<br><br>"); // Valid Inputs if (validInputs != null) { sb.append(validInputs).append("<br><br>"); } // Examples if (exampleList.length > 0) { sb.append("<u>Examples:</u>"); } for (int i=0; i<exampleList.length; i++) { String item = html_replace(exampleList[i]); sb.append("<br>").append(item); } sb.append("</p></html>"); return sb.toString(); } /** * Returns the HTML code for an output's pop-up tooltip in the Output Viewer. * @param name - name of the output * @param description - description of the output * @return HTML for the tooltip */ public static String formatOutputToolTip(String name, String description) { String desc = html_replace(description); return String.format("<html><p width=\"250px\"><b>%s</b><br>%s</p></html>", name, desc); } /** * Returns the HTML code for an entity's pop-up tooltip in the Input Builder. * @param name - entity name * @param type - object type for the entity * @param description - description for the entity * @return HTML for the tooltip */ public static String formatEntityToolTip(String name, String type, String description) { String desc = html_replace(description); return String.format("<html><p width=\"250px\"><b>%s</b> (%s)<br>%s</p></html>", name, type, desc); } static ArrayList<Color4d> getFillColoursInUse(JaamSimModel simModel) { ArrayList<Color4d> ret = new ArrayList<>(); for (DisplayEntity ent : simModel.getClonesOfIterator(DisplayEntity.class, FillEntity.class)) { FillEntity fillEnt = (FillEntity) ent; if (ret.contains(fillEnt.getFillColour())) continue; ret.add(fillEnt.getFillColour()); } Collections.sort(ret, ColourInput.colourComparator); return ret; } static ArrayList<Color4d> getLineColoursInUse(JaamSimModel simModel) { ArrayList<Color4d> ret = new ArrayList<>(); for (DisplayEntity ent : simModel.getClonesOfIterator(DisplayEntity.class, LineEntity.class)) { LineEntity lineEnt = (LineEntity) ent; if (ret.contains(lineEnt.getLineColour())) continue; ret.add(lineEnt.getLineColour()); } Collections.sort(ret, ColourInput.colourComparator); return ret; } static ArrayList<String> getFontsInUse(JaamSimModel simModel) { ArrayList<String> ret = new ArrayList<>(); for (DisplayEntity ent : simModel.getClonesOfIterator(DisplayEntity.class, TextEntity.class)) { TextEntity textEnt = (TextEntity) ent; if (ret.contains(textEnt.getFontName())) continue; ret.add(textEnt.getFontName()); } Collections.sort(ret); return ret; } static ArrayList<Color4d> getFontColoursInUse(JaamSimModel simModel) { ArrayList<Color4d> ret = new ArrayList<>(); for (DisplayEntity ent : simModel.getClonesOfIterator(DisplayEntity.class, TextEntity.class)) { TextEntity textEnt = (TextEntity) ent; if (ret.contains(textEnt.getFontColor())) continue; ret.add(textEnt.getFontColor()); } Collections.sort(ret, ColourInput.colourComparator); return ret; } }
src/main/java/com/jaamsim/ui/GUIFrame.java
/* * JaamSim Discrete Event Simulation * Copyright (C) 2002-2011 Ausenco Engineering Canada Inc. * Copyright (C) 2016-2020 JaamSim Software Inc. * * 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. */ package com.jaamsim.ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Frame; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.FocusEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Rectangle2D; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.prefs.Preferences; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.swing.Box; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.JWindow; import javax.swing.KeyStroke; import javax.swing.SpinnerNumberModel; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import javax.swing.filechooser.FileNameExtensionFilter; import com.jaamsim.Commands.Command; import com.jaamsim.Commands.CoordinateCommand; import com.jaamsim.Commands.DefineCommand; import com.jaamsim.Commands.DefineViewCommand; import com.jaamsim.Commands.DeleteCommand; import com.jaamsim.Commands.KeywordCommand; import com.jaamsim.Commands.RenameCommand; import com.jaamsim.DisplayModels.TextModel; import com.jaamsim.Graphics.BillboardText; import com.jaamsim.Graphics.DirectedEntity; import com.jaamsim.Graphics.DisplayEntity; import com.jaamsim.Graphics.EntityLabel; import com.jaamsim.Graphics.FillEntity; import com.jaamsim.Graphics.LineEntity; import com.jaamsim.Graphics.OverlayEntity; import com.jaamsim.Graphics.OverlayText; import com.jaamsim.Graphics.Region; import com.jaamsim.Graphics.TextBasics; import com.jaamsim.Graphics.TextEntity; import com.jaamsim.Graphics.View; import com.jaamsim.ProbabilityDistributions.RandomStreamUser; import com.jaamsim.SubModels.CompoundEntity; import com.jaamsim.basicsim.Entity; import com.jaamsim.basicsim.ErrorException; import com.jaamsim.basicsim.GUIListener; import com.jaamsim.basicsim.JaamSimModel; import com.jaamsim.basicsim.Simulation; import com.jaamsim.controllers.RateLimiter; import com.jaamsim.controllers.RenderManager; import com.jaamsim.datatypes.IntegerVector; import com.jaamsim.events.EventManager; import com.jaamsim.events.EventTimeListener; import com.jaamsim.input.ColourInput; import com.jaamsim.input.Input; import com.jaamsim.input.InputAgent; import com.jaamsim.input.InputErrorException; import com.jaamsim.input.KeywordIndex; import com.jaamsim.input.Parser; import com.jaamsim.math.Color4d; import com.jaamsim.math.MathUtils; import com.jaamsim.math.Vec3d; import com.jaamsim.rng.MRG1999a; import com.jaamsim.units.DimensionlessUnit; import com.jaamsim.units.DistanceUnit; import com.jaamsim.units.TimeUnit; /** * The main window for a Graphical Simulation. It provides the controls for managing then * EventManager (run, pause, ...) and the graphics (zoom, pan, ...) */ public class GUIFrame extends OSFixJFrame implements EventTimeListener, GUIListener { private static GUIFrame instance; private static JaamSimModel sim; private static final ArrayList<JaamSimModel> simList = new ArrayList<>(); private static final AtomicLong modelCount = new AtomicLong(0); // number of JaamSimModels private final ArrayList<View> views = new ArrayList<>(); private int nextViewID = 1; // global shutdown flag static private AtomicBoolean shuttingDown; private JMenu fileMenu; private JMenu editMenu; private JMenu toolsMenu; private JMenu viewsMenu; private JMenu optionMenu; private JMenu unitsMenu; private JMenu windowMenu; private JMenu helpMenu; private JToggleButton snapToGrid; private JToggleButton xyzAxis; private JToggleButton grid; private JCheckBoxMenuItem alwaysTop; private JCheckBoxMenuItem graphicsDebug; private JMenuItem printInputItem; private JMenuItem saveConfigurationMenuItem; // "Save" private JLabel clockDisplay; private JLabel speedUpDisplay; private JLabel remainingDisplay; private JMenuItem undoMenuItem; private JMenuItem redoMenuItem; private JMenuItem copyMenuItem; private JMenuItem pasteMenuItem; private JMenuItem deleteMenuItem; private JToggleButton controlRealTime; private JSpinner spinner; private JButton fileSave; private JButton undo; private JButton redo; private JButton undoDropdown; private JButton redoDropdown; private final ArrayList<Command> undoList = new ArrayList<>(); private final ArrayList<Command> redoList = new ArrayList<>(); private JToggleButton showLabels; private JToggleButton showSubModels; private JToggleButton showLinks; private JToggleButton createLinks; private JButton nextButton; private JButton prevButton; private JToggleButton reverseButton; private JButton copyButton; private JButton pasteButton; private JToggleButton find; private JTextField dispModel; private JButton modelSelector; private JButton editDmButton; private JButton clearButton; private Entity selectedEntity; private ButtonGroup alignmentGroup; private JToggleButton alignLeft; private JToggleButton alignCentre; private JToggleButton alignRight; private JToggleButton bold; private JToggleButton italic; private JTextField font; private JButton fontSelector; private JTextField textHeight; private JButton largerText; private JButton smallerText; private ColorIcon colourIcon; private JButton fontColour; private JButton increaseZ; private JButton decreaseZ; private JToggleButton outline; private JSpinner lineWidth; private ColorIcon lineColourIcon; private JButton lineColour; private JToggleButton fill; private ColorIcon fillColourIcon; private JButton fillColour; private RoundToggleButton controlStartResume; private ImageIcon runPressedIcon; private ImageIcon pausePressedIcon; private RoundToggleButton controlStop; private JTextField pauseTime; private JTextField gridSpacing; private JLabel locatorPos; //JButton toolButtonIsometric; private JToggleButton lockViewXYPlane; private int lastValue = -1; private JProgressBar progressBar; private static ArrayList<Image> iconImages = new ArrayList<>(); private static final RateLimiter rateLimiter; private static boolean SAFE_GRAPHICS; // Collection of default window parameters int DEFAULT_GUI_WIDTH; int COL1_WIDTH; int COL2_WIDTH; int COL3_WIDTH; int COL4_WIDTH; int COL1_START; int COL2_START; int COL3_START; int COL4_START; int HALF_TOP; int HALF_BOTTOM; int TOP_START; int BOTTOM_START; int LOWER_HEIGHT; int LOWER_START; int VIEW_HEIGHT; int VIEW_WIDTH; int VIEW_OFFSET = 50; private static final String LAST_USED_FOLDER = ""; private static final String LAST_USED_3D_FOLDER = "3D_FOLDER"; private static final String LAST_USED_IMAGE_FOLDER = "IMAGE_FOLDER"; private static final String RUN_TOOLTIP = GUIFrame.formatToolTip("Run (space key)", "Starts or resumes the simulation run."); private static final String PAUSE_TOOLTIP = "<html><b>Pause</b></html>"; // Use a small tooltip for Pause so that it does not block the simulation time display static { try { if (OSFix.isWindows()) UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); else UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { LogBox.logLine("Unable to change look and feel."); } try { iconImages.clear(); Toolkit toolkit = Toolkit.getDefaultToolkit(); iconImages.add(toolkit.getImage(GUIFrame.class.getResource("/resources/images/icon-16.png"))); iconImages.add(toolkit.getImage(GUIFrame.class.getResource("/resources/images/icon-32.png"))); iconImages.add(toolkit.getImage(GUIFrame.class.getResource("/resources/images/icon-64.png"))); iconImages.add(toolkit.getImage(GUIFrame.class.getResource("/resources/images/icon-128.png"))); } catch (Exception e) { LogBox.logLine("Unable to load icon file."); } shuttingDown = new AtomicBoolean(false); rateLimiter = RateLimiter.create(60); } private GUIFrame() { super(); getContentPane().setLayout( new BorderLayout() ); setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ); // Initialize the working environment initializeMenus(); initializeButtonBar(); initializeMainToolBars(); this.setIconImages(GUIFrame.getWindowIcons()); //Set window size setResizable( true ); //FIXME should be false, but this causes the window to be sized // and positioned incorrectly in the Windows 7 Aero theme pack(); controlStartResume.requestFocusInWindow(); controlStartResume.setSelected( false ); controlStartResume.setEnabled( false ); controlStop.setSelected( false ); controlStop.setEnabled( false ); ToolTipManager.sharedInstance().setLightWeightPopupEnabled( false ); JPopupMenu.setDefaultLightWeightPopupEnabled( false ); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { close(); } @Override public void windowDeiconified(WindowEvent e) { showWindows(); } @Override public void windowIconified(WindowEvent e) { updateUI(); } @Override public void windowActivated(WindowEvent e) { showWindows(); } }); addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { if (sim.getSimulation() == null) return; sim.getSimulation().setControlPanelWidth(getSize().width); } @Override public void componentMoved(ComponentEvent e) { Simulation simulation = sim.getSimulation(); if (simulation == null) return; windowOffset = new Point(getLocation().x - initLocation.x, getLocation().y - initLocation.y); updateToolLocations(simulation); updateViewLocations(); } }); } private Point windowOffset = new Point(); private Point initLocation = new Point(getX(), getY()); // bypass the OSFix correction public Point getRelativeLocation(int x, int y) { return new Point(x - windowOffset.x, y - windowOffset.y); } public Point getGlobalLocation(int x, int y) { return new Point(x + windowOffset.x, y + windowOffset.y); } public static JaamSimModel getJaamSimModel() { return sim; } private static void setJaamSimModel(JaamSimModel sm) { if (sm == sim) return; if (!simList.contains(sm)) simList.add(sm); // Clear the listeners for the previous model if (sim != null) { sim.setTimeListener(null); sim.setGUIListener(null); } sim = sm; GUIFrame gui = getInstance(); if (gui == null) return; RenderManager.clear(); EntityPallet.update(); ObjectSelector.allowUpdate(); gui.resetViews(); gui.setTitle(sm); // Set the listeners for the new model sm.setTimeListener(gui); sm.setGUIListener(gui); // Pass the simulation time for the new model to the user interface gui.initSpeedUp(sm.getSimTime()); gui.tickUpdate(sm.getSimTicks()); gui.updateForSimulationState(sm.getSimState()); } public void setTitle(JaamSimModel sm) { String str = "JaamSim"; if (sm.getSimulation() != null) str = sm.getSimulation().getModelName(); setTitle(sm.toString() + " - " + str); } public void setTitle(JaamSimModel sm, int val) { String str = "JaamSim"; if (sm.getSimulation() != null) str = sm.getSimulation().getModelName(); String title = String.format("%d%% %s - %s", val, sim.toString(), str); setTitle(title); } private static JaamSimModel getNextJaamSimModel() { long num = modelCount.incrementAndGet(); return new JaamSimModel("Model" + num); } @Override public Dimension getPreferredSize() { Point fix = OSFix.getSizeAdustment(); return new Dimension(DEFAULT_GUI_WIDTH + fix.x, super.getPreferredSize().height); } public static synchronized GUIFrame getInstance() { return instance; } private static synchronized GUIFrame createInstance() { instance = new GUIFrame(); UIUpdater updater = new UIUpdater(instance); GUIFrame.registerCallback(new Runnable() { @Override public void run() { SwingUtilities.invokeLater(updater); } }); return instance; } public static final void registerCallback(Runnable r) { rateLimiter.registerCallback(r); } public static final void updateUI() { rateLimiter.queueUpdate(); } public void showWindows() { if (!RenderManager.isGood()) return; // Identity the view window that is active View activeView = RenderManager.inst().getActiveView(); // Re-open the view windows for (int i = 0; i < views.size(); i++) { View v = views.get(i); if (v != null && v.showWindow() && v != activeView) RenderManager.inst().createWindow(v); } // Re-open the active view window last if (activeView != null) RenderManager.inst().createWindow(activeView); // Re-open the tools showActiveTools(sim.getSimulation()); updateUI(); } /** * Perform exit window duties */ void close() { // check for unsaved changes if (sim.isSessionEdited()) { boolean confirmed = GUIFrame.showSaveChangesDialog(this); if (!confirmed) return; } sim.closeLogFile(); simList.remove(sim); if (simList.isEmpty()) GUIFrame.shutdown(0); setJaamSimModel(simList.get(0)); FrameBox.setSelectedEntity(sim.getSimulation(), false); } /** * Clears the simulation and user interface prior to loading a new model */ public void clear() { this.updateForSimulationState(JaamSimModel.SIM_STATE_LOADED); // Clear the buttons clearButtons(); clearUndoRedo(); } /** * Sets up the Control Panel's menu bar. */ private void initializeMenus() { // Set up the individual menus this.initializeFileMenu(); this.initializeEditMenu(); this.initializeToolsMenu(); this.initializeViewsMenu(); this.initializeOptionsMenu(); this.initializeUnitsMenu(); this.initializeWindowMenu(); this.initializeHelpMenu(); // Add the individual menu to the main menu JMenuBar mainMenuBar = new JMenuBar(); mainMenuBar.add( fileMenu ); mainMenuBar.add( editMenu ); mainMenuBar.add( toolsMenu ); mainMenuBar.add( viewsMenu ); mainMenuBar.add( optionMenu ); mainMenuBar.add( unitsMenu ); mainMenuBar.add( windowMenu ); mainMenuBar.add( helpMenu ); // Add main menu to the window setJMenuBar( mainMenuBar ); } // ****************************************************************************************************** // MENU BAR // ****************************************************************************************************** /** * Sets up the File menu in the Control Panel's menu bar. */ private void initializeFileMenu() { // File menu creation fileMenu = new JMenu( "File" ); fileMenu.setMnemonic(KeyEvent.VK_F); fileMenu.setEnabled( false ); // 1) "New" menu item JMenuItem newMenuItem = new JMenuItem( "New" ); newMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/New-16.png")) ); newMenuItem.setMnemonic(KeyEvent.VK_N); newMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)); newMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.newModel(); } } ); fileMenu.add( newMenuItem ); // 2) "Open" menu item JMenuItem configMenuItem = new JMenuItem( "Open..." ); configMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/Open-16.png")) ); configMenuItem.setMnemonic(KeyEvent.VK_O); configMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK)); configMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.load(); } } ); fileMenu.add( configMenuItem ); // 3) "Save" menu item saveConfigurationMenuItem = new JMenuItem( "Save" ); saveConfigurationMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/Save-16.png")) ); saveConfigurationMenuItem.setMnemonic(KeyEvent.VK_S); saveConfigurationMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)); saveConfigurationMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.save(); } } ); fileMenu.add( saveConfigurationMenuItem ); // 4) "Save As..." menu item JMenuItem saveConfigurationAsMenuItem = new JMenuItem( "Save As..." ); saveConfigurationAsMenuItem.setMnemonic(KeyEvent.VK_V); saveConfigurationAsMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.ALT_MASK + ActionEvent.CTRL_MASK)); saveConfigurationAsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.saveAs(); } } ); fileMenu.add( saveConfigurationAsMenuItem ); fileMenu.addSeparator(); // 5) "Import..." menu item JMenu importGraphicsMenuItem = new JMenu( "Import..." ); importGraphicsMenuItem.setMnemonic(KeyEvent.VK_I); JMenuItem importImages = new JMenuItem( "Images..." ); importImages.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { DisplayEntityFactory.importImages(GUIFrame.this); } } ); importGraphicsMenuItem.add( importImages ); JMenuItem import3D = new JMenuItem( "3D Assets..." ); import3D.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { DisplayEntityFactory.import3D(GUIFrame.this); } } ); importGraphicsMenuItem.add( import3D ); fileMenu.add( importGraphicsMenuItem ); // 6) "Print Input Report" menu item printInputItem = new JMenuItem( "Print Input Report" ); printInputItem.setMnemonic(KeyEvent.VK_I); printInputItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.printInputFileKeywords(sim); } } ); fileMenu.add( printInputItem ); // 7) "Exit" menu item JMenuItem exitMenuItem = new JMenuItem( "Exit" ); exitMenuItem.setMnemonic(KeyEvent.VK_X); exitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, ActionEvent.ALT_MASK)); exitMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { close(); } }); fileMenu.addSeparator(); fileMenu.add( exitMenuItem ); } /** * Sets up the Edit menu in the Control Panel's menu bar. */ private void initializeEditMenu() { // Edit menu creation editMenu = new JMenu( "Edit" ); editMenu.setMnemonic(KeyEvent.VK_E); // 1) "Undo" menu item undoMenuItem = new JMenuItem("Undo"); undoMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/Undo-16.png")) ); undoMenuItem.setMnemonic(KeyEvent.VK_U); undoMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_Z, ActionEvent.CTRL_MASK)); undoMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { undo(); } } ); editMenu.add( undoMenuItem ); // 2) "Redo" menu item redoMenuItem = new JMenuItem("Redo"); redoMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/Redo-16.png")) ); redoMenuItem.setMnemonic(KeyEvent.VK_R); redoMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_Y, ActionEvent.CTRL_MASK)); redoMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { redo(); } } ); editMenu.add( redoMenuItem ); editMenu.addSeparator(); // 3) "Copy" menu item copyMenuItem = new JMenuItem("Copy"); copyMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/Copy-16.png")) ); copyMenuItem.setMnemonic(KeyEvent.VK_C); copyMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_C, ActionEvent.CTRL_MASK)); copyMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (selectedEntity == null) return; copyToClipboard(selectedEntity); } } ); editMenu.add( copyMenuItem ); // 4) "Paste" menu item pasteMenuItem = new JMenuItem("Paste"); pasteMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/Paste-16.png")) ); pasteMenuItem.setMnemonic(KeyEvent.VK_P); pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_V, ActionEvent.CTRL_MASK)); pasteMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { pasteEntityFromClipboard(); } } ); editMenu.add( pasteMenuItem ); // 5) "Delete" menu item deleteMenuItem = new JMenuItem("Delete"); deleteMenuItem.setMnemonic(KeyEvent.VK_D); deleteMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_DELETE, 0)); deleteMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (selectedEntity == null) return; try { deleteEntity(selectedEntity); FrameBox.setSelectedEntity(null, false); } catch (ErrorException e) { GUIFrame.showErrorDialog("User Error", e.getMessage()); } } } ); editMenu.add( deleteMenuItem ); editMenu.addSeparator(); // 6) "Find" menu item JMenuItem findMenuItem = new JMenuItem("Find"); findMenuItem.setIcon( new ImageIcon( GUIFrame.class.getResource("/resources/images/Find-16.png")) ); findMenuItem.setMnemonic(KeyEvent.VK_F); findMenuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_F, ActionEvent.CTRL_MASK)); findMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { FindBox.getInstance().showDialog(); } } ); editMenu.add( findMenuItem ); } /** * Sets up the Tools menu in the Control Panel's menu bar. */ private void initializeToolsMenu() { // Tools menu creation toolsMenu = new JMenu( "Tools" ); toolsMenu.setMnemonic(KeyEvent.VK_T); // 1) "Show Basic Tools" menu item JMenuItem showBasicToolsMenuItem = new JMenuItem( "Show Basic Tools" ); showBasicToolsMenuItem.setMnemonic(KeyEvent.VK_B); showBasicToolsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { EntityPallet.getInstance().toFront(); ObjectSelector.getInstance().toFront(); EditBox.getInstance().toFront(); OutputBox.getInstance().toFront(); KeywordIndex[] kws = new KeywordIndex[4]; kws[0] = InputAgent.formatBoolean("ShowModelBuilder", true); kws[1] = InputAgent.formatBoolean("ShowObjectSelector", true); kws[2] = InputAgent.formatBoolean("ShowInputEditor", true); kws[3] = InputAgent.formatBoolean("ShowOutputViewer", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kws)); } } ); toolsMenu.add( showBasicToolsMenuItem ); // 2) "Close All Tools" menu item JMenuItem closeAllToolsMenuItem = new JMenuItem( "Close All Tools" ); closeAllToolsMenuItem.setMnemonic(KeyEvent.VK_C); closeAllToolsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { KeywordIndex[] kws = new KeywordIndex[7]; kws[0] = InputAgent.formatBoolean("ShowModelBuilder", false); kws[1] = InputAgent.formatBoolean("ShowObjectSelector", false); kws[2] = InputAgent.formatBoolean("ShowInputEditor", false); kws[3] = InputAgent.formatBoolean("ShowOutputViewer", false); kws[4] = InputAgent.formatBoolean("ShowPropertyViewer", false); kws[5] = InputAgent.formatBoolean("ShowLogViewer", false); kws[6] = InputAgent.formatBoolean("ShowEventViewer", false); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kws)); } } ); toolsMenu.add( closeAllToolsMenuItem ); // 3) "Model Builder" menu item JMenuItem objectPalletMenuItem = new JMenuItem( "Model Builder" ); objectPalletMenuItem.setMnemonic(KeyEvent.VK_O); objectPalletMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { EntityPallet.getInstance().toFront(); KeywordIndex kw = InputAgent.formatBoolean("ShowModelBuilder", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } ); toolsMenu.addSeparator(); toolsMenu.add( objectPalletMenuItem ); // 4) "Object Selector" menu item JMenuItem objectSelectorMenuItem = new JMenuItem( "Object Selector" ); objectSelectorMenuItem.setMnemonic(KeyEvent.VK_S); objectSelectorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ObjectSelector.getInstance().toFront(); KeywordIndex kw = InputAgent.formatBoolean("ShowObjectSelector", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } ); toolsMenu.add( objectSelectorMenuItem ); // 5) "Input Editor" menu item JMenuItem inputEditorMenuItem = new JMenuItem( "Input Editor" ); inputEditorMenuItem.setMnemonic(KeyEvent.VK_I); inputEditorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { EditBox.getInstance().toFront(); KeywordIndex kw = InputAgent.formatBoolean("ShowInputEditor", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } ); toolsMenu.add( inputEditorMenuItem ); // 6) "Output Viewer" menu item JMenuItem outputMenuItem = new JMenuItem( "Output Viewer" ); outputMenuItem.setMnemonic(KeyEvent.VK_U); outputMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { OutputBox.getInstance().toFront(); KeywordIndex kw = InputAgent.formatBoolean("ShowOutputViewer", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } ); toolsMenu.add( outputMenuItem ); // 7) "Property Viewer" menu item JMenuItem propertiesMenuItem = new JMenuItem( "Property Viewer" ); propertiesMenuItem.setMnemonic(KeyEvent.VK_P); propertiesMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PropertyBox.getInstance().toFront(); KeywordIndex kw = InputAgent.formatBoolean("ShowPropertyViewer", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } ); toolsMenu.add( propertiesMenuItem ); // 8) "Log Viewer" menu item JMenuItem logMenuItem = new JMenuItem( "Log Viewer" ); logMenuItem.setMnemonic(KeyEvent.VK_L); logMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { LogBox.getInstance().toFront(); KeywordIndex kw = InputAgent.formatBoolean("ShowLogViewer", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } ); toolsMenu.add( logMenuItem ); // 9) "Event Viewer" menu item JMenuItem eventsMenuItem = new JMenuItem( "Event Viewer" ); eventsMenuItem.setMnemonic(KeyEvent.VK_E); eventsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { EventViewer.getInstance().toFront(); KeywordIndex kw = InputAgent.formatBoolean("ShowEventViewer", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } ); toolsMenu.add( eventsMenuItem ); // 10) "Reset Positions and Sizes" menu item JMenuItem resetItem = new JMenuItem( "Reset Positions and Sizes" ); resetItem.setMnemonic(KeyEvent.VK_R); resetItem.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { sim.getSimulation().resetWindowPositionsAndSizes(); } } ); toolsMenu.addSeparator(); toolsMenu.add( resetItem ); } /** * Sets up the Views menu in the Control Panel's menu bar. */ private void initializeViewsMenu() { viewsMenu = new JMenu("Views"); viewsMenu.setMnemonic(KeyEvent.VK_V); viewsMenu.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { // 1) Select from the available view windows for (View view : getInstance().getViews()) { JMenuItem item = new JMenuItem(view.getName()); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { if (RenderManager.canInitialize()) { RenderManager.initialize(SAFE_GRAPHICS); } else { // A fatal error has occurred, don't try to initialize again return; } } KeywordIndex kw = InputAgent.formatBoolean("ShowWindow", true); InputAgent.storeAndExecute(new KeywordCommand(view, kw)); FrameBox.setSelectedEntity(view, false); } }); viewsMenu.add(item); } // 2) "Define New View" menu item JMenuItem defineItem = new JMenuItem("Define New View"); defineItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { if (RenderManager.canInitialize()) { RenderManager.initialize(SAFE_GRAPHICS); } else { // A fatal error has occurred, don't try to initialize again return; } } String name = InputAgent.getUniqueName(sim, "View", ""); IntegerVector winPos = null; Vec3d pos = null; Vec3d center = null; ArrayList<View> viewList = getInstance().getViews(); if (!viewList.isEmpty()) { View lastView = viewList.get(viewList.size() - 1); winPos = (IntegerVector) lastView.getInput("WindowPosition").getValue(); winPos = new IntegerVector(winPos); winPos.set(0, winPos.get(0) + VIEW_OFFSET); pos = lastView.getViewPosition(); center = lastView.getViewCenter(); } InputAgent.storeAndExecute(new DefineViewCommand(sim, name, pos, center, winPos)); } }); viewsMenu.addSeparator(); viewsMenu.add(defineItem); // 3) "Reset Positions and Sizes" menu item JMenuItem resetItem = new JMenuItem( "Reset Positions and Sizes" ); resetItem.setMnemonic(KeyEvent.VK_R); resetItem.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { for (View v : getInstance().getViews()) { KeywordIndex posKw = InputAgent.formatArgs("WindowPosition"); KeywordIndex sizeKw = InputAgent.formatArgs("WindowSize"); InputAgent.storeAndExecute(new KeywordCommand(v, posKw, sizeKw)); } } } ); viewsMenu.addSeparator(); viewsMenu.add(resetItem); } @Override public void menuCanceled(MenuEvent arg0) { } @Override public void menuDeselected(MenuEvent arg0) { viewsMenu.removeAll(); } }); } /** * Sets up the Options menu in the Control Panel's menu bar. */ private void initializeOptionsMenu() { optionMenu = new JMenu( "Options" ); optionMenu.setMnemonic(KeyEvent.VK_O); // 1) "Always on top" check box alwaysTop = new JCheckBoxMenuItem( "Always on top", false ); alwaysTop.setMnemonic(KeyEvent.VK_A); optionMenu.add( alwaysTop ); alwaysTop.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { if( GUIFrame.this.isAlwaysOnTop() ) { GUIFrame.this.setAlwaysOnTop( false ); } else { GUIFrame.this.setAlwaysOnTop( true ); } } } ); // 2) "Graphics Debug Info" check box graphicsDebug = new JCheckBoxMenuItem( "Graphics Debug Info", false ); graphicsDebug.setMnemonic(KeyEvent.VK_D); optionMenu.add( graphicsDebug ); graphicsDebug.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RenderManager.setDebugInfo(((JCheckBoxMenuItem)e.getSource()).getState()); } }); } /** * Sets up the Units menu in the Control Panel's menu bar. */ private void initializeUnitsMenu() { unitsMenu = new JMenu( "Units" ); unitsMenu.setMnemonic(KeyEvent.VK_U); unitsMenu.addMenuListener( new MenuListener() { @Override public void menuCanceled(MenuEvent arg0) {} @Override public void menuDeselected(MenuEvent arg0) { unitsMenu.removeAll(); } @Override public void menuSelected(MenuEvent arg0) { UnitsSelector.populateMenu(unitsMenu); unitsMenu.setVisible(true); } }); } /** * Sets up the Windows menu in the Control Panel's menu bar. */ private void initializeWindowMenu() { windowMenu = new JMenu( "Window" ); windowMenu.setMnemonic(KeyEvent.VK_W); windowMenu.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { for (JaamSimModel sm : simList) { JRadioButtonMenuItem item = new JRadioButtonMenuItem(sm.toString()); if (sm == sim) item.setSelected(true); item.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { setJaamSimModel(sm); FrameBox.setSelectedEntity(sm.getSimulation(), false); } } ); windowMenu.add( item ); } } @Override public void menuCanceled(MenuEvent arg0) { } @Override public void menuDeselected(MenuEvent arg0) { windowMenu.removeAll(); } }); } /** * Sets up the Help menu in the Control Panel's menu bar. */ private void initializeHelpMenu() { // Help menu creation helpMenu = new JMenu( "Help" ); helpMenu.setMnemonic(KeyEvent.VK_H); // 1) "About" menu item JMenuItem aboutMenu = new JMenuItem( "About" ); aboutMenu.setMnemonic(KeyEvent.VK_A); aboutMenu.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { AboutBox about = new AboutBox(); about.setLocationRelativeTo(null); about.setVisible(true); } } ); helpMenu.add( aboutMenu ); // 2) "Help" menu item JMenuItem helpItem = new JMenuItem( "Help" ); helpItem.setMnemonic(KeyEvent.VK_H); helpItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); helpItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { String topic = ""; if (selectedEntity != null) topic = selectedEntity.getObjectType().getName(); HelpBox.getInstance().showDialog(topic); } } ); helpMenu.add( helpItem ); } /** * Returns the pixel length of the string with specified font */ private static int getPixelWidthOfString_ForFont(String str, Font font) { FontMetrics metrics = new FontMetrics(font) {}; Rectangle2D bounds = metrics.getStringBounds(str, null); return (int)bounds.getWidth(); } // ****************************************************************************************************** // BUTTON BAR // ****************************************************************************************************** /** * Sets up the Control Panel's button bar. */ public void initializeButtonBar() { Insets noMargin = new Insets( 0, 0, 0, 0 ); Insets smallMargin = new Insets( 1, 1, 1, 1 ); Dimension separatorDim = new Dimension(11, 20); Dimension gapDim = new Dimension(5, separatorDim.height); JToolBar buttonBar = new JToolBar(); buttonBar.setMargin( smallMargin ); buttonBar.setFloatable(false); buttonBar.setLayout( new FlowLayout( FlowLayout.LEFT, 0, 0 ) ); getContentPane().add( buttonBar, BorderLayout.NORTH ); // File new, open, and save buttons buttonBar.add(Box.createRigidArea(gapDim)); addFileNewButton(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addFileOpenButton(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addFileSaveButton(buttonBar, noMargin); // Undo and redo buttons buttonBar.addSeparator(separatorDim); addUndoButtons(buttonBar, noMargin); // 2D, axes, and grid buttons buttonBar.addSeparator(separatorDim); add2dButton(buttonBar, smallMargin); buttonBar.add(Box.createRigidArea(gapDim)); addShowAxesButton(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addShowGridButton(buttonBar, noMargin); // Show labels button buttonBar.add(Box.createRigidArea(gapDim)); addShowLabelsButton(buttonBar, noMargin); // Show sub-models button buttonBar.add(Box.createRigidArea(gapDim)); addShowSubModelsButton(buttonBar, noMargin); // Snap-to-grid button and field buttonBar.addSeparator(separatorDim); addSnapToGridButton(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addSnapToGridField(buttonBar, noMargin); // Show and create links buttons buttonBar.addSeparator(separatorDim); addShowLinksButton(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addCreateLinksButton(buttonBar, noMargin); // Previous and Next buttons buttonBar.add(Box.createRigidArea(gapDim)); addPreviousButton(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addNextButton(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addReverseButton(buttonBar, noMargin); // Show Copy and Paste buttons buttonBar.addSeparator(separatorDim); addCopyButton(buttonBar, noMargin); addPasteButton(buttonBar, noMargin); // Show Entity Finder button buttonBar.add(Box.createRigidArea(gapDim)); addEntityFinderButton(buttonBar, noMargin); // DisplayModel field and button buttonBar.addSeparator(separatorDim); addDisplayModelSelector(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addEditDisplayModelButton(buttonBar, noMargin); // Clear formatting button buttonBar.add(Box.createRigidArea(gapDim)); addClearFormattingButton(buttonBar, noMargin); // Font selector and text height field buttonBar.addSeparator(separatorDim); addFontSelector(buttonBar, noMargin); buttonBar.add(Box.createRigidArea(gapDim)); addTextHeightField(buttonBar, noMargin); // Larger and smaller text height buttons buttonBar.add(Box.createRigidArea(gapDim)); addTextHeightButtons(buttonBar, noMargin); // Bold and Italic buttons buttonBar.add(Box.createRigidArea(gapDim)); addFontStyleButtons(buttonBar, noMargin); // Font colour button buttonBar.add(Box.createRigidArea(gapDim)); addFontColourButton(buttonBar, noMargin); // Text alignment buttons buttonBar.add(Box.createRigidArea(gapDim)); addTextAlignmentButtons(buttonBar, noMargin); // Z-coordinate buttons buttonBar.addSeparator(separatorDim); addZButtons(buttonBar, noMargin); // Line buttons buttonBar.addSeparator(separatorDim); addOutlineButton(buttonBar, noMargin); addLineWidthSpinner(buttonBar, noMargin); addLineColourButton(buttonBar, noMargin); // Fill buttons buttonBar.addSeparator(separatorDim); addFillButton(buttonBar, noMargin); addFillColourButton(buttonBar, noMargin); } private void addFileNewButton(JToolBar buttonBar, Insets margin) { JButton fileNew = new JButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/New-16.png")) ); fileNew.setMargin(margin); fileNew.setFocusPainted(false); fileNew.setToolTipText(formatToolTip("New (Ctrl+N)", "Starts a new model.")); fileNew.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.newModel(); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( fileNew ); } private void addFileOpenButton(JToolBar buttonBar, Insets margin) { JButton fileOpen = new JButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/Open-16.png")) ); fileOpen.setMargin(margin); fileOpen.setFocusPainted(false); fileOpen.setToolTipText(formatToolTip("Open... (Ctrl+O)", "Opens a model.")); fileOpen.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.load(); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( fileOpen ); } private void addFileSaveButton(JToolBar buttonBar, Insets margin) { fileSave = new JButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/Save-16.png")) ); fileSave.setMargin(margin); fileSave.setFocusPainted(false); fileSave.setToolTipText(formatToolTip("Save (Ctrl+S)", "Saves the present model.")); fileSave.setEnabled(false); fileSave.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.save(); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( fileSave ); } private void addUndoButtons(JToolBar buttonBar, Insets margin) { // Undo button undo = new JButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/Undo-16.png")) ); undo.setMargin(margin); undo.setFocusPainted(false); undo.setRequestFocusEnabled(false); undo.setToolTipText(formatToolTip("Undo (Ctrl+Z)", "Reverses the last change to the model.")); undo.setEnabled(!undoList.isEmpty()); undo.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { undo(); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( undo ); // Undo Dropdown Menu undoDropdown = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/dropdown.png"))); undoDropdown.setMargin(margin); undoDropdown.setFocusPainted(false); undoDropdown.setRequestFocusEnabled(false); undoDropdown.setEnabled(!undoList.isEmpty()); undoDropdown.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ScrollablePopupMenu menu = new ScrollablePopupMenu("UndoMenu"); synchronized (undoList) { for (int i = 1; i <= undoList.size(); i++) { Command cmd = undoList.get(undoList.size() - i); final int num = i; JMenuItem item = new JMenuItem(cmd.toString()); item.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { undo(num); controlStartResume.requestFocusInWindow(); } } ); menu.add(item); } menu.show(undoDropdown, 0, undoDropdown.getHeight()); } } } ); buttonBar.add( undoDropdown ); // Redo button redo = new JButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/Redo-16.png")) ); redo.setMargin(margin); redo.setFocusPainted(false); redo.setRequestFocusEnabled(false); redo.setToolTipText(formatToolTip("Redo (Ctrl+Y)", "Re-performs the last change to the model that was undone.")); redo.setEnabled(!redoList.isEmpty()); redo.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { redo(); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( redo ); // Redo Dropdown Menu redoDropdown = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/dropdown.png"))); redoDropdown.setMargin(margin); redoDropdown.setFocusPainted(false); redoDropdown.setRequestFocusEnabled(false); redoDropdown.setEnabled(!redoList.isEmpty()); redoDropdown.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ScrollablePopupMenu menu = new ScrollablePopupMenu("RedoMenu"); synchronized (undoList) { for (int i = 1; i <= redoList.size(); i++) { Command cmd = redoList.get(redoList.size() - i); final int num = i; JMenuItem item = new JMenuItem(cmd.toString()); item.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { redo(num); controlStartResume.requestFocusInWindow(); } } ); menu.add(item); } menu.show(redoDropdown, 0, redoDropdown.getHeight()); } } } ); buttonBar.add( redoDropdown ); } private void add2dButton(JToolBar buttonBar, Insets margin) { lockViewXYPlane = new JToggleButton( "2D" ); lockViewXYPlane.setMargin(margin); lockViewXYPlane.setFocusPainted(false); lockViewXYPlane.setRequestFocusEnabled(false); lockViewXYPlane.setToolTipText(formatToolTip("2D View", "Sets the camera position to show a bird's eye view of the 3D scene.")); lockViewXYPlane.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { boolean bLock2D = (((JToggleButton)event.getSource()).isSelected()); if (RenderManager.isGood()) { View currentView = RenderManager.inst().getActiveView(); if (currentView != null) { currentView.setLock2D(bLock2D); } } controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( lockViewXYPlane ); } private void addShowAxesButton(JToolBar buttonBar, Insets margin) { xyzAxis = new JToggleButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/Axes-16.png")) ); xyzAxis.setMargin(margin); xyzAxis.setFocusPainted(false); xyzAxis.setRequestFocusEnabled(false); xyzAxis.setToolTipText(formatToolTip("Show Axes", "Shows the unit vectors for the x, y, and z axes.")); xyzAxis.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { DisplayEntity ent = (DisplayEntity) sim.getNamedEntity("XYZ-Axis"); if (ent != null) { KeywordIndex kw = InputAgent.formatBoolean("Show", xyzAxis.isSelected()); InputAgent.storeAndExecute(new KeywordCommand(ent, kw)); } controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( xyzAxis ); } private void addShowGridButton(JToolBar buttonBar, Insets margin) { grid = new JToggleButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/Grid-16.png")) ); grid.setMargin(margin); grid.setFocusPainted(false); grid.setRequestFocusEnabled(false); grid.setToolTipText(formatToolTip("Show Grid", "Shows the coordinate grid on the x-y plane.")); grid.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { DisplayEntity ent = (DisplayEntity) sim.getNamedEntity("XY-Grid"); if (ent == null && sim.getNamedEntity("Grid100x100") != null) { InputAgent.storeAndExecute(new DefineCommand(sim, DisplayEntity.class, "XY-Grid")); ent = (DisplayEntity) sim.getNamedEntity("XY-Grid"); KeywordIndex dmKw = InputAgent.formatArgs("DisplayModel", "Grid100x100"); KeywordIndex sizeKw = InputAgent.formatArgs("Size", "100", "100", "0", "m"); InputAgent.storeAndExecute(new KeywordCommand(ent, dmKw, sizeKw)); grid.setSelected(true); } if (ent != null) { KeywordIndex kw = InputAgent.formatBoolean("Show", grid.isSelected()); InputAgent.storeAndExecute(new KeywordCommand(ent, kw)); } controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( grid ); } private void addShowLabelsButton(JToolBar buttonBar, Insets margin) { showLabels = new JToggleButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/ShowLabels-16.png")) ); showLabels.setMargin(margin); showLabels.setFocusPainted(false); showLabels.setRequestFocusEnabled(false); showLabels.setToolTipText(formatToolTip("Show Labels", "Displays the label for every entity in the model.")); showLabels.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { boolean bool = showLabels.isSelected(); KeywordIndex kw = InputAgent.formatBoolean("ShowLabels", bool); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); setShowLabels(bool); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( showLabels ); } private void addShowSubModelsButton(JToolBar buttonBar, Insets margin) { showSubModels = new JToggleButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/ShowSubModels-16.png")) ); showSubModels.setMargin(margin); showSubModels.setFocusPainted(false); showSubModels.setRequestFocusEnabled(false); showSubModels.setToolTipText(formatToolTip("Show SubModels", "Displays the components of each sub-model.")); showSubModels.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { boolean bool = showSubModels.isSelected(); KeywordIndex kw = InputAgent.formatBoolean("ShowSubModels", bool); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); setShowSubModels(bool); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( showSubModels ); } private void addSnapToGridButton(JToolBar buttonBar, Insets margin) { snapToGrid = new JToggleButton( new ImageIcon( GUIFrame.class.getResource("/resources/images/Snap-16.png")) ); snapToGrid.setMargin(margin); snapToGrid.setFocusPainted(false); snapToGrid.setRequestFocusEnabled(false); snapToGrid.setToolTipText(formatToolTip("Snap to Grid", "During repositioning, objects are forced to the nearest grid point.")); snapToGrid.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { KeywordIndex kw = InputAgent.formatBoolean("SnapToGrid", snapToGrid.isSelected()); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); gridSpacing.setEnabled(snapToGrid.isSelected()); controlStartResume.requestFocusInWindow(); } } ); buttonBar.add( snapToGrid ); } private void addSnapToGridField(JToolBar buttonBar, Insets margin) { gridSpacing = new JTextField("1000000 m") { @Override protected void processFocusEvent(FocusEvent fe) { if (fe.getID() == FocusEvent.FOCUS_LOST) { GUIFrame.this.setSnapGridSpacing(this.getText().trim()); } else if (fe.getID() == FocusEvent.FOCUS_GAINED) { gridSpacing.selectAll(); } super.processFocusEvent( fe ); } }; gridSpacing.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { GUIFrame.this.setSnapGridSpacing(gridSpacing.getText().trim()); controlStartResume.requestFocusInWindow(); } }); gridSpacing.setMaximumSize(gridSpacing.getPreferredSize()); int hght = snapToGrid.getPreferredSize().height; gridSpacing.setPreferredSize(new Dimension(gridSpacing.getPreferredSize().width, hght)); gridSpacing.setHorizontalAlignment(JTextField.RIGHT); gridSpacing.setToolTipText(formatToolTip("Snap Grid Spacing", "Distance between adjacent grid points, e.g. 0.1 m, 10 km, etc.")); gridSpacing.setEnabled(snapToGrid.isSelected()); buttonBar.add(gridSpacing); } private void addShowLinksButton(JToolBar buttonBar, Insets margin) { showLinks = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/ShowLinks-16.png"))); showLinks.setToolTipText(formatToolTip("Show Entity Flow", "When selected, arrows are shown between objects to indicate the flow of entities.")); showLinks.setMargin(margin); showLinks.setFocusPainted(false); showLinks.setRequestFocusEnabled(false); showLinks.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { boolean bShow = (((JToggleButton)event.getSource()).isSelected()); KeywordIndex kw = InputAgent.formatBoolean("ShowEntityFlow", bShow); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); setShowEntityFlow(bShow); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( showLinks ); } private void addCreateLinksButton(JToolBar buttonBar, Insets margin) { createLinks = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/MakeLinks-16.png"))); createLinks.setToolTipText(formatToolTip("Create Entity Links", "When this is enabled, entities are linked when selection is changed.")); createLinks.setMargin(margin); createLinks.setFocusPainted(false); createLinks.setRequestFocusEnabled(false); createLinks.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { boolean bCreate = (((JToggleButton)event.getSource()).isSelected()); if (RenderManager.isGood()) { if (bCreate) { FrameBox.setSelectedEntity(null, false); if (!showLinks.isSelected()) showLinks.doClick(); } RenderManager.inst().setCreateLinks(bCreate); } controlStartResume.requestFocusInWindow(); } }); buttonBar.add( createLinks ); } private void addPreviousButton(JToolBar buttonBar, Insets margin) { prevButton = new JButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/Previous-16.png"))); prevButton.setToolTipText(formatToolTip("Previous", "Selects the previous object in the chain of linked objects.")); prevButton.setMargin(margin); prevButton.setFocusPainted(false); prevButton.setRequestFocusEnabled(false); prevButton.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (createLinks.isSelected()) createLinks.doClick(); if (selectedEntity != null && selectedEntity instanceof DisplayEntity) { DisplayEntity selectedDEnt = (DisplayEntity) selectedEntity; boolean dir = !reverseButton.isSelected(); ArrayList<DirectedEntity> list = selectedDEnt.getPreviousList(dir); if (list.isEmpty()) return; if (list.size() == 1) { setSelectedDEnt(list.get(0)); return; } ScrollablePopupMenu menu = new ScrollablePopupMenu(); for (DirectedEntity de : list) { JMenuItem item = new JMenuItem(de.toString()); item.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { setSelectedDEnt(de); controlStartResume.requestFocusInWindow(); } } ); menu.add(item); } menu.show(prevButton, 0, prevButton.getHeight()); } } }); buttonBar.add( prevButton ); } private void addNextButton(JToolBar buttonBar, Insets margin) { nextButton = new JButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/Next-16.png"))); nextButton.setToolTipText(formatToolTip("Next", "Selects the next object in the chain of linked objects.")); nextButton.setMargin(margin); nextButton.setFocusPainted(false); nextButton.setRequestFocusEnabled(false); nextButton.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (createLinks.isSelected()) createLinks.doClick(); if (selectedEntity != null && selectedEntity instanceof DisplayEntity) { DisplayEntity selectedDEnt = (DisplayEntity) selectedEntity; boolean dir = !reverseButton.isSelected(); ArrayList<DirectedEntity> list = selectedDEnt.getNextList(dir); if (list.isEmpty()) return; if (list.size() == 1) { setSelectedDEnt(list.get(0)); return; } ScrollablePopupMenu menu = new ScrollablePopupMenu(); for (DirectedEntity de : list) { JMenuItem item = new JMenuItem(de.toString()); item.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { setSelectedDEnt(de); controlStartResume.requestFocusInWindow(); } } ); menu.add(item); } menu.show(nextButton, 0, nextButton.getHeight()); } } }); buttonBar.add( nextButton ); } private void setSelectedDEnt(DirectedEntity de) { FrameBox.setSelectedEntity(de.entity, false); if (!reverseButton.isSelected() == de.direction) return; reverseButton.doClick(); } private void addReverseButton(JToolBar buttonBar, Insets margin) { reverseButton = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/Reverse-16.png"))); reverseButton.setToolTipText(formatToolTip("Reverse Direction", "When enabled, the link arrows are shown for entities travelling in the reverse " + "direction, and the Next and Previous buttons select the next/previous links " + "for that direction.")); reverseButton.setMargin(margin); reverseButton.setFocusPainted(false); reverseButton.setRequestFocusEnabled(false); reverseButton.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (createLinks.isSelected()) createLinks.doClick(); boolean bool = (((JToggleButton)event.getSource()).isSelected()); if (RenderManager.isGood()) { RenderManager.inst().setLinkDirection(!bool); RenderManager.redraw(); } updateUI(); } }); // Reverse button is not needed in the open source JaamSim //buttonBar.add( reverseButton ); } private void addCopyButton(JToolBar buttonBar, Insets margin) { copyButton = new JButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/Copy-16.png"))); copyButton.setToolTipText(formatToolTip("Copy (Ctrl+C)", "Copies the selected entity to the clipboard.")); copyButton.setMargin(margin); copyButton.setFocusPainted(false); copyButton.setRequestFocusEnabled(false); copyButton.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (selectedEntity != null) copyToClipboard(selectedEntity); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( copyButton ); } private void addPasteButton(JToolBar buttonBar, Insets margin) { pasteButton = new JButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/Paste-16.png"))); pasteButton.setToolTipText(formatToolTip("Paste (Ctrl+V)", "Pastes a copy of an entity from the clipboard to the location of the most recent " + "mouse click.")); pasteButton.setMargin(margin); pasteButton.setFocusPainted(false); pasteButton.setRequestFocusEnabled(false); pasteButton.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { pasteEntityFromClipboard(); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( pasteButton ); } private void addEntityFinderButton(JToolBar buttonBar, Insets margin) { find = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/Find-16.png"))); find.setToolTipText(formatToolTip("Entity Finder (Ctrl+F)", "Searches for an entity with a given name.")); find.setMargin(margin); find.setFocusPainted(false); find.setRequestFocusEnabled(false); find.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (find.isSelected()) { FindBox.getInstance().showDialog(); } else { FindBox.getInstance().setVisible(false); } controlStartResume.requestFocusInWindow(); } }); buttonBar.add( find ); } private void addDisplayModelSelector(JToolBar buttonBar, Insets margin) { dispModel = new JTextField(""); dispModel.setEditable(false); dispModel.setHorizontalAlignment(JTextField.CENTER); dispModel.setPreferredSize(new Dimension(120, fileSave.getPreferredSize().height)); dispModel.setToolTipText(formatToolTip("DisplayModel", "Sets the default appearance of the entity. " + "A DisplayModel is analogous to a text style in a word processor.")); buttonBar.add(dispModel); modelSelector = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/dropdown.png"))); modelSelector.setMargin(margin); modelSelector.setFocusPainted(false); modelSelector.setRequestFocusEnabled(false); modelSelector.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof DisplayEntity)) return; DisplayEntity dispEnt = (DisplayEntity) selectedEntity; if (!dispEnt.isDisplayModelNominal() || dispEnt.getDisplayModelList().size() != 1) return; final String presentModelName = dispEnt.getDisplayModelList().get(0).getName(); Input<?> in = dispEnt.getInput("DisplayModel"); ArrayList<String> choices = in.getValidOptions(selectedEntity); PreviewablePopupMenu menu = new PreviewablePopupMenu(presentModelName, choices, true) { @Override public void setValue(String str) { dispModel.setText(str); KeywordIndex kw = InputAgent.formatArgs("DisplayModel", str); InputAgent.storeAndExecute(new KeywordCommand(dispEnt, kw)); controlStartResume.requestFocusInWindow(); } }; menu.show(dispModel, 0, dispModel.getPreferredSize().height); } }); buttonBar.add(modelSelector); } private void addEditDisplayModelButton(JToolBar buttonBar, Insets margin) { editDmButton = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/Edit-16.png"))); editDmButton.setToolTipText(formatToolTip("Edit DisplayModel", "Selects the present DisplayModel so that its inputs can be edited.")); editDmButton.setMargin(margin); editDmButton.setFocusPainted(false); editDmButton.setRequestFocusEnabled(false); editDmButton.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof DisplayEntity)) return; DisplayEntity dEnt = (DisplayEntity) selectedEntity; if (dEnt.getDisplayModelList().size() != 1) return; FrameBox.setSelectedEntity(dEnt.getDisplayModelList().get(0), false); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( editDmButton ); } private void addClearFormattingButton(JToolBar buttonBar, Insets margin) { clearButton = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/Clear-16.png"))); clearButton.setToolTipText(formatToolTip("Clear Formatting", "Resets the format inputs for the selected Entity or DisplayModel to their default " + "values.")); clearButton.setMargin(margin); clearButton.setFocusPainted(false); clearButton.setRequestFocusEnabled(false); clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (selectedEntity == null) return; ArrayList<KeywordIndex> kwList = new ArrayList<>(); for (Input<?> in : selectedEntity.getEditableInputs()) { String cat = in.getCategory(); if (in.isDefault() || !cat.equals(Entity.FORMAT) && !cat.equals(Entity.FONT)) continue; KeywordIndex kw = InputAgent.formatArgs(in.getKeyword()); kwList.add(kw); } if (kwList.isEmpty()) return; KeywordIndex[] kws = new KeywordIndex[kwList.size()]; kwList.toArray(kws); InputAgent.storeAndExecute(new KeywordCommand(selectedEntity, kws)); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( clearButton ); } private void addTextAlignmentButtons(JToolBar buttonBar, Insets margin) { ActionListener alignListener = new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof TextBasics)) return; TextBasics textEnt = (TextBasics) selectedEntity; Vec3d align = textEnt.getAlignment(); double prevAlign = align.x; align.x = alignLeft.isSelected() ? -0.5d : align.x; align.x = alignCentre.isSelected() ? 0.0d : align.x; align.x = alignRight.isSelected() ? 0.5d : align.x; if (align.x == textEnt.getAlignment().x) return; KeywordIndex kw = sim.formatVec3dInput("Alignment", align, DimensionlessUnit.class); Vec3d pos = textEnt.getPosition(); Vec3d size = textEnt.getSize(); pos.x += (align.x - prevAlign) * size.x; KeywordIndex posKw = sim.formatVec3dInput("Position", pos, DistanceUnit.class); InputAgent.storeAndExecute(new KeywordCommand(textEnt, kw, posKw)); controlStartResume.requestFocusInWindow(); } }; alignLeft = new JToggleButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/AlignLeft-16.png"))); alignLeft.setMargin(margin); alignLeft.setFocusPainted(false); alignLeft.setRequestFocusEnabled(false); alignLeft.setToolTipText(formatToolTip("Align Left", "Aligns the text to the left margin.")); alignLeft.addActionListener( alignListener ); alignCentre = new JToggleButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/AlignCentre-16.png"))); alignCentre.setMargin(margin); alignCentre.setFocusPainted(false); alignCentre.setRequestFocusEnabled(false); alignCentre.setToolTipText(formatToolTip("Align Centre", "Centres the text between the right and left margins.")); alignCentre.addActionListener( alignListener ); alignRight = new JToggleButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/AlignRight-16.png"))); alignRight.setMargin(margin); alignRight.setFocusPainted(false); alignRight.setRequestFocusEnabled(false); alignRight.setToolTipText(formatToolTip("Align Right", "Aligns the text to the right margin.")); alignRight.addActionListener( alignListener ); alignmentGroup = new ButtonGroup(); alignmentGroup.add(alignLeft); alignmentGroup.add(alignCentre); alignmentGroup.add(alignRight); buttonBar.add( alignLeft ); buttonBar.add( alignCentre ); buttonBar.add( alignRight ); } private void addFontStyleButtons(JToolBar buttonBar, Insets margin) { ActionListener alignmentListener = new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof TextEntity)) return; TextEntity textEnt = (TextEntity) selectedEntity; if (textEnt.isBold() == bold.isSelected() && textEnt.isItalic() && italic.isSelected()) return; ArrayList<String> stylesList = new ArrayList<>(2); if (bold.isSelected()) stylesList.add("BOLD"); if (italic.isSelected()) stylesList.add("ITALIC"); String[] styles = stylesList.toArray(new String[stylesList.size()]); KeywordIndex kw = InputAgent.formatArgs("FontStyle", styles); InputAgent.storeAndExecute(new KeywordCommand((Entity)textEnt, kw)); controlStartResume.requestFocusInWindow(); } }; bold = new JToggleButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/Bold-16.png"))); bold.setMargin(margin); bold.setFocusPainted(false); bold.setRequestFocusEnabled(false); bold.setToolTipText(formatToolTip("Bold", "Makes the text bold.")); bold.addActionListener( alignmentListener ); italic = new JToggleButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/Italic-16.png"))); italic.setMargin(margin); italic.setFocusPainted(false); italic.setRequestFocusEnabled(false); italic.setToolTipText(formatToolTip("Italic", "Italicizes the text.")); italic.addActionListener( alignmentListener ); buttonBar.add( bold ); buttonBar.add( italic ); } private void addFontSelector(JToolBar buttonBar, Insets margin) { font = new JTextField(""); font.setEditable(false); font.setHorizontalAlignment(JTextField.CENTER); font.setPreferredSize(new Dimension(120, fileSave.getPreferredSize().height)); font.setToolTipText(formatToolTip("Font", "Sets the font for the text.")); buttonBar.add(font); fontSelector = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/dropdown.png"))); fontSelector.setMargin(margin); fontSelector.setFocusPainted(false); fontSelector.setRequestFocusEnabled(false); fontSelector.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof TextEntity)) return; final TextEntity textEnt = (TextEntity) selectedEntity; final String presentFontName = textEnt.getFontName(); ArrayList<String> valuesInUse = GUIFrame.getFontsInUse(sim); ArrayList<String> choices = TextModel.validFontNames; PreviewablePopupMenu fontMenu = new PreviewablePopupMenu(presentFontName, valuesInUse, choices, true) { @Override public void setValue(String str) { font.setText(str); String name = Parser.addQuotesIfNeeded(str); KeywordIndex kw = InputAgent.formatInput("FontName", name); InputAgent.storeAndExecute(new KeywordCommand(selectedEntity, kw)); controlStartResume.requestFocusInWindow(); } }; fontMenu.show(font, 0, font.getPreferredSize().height); } }); buttonBar.add(fontSelector); } private void addTextHeightField(JToolBar buttonBar, Insets margin) { textHeight = new JTextField("1000000 m") { @Override protected void processFocusEvent(FocusEvent fe) { if (fe.getID() == FocusEvent.FOCUS_LOST) { GUIFrame.this.setTextHeight(this.getText().trim()); } super.processFocusEvent( fe ); } }; textHeight.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { GUIFrame.this.setTextHeight(textHeight.getText().trim()); controlStartResume.requestFocusInWindow(); } }); textHeight.setMaximumSize(textHeight.getPreferredSize()); textHeight.setPreferredSize(new Dimension(textHeight.getPreferredSize().width, fileSave.getPreferredSize().height)); textHeight.setHorizontalAlignment(JTextField.RIGHT); textHeight.setToolTipText(formatToolTip("Text Height", "Sets the height of the text, e.g. 0.1 m, 200 cm, etc.")); buttonBar.add(textHeight); } private void addTextHeightButtons(JToolBar buttonBar, Insets margin) { ActionListener textHeightListener = new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof TextEntity)) return; TextEntity textEnt = (TextEntity) selectedEntity; double height = textEnt.getTextHeight(); double spacing = sim.getSimulation().getSnapGridSpacing(); if (textEnt instanceof OverlayText || textEnt instanceof BillboardText) spacing = 1.0d; height = Math.round(height/spacing) * spacing; if (event.getActionCommand().equals("LargerText")) { height += spacing; } else if (event.getActionCommand().equals("SmallerText")) { height -= spacing; height = Math.max(spacing, height); } String format = "%.1f m"; if (textEnt instanceof OverlayText || textEnt instanceof BillboardText) format = "%.0f"; String str = String.format(format, height); textHeight.setText(str); KeywordIndex kw = InputAgent.formatInput("TextHeight", str); InputAgent.storeAndExecute(new KeywordCommand((Entity)textEnt, kw)); controlStartResume.requestFocusInWindow(); } }; largerText = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/LargerText-16.png"))); largerText.setMargin(margin); largerText.setFocusPainted(false); largerText.setRequestFocusEnabled(false); largerText.setToolTipText(formatToolTip("Larger Text", "Increases the text height to the next higher multiple of the snap grid spacing.")); largerText.setActionCommand("LargerText"); largerText.addActionListener( textHeightListener ); smallerText = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/SmallerText-16.png"))); smallerText.setMargin(margin); smallerText.setFocusPainted(false); smallerText.setRequestFocusEnabled(false); smallerText.setToolTipText(formatToolTip("Smaller Text", "Decreases the text height to the next lower multiple of the snap grid spacing.")); smallerText.setActionCommand("SmallerText"); smallerText.addActionListener( textHeightListener ); buttonBar.add( largerText ); buttonBar.add( smallerText ); } private void addFontColourButton(JToolBar buttonBar, Insets margin) { colourIcon = new ColorIcon(16, 16); colourIcon.setFillColor(Color.LIGHT_GRAY); colourIcon.setOutlineColor(Color.LIGHT_GRAY); fontColour = new JButton(colourIcon); fontColour.setMargin(margin); fontColour.setFocusPainted(false); fontColour.setRequestFocusEnabled(false); fontColour.setToolTipText(formatToolTip("Font Colour", "Sets the colour of the text.")); fontColour.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof TextEntity)) return; final TextEntity textEnt = (TextEntity) selectedEntity; final Color4d presentColour = textEnt.getFontColor(); ArrayList<Color4d> coloursInUse = GUIFrame.getFontColoursInUse(sim); ColourMenu fontMenu = new ColourMenu(presentColour, coloursInUse, true) { @Override public void setColour(String colStr) { KeywordIndex kw = InputAgent.formatInput("FontColour", colStr); InputAgent.storeAndExecute(new KeywordCommand(selectedEntity, kw)); } }; fontMenu.show(fontColour, 0, fontColour.getPreferredSize().height); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( fontColour ); } private void addZButtons(JToolBar buttonBar, Insets margin) { ActionListener actionListener = new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof DisplayEntity) || selectedEntity instanceof OverlayEntity) return; DisplayEntity dispEnt = (DisplayEntity) selectedEntity; double delta = sim.getSimulation().getSnapGridSpacing()/100.0d; Vec3d pos = dispEnt.getPosition(); ArrayList<Vec3d> points = dispEnt.getPoints(); Vec3d offset = new Vec3d(); if (event.getActionCommand().equals("Up")) { pos.z += delta; offset.z += delta; } else if (event.getActionCommand().equals("Down")) { pos.z -= delta; offset.z -= delta; } // Normal object KeywordIndex posKw = sim.formatVec3dInput("Position", pos, DistanceUnit.class); if (!dispEnt.usePointsInput()) { InputAgent.storeAndExecute(new KeywordCommand(dispEnt, posKw)); controlStartResume.requestFocusInWindow(); return; } // Polyline object KeywordIndex ptsKw = sim.formatPointsInputs("Points", points, offset); InputAgent.storeAndExecute(new KeywordCommand(dispEnt, posKw, ptsKw)); controlStartResume.requestFocusInWindow(); } }; increaseZ = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/PlusZ-16.png"))); increaseZ.setMargin(margin); increaseZ.setFocusPainted(false); increaseZ.setRequestFocusEnabled(false); increaseZ.setToolTipText(formatToolTip("Move Up", "Increases the selected object's z-coordinate by one hundredth of the snap-grid " + "spacing. By moving the object closer to the camera, it will appear on top of " + "other objects with smaller z-coordinates.")); increaseZ.setActionCommand("Up"); increaseZ.addActionListener( actionListener ); decreaseZ = new JButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/MinusZ-16.png"))); decreaseZ.setMargin(margin); decreaseZ.setFocusPainted(false); decreaseZ.setRequestFocusEnabled(false); decreaseZ.setToolTipText(formatToolTip("Move Down", "Decreases the selected object's z-coordinate by one hundredth of the snap-grid " + "spacing. By moving the object farther from the camera, it will appear below " + "other objects with larger z-coordinates.")); decreaseZ.setActionCommand("Down"); decreaseZ.addActionListener( actionListener ); buttonBar.add( increaseZ ); buttonBar.add( decreaseZ ); } private void addOutlineButton(JToolBar buttonBar, Insets margin) { outline = new JToggleButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/Outline-16.png"))); outline.setMargin(margin); outline.setFocusPainted(false); outline.setRequestFocusEnabled(false); outline.setToolTipText(formatToolTip("Show Outline", "Shows the outline.")); outline.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof LineEntity)) return; LineEntity lineEnt = (LineEntity) selectedEntity; lineWidth.setEnabled(outline.isSelected()); lineColour.setEnabled(outline.isSelected()); if (lineEnt.isOutlined() == outline.isSelected()) return; KeywordIndex kw = InputAgent.formatBoolean("Outlined", outline.isSelected()); InputAgent.storeAndExecute(new KeywordCommand((Entity)lineEnt, kw)); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( outline ); } private void addLineWidthSpinner(JToolBar buttonBar, Insets margin) { SpinnerNumberModel numberModel = new SpinnerNumberModel(1, 1, 10, 1); lineWidth = new JSpinner(numberModel); lineWidth.addChangeListener(new ChangeListener() { @Override public void stateChanged( ChangeEvent e ) { if (!(selectedEntity instanceof LineEntity)) return; LineEntity lineEnt = (LineEntity) selectedEntity; int val = (int) lineWidth.getValue(); if (val == lineEnt.getLineWidth()) return; KeywordIndex kw = InputAgent.formatIntegers("LineWidth", val); InputAgent.storeAndExecute(new KeywordCommand((Entity)lineEnt, kw)); } }); lineWidth.setToolTipText(formatToolTip("Line Width", "Sets the width of the line in pixels.")); buttonBar.add( lineWidth ); } private void addLineColourButton(JToolBar buttonBar, Insets margin) { lineColourIcon = new ColorIcon(16, 16); lineColourIcon.setFillColor(Color.LIGHT_GRAY); lineColourIcon.setOutlineColor(Color.LIGHT_GRAY); lineColour = new JButton(lineColourIcon); lineColour.setMargin(margin); lineColour.setFocusPainted(false); lineColour.setRequestFocusEnabled(false); lineColour.setToolTipText(formatToolTip("Line Colour", "Sets the colour of the line.")); lineColour.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof LineEntity)) return; final LineEntity lineEnt = (LineEntity) selectedEntity; final Color4d presentColour = lineEnt.getLineColour(); ArrayList<Color4d> coloursInUse = GUIFrame.getLineColoursInUse(sim); ColourMenu menu = new ColourMenu(presentColour, coloursInUse, true) { @Override public void setColour(String colStr) { KeywordIndex kw = InputAgent.formatInput("LineColour", colStr); InputAgent.storeAndExecute(new KeywordCommand(selectedEntity, kw)); } }; menu.show(lineColour, 0, lineColour.getPreferredSize().height); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( lineColour ); } private void addFillButton(JToolBar buttonBar, Insets margin) { fill = new JToggleButton(new ImageIcon( GUIFrame.class.getResource("/resources/images/Fill-16.png"))); fill.setMargin(margin); fill.setFocusPainted(false); fill.setRequestFocusEnabled(false); fill.setToolTipText(formatToolTip("Show Fill", "Fills the entity with the selected colour.")); fill.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof FillEntity)) return; FillEntity fillEnt = (FillEntity) selectedEntity; fillColour.setEnabled(fill.isSelected()); if (fillEnt.isFilled() == fill.isSelected()) return; KeywordIndex kw = InputAgent.formatBoolean("Filled", fill.isSelected()); InputAgent.storeAndExecute(new KeywordCommand((Entity)fillEnt, kw)); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( fill ); } private void addFillColourButton(JToolBar buttonBar, Insets margin) { fillColourIcon = new ColorIcon(16, 16); fillColourIcon.setFillColor(Color.LIGHT_GRAY); fillColourIcon.setOutlineColor(Color.LIGHT_GRAY); fillColour = new JButton(fillColourIcon); fillColour.setMargin(margin); fillColour.setFocusPainted(false); fillColour.setRequestFocusEnabled(false); fillColour.setToolTipText(formatToolTip("Fill Colour", "Sets the colour of the fill.")); fillColour.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (!(selectedEntity instanceof FillEntity)) return; final FillEntity fillEnt = (FillEntity) selectedEntity; final Color4d presentColour = fillEnt.getFillColour(); ArrayList<Color4d> coloursInUse = GUIFrame.getFillColoursInUse(sim); ColourMenu menu = new ColourMenu(presentColour, coloursInUse, true) { @Override public void setColour(String colStr) { KeywordIndex kw = InputAgent.formatInput("FillColour", colStr); InputAgent.storeAndExecute(new KeywordCommand(selectedEntity, kw)); } }; menu.show(fillColour, 0, fillColour.getPreferredSize().height); controlStartResume.requestFocusInWindow(); } }); buttonBar.add( fillColour ); } // ****************************************************************************************************** // TOOL BAR // ****************************************************************************************************** /** * Sets up the Control Panel's main tool bar. */ public void initializeMainToolBars() { // Insets used in setting the tool bar components Insets noMargin = new Insets( 0, 0, 0, 0 ); Insets smallMargin = new Insets( 1, 1, 1, 1 ); // Initialize the main tool bar JToolBar mainToolBar = new JToolBar(); mainToolBar.setMargin( smallMargin ); mainToolBar.setFloatable(false); mainToolBar.setLayout( new FlowLayout( FlowLayout.LEFT, 0, 0 ) ); // Add the main tool bar to the display getContentPane().add( mainToolBar, BorderLayout.SOUTH ); // Run/pause button addRunButton(mainToolBar, noMargin); Dimension separatorDim = new Dimension(11, controlStartResume.getPreferredSize().height); Dimension gapDim = new Dimension(5, separatorDim.height); // Reset button mainToolBar.add(Box.createRigidArea(gapDim)); addResetButton(mainToolBar, noMargin); // Real time button mainToolBar.addSeparator(separatorDim); addRealTimeButton(mainToolBar, smallMargin); // Speed multiplier spinner mainToolBar.add(Box.createRigidArea(gapDim)); addSpeedMultiplier(mainToolBar, noMargin); // Pause time field mainToolBar.addSeparator(separatorDim); mainToolBar.add(new JLabel("Pause Time:")); mainToolBar.add(Box.createRigidArea(gapDim)); addPauseTime(mainToolBar, noMargin); // Simulation time display mainToolBar.addSeparator(separatorDim); addSimulationTime(mainToolBar, noMargin); // Run progress bar mainToolBar.add(Box.createRigidArea(gapDim)); addRunProgress(mainToolBar, noMargin); // Remaining time display mainToolBar.add(Box.createRigidArea(gapDim)); addRemainingTime(mainToolBar, noMargin); // Achieved speed multiplier mainToolBar.addSeparator(separatorDim); mainToolBar.add(new JLabel("Speed:")); addAchievedSpeedMultiplier(mainToolBar, noMargin); // Cursor position mainToolBar.addSeparator(separatorDim); mainToolBar.add(new JLabel("Position:")); addCursorPosition(mainToolBar, noMargin); } private void addRunButton(JToolBar mainToolBar, Insets margin) { runPressedIcon = new ImageIcon(GUIFrame.class.getResource("/resources/images/run-pressed-24.png")); pausePressedIcon = new ImageIcon(GUIFrame.class.getResource("/resources/images/pause-pressed-24.png")); controlStartResume = new RoundToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/run-24.png"))); controlStartResume.setRolloverEnabled(true); controlStartResume.setRolloverIcon(new ImageIcon(GUIFrame.class.getResource("/resources/images/run-rollover-24.png"))); controlStartResume.setPressedIcon(runPressedIcon); controlStartResume.setSelectedIcon( new ImageIcon(GUIFrame.class.getResource("/resources/images/pause-24.png"))); controlStartResume.setRolloverSelectedIcon( new ImageIcon(GUIFrame.class.getResource("/resources/images/pause-rollover-24.png"))); controlStartResume.setToolTipText(RUN_TOOLTIP); controlStartResume.setMargin(margin); controlStartResume.setEnabled( false ); controlStartResume.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { JToggleButton startResume = (JToggleButton)event.getSource(); startResume.setEnabled(false); if(startResume.isSelected()) { boolean bool = GUIFrame.this.startSimulation(); if (bool) { controlStartResume.setPressedIcon(pausePressedIcon); } else { startResume.setSelected(false); startResume.setEnabled(true); } } else { GUIFrame.this.pauseSimulation(); controlStartResume.setPressedIcon(runPressedIcon); } controlStartResume.requestFocusInWindow(); } } ); mainToolBar.add( controlStartResume ); // Listen for keyboard shortcuts for simulation speed controlStartResume.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_PERIOD) { // same as the '>' key if (!spinner.isEnabled()) return; spinner.setValue(spinner.getNextValue()); return; } if (e.getKeyCode() == KeyEvent.VK_COMMA) { // same as the '<' key if (!spinner.isEnabled()) return; spinner.setValue(spinner.getPreviousValue()); return; } } @Override public void keyReleased(KeyEvent e) {} }); } private void addResetButton(JToolBar mainToolBar, Insets margin) { controlStop = new RoundToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/reset-16.png"))); controlStop.setToolTipText(formatToolTip("Reset", "Resets the simulation run time to zero.")); controlStop.setPressedIcon(new ImageIcon(GUIFrame.class.getResource("/resources/images/reset-pressed-16.png"))); controlStop.setRolloverEnabled( true ); controlStop.setRolloverIcon(new ImageIcon(GUIFrame.class.getResource("/resources/images/reset-rollover-16.png"))); controlStop.setMargin(margin); controlStop.setEnabled( false ); controlStop.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (sim.getSimState() == JaamSimModel.SIM_STATE_RUNNING) { GUIFrame.this.pauseSimulation(); } controlStartResume.requestFocusInWindow(); boolean confirmed = GUIFrame.showConfirmStopDialog(); if (!confirmed) return; GUIFrame.this.stopSimulation(); initSpeedUp(0.0d); tickUpdate(0L); } } ); mainToolBar.add( controlStop ); } private void addRealTimeButton(JToolBar mainToolBar, Insets margin) { controlRealTime = new JToggleButton( " Real Time " ); controlRealTime.setToolTipText(formatToolTip("Real Time Mode", "When selected, the simulation runs at a fixed multiple of wall clock time.")); controlRealTime.setMargin(margin); controlRealTime.setFocusPainted(false); controlRealTime.setRequestFocusEnabled(false); controlRealTime.addActionListener(new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { boolean bool = ((JToggleButton)event.getSource()).isSelected(); KeywordIndex kw = InputAgent.formatBoolean("RealTime", bool); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); controlStartResume.requestFocusInWindow(); } }); mainToolBar.add( controlRealTime ); } private void addSpeedMultiplier(JToolBar mainToolBar, Insets margin) { SpinnerNumberModel numberModel = new SpinnerModel(Simulation.DEFAULT_REAL_TIME_FACTOR, Simulation.MIN_REAL_TIME_FACTOR, Simulation.MAX_REAL_TIME_FACTOR, 1); spinner = new JSpinner(numberModel); // show up to 6 decimal places JSpinner.NumberEditor numberEditor = new JSpinner.NumberEditor(spinner,"0.######"); spinner.setEditor(numberEditor); // make sure spinner TextField is no wider than 9 digits int diff = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().getPreferredSize().width - getPixelWidthOfString_ForFont("9", spinner.getFont()) * 9; Dimension dim = spinner.getPreferredSize(); dim.width -= diff; spinner.setPreferredSize(dim); spinner.addChangeListener(new ChangeListener() { @Override public void stateChanged( ChangeEvent e ) { Double val = (Double)((JSpinner)e.getSource()).getValue(); if (MathUtils.near(val, sim.getSimulation().getRealTimeFactor())) return; NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); DecimalFormat df = (DecimalFormat)nf; df.applyPattern("0.######"); KeywordIndex kw = InputAgent.formatArgs("RealTimeFactor", df.format(val)); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); controlStartResume.requestFocusInWindow(); } }); spinner.setToolTipText(formatToolTip("Speed Multiplier (&lt and &gt keys)", "Target ratio of simulation time to wall clock time when Real Time mode is selected.")); spinner.setEnabled(false); mainToolBar.add( spinner ); } private void addPauseTime(JToolBar mainToolBar, Insets margin) { pauseTime = new JTextField("0000-00-00T00:00:00") { @Override protected void processFocusEvent(FocusEvent fe) { if (fe.getID() == FocusEvent.FOCUS_LOST) { GUIFrame.this.setPauseTime(this.getText()); } else if (fe.getID() == FocusEvent.FOCUS_GAINED) { pauseTime.selectAll(); } super.processFocusEvent( fe ); } }; pauseTime.setPreferredSize(new Dimension(pauseTime.getPreferredSize().width, pauseTime.getPreferredSize().height)); pauseTime.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { GUIFrame.this.setPauseTime(pauseTime.getText()); controlStartResume.requestFocusInWindow(); } }); pauseTime.setText(""); pauseTime.setHorizontalAlignment(JTextField.RIGHT); pauseTime.setToolTipText(formatToolTip("Pause Time", "Time at which to pause the run, e.g. 3 h, 10 s, etc.")); mainToolBar.add(pauseTime); } private void addSimulationTime(JToolBar mainToolBar, Insets margin) { clockDisplay = new JLabel( "", JLabel.CENTER ); clockDisplay.setPreferredSize( new Dimension( 110, 16 ) ); clockDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); clockDisplay.setToolTipText(formatToolTip("Simulation Time", "The present simulation time")); mainToolBar.add( clockDisplay ); } private void addRunProgress(JToolBar mainToolBar, Insets margin) { progressBar = new JProgressBar( 0, 100 ); progressBar.setPreferredSize( new Dimension( 120, controlRealTime.getPreferredSize().height ) ); progressBar.setValue( 0 ); progressBar.setStringPainted( true ); progressBar.setToolTipText(formatToolTip("Run Progress", "Percent of the present simulation run that has been completed.")); mainToolBar.add( progressBar ); } private void addRemainingTime(JToolBar mainToolBar, Insets margin) { remainingDisplay = new JLabel( "", JLabel.CENTER ); remainingDisplay.setPreferredSize( new Dimension( 110, 16 ) ); remainingDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); remainingDisplay.setToolTipText(formatToolTip("Remaining Time", "The remaining time required to complete the present simulation run.")); mainToolBar.add( remainingDisplay ); } private void addAchievedSpeedMultiplier(JToolBar mainToolBar, Insets margin) { speedUpDisplay = new JLabel( "", JLabel.CENTER ); speedUpDisplay.setPreferredSize( new Dimension( 110, 16 ) ); speedUpDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); speedUpDisplay.setToolTipText(formatToolTip("Achieved Speed Multiplier", "The ratio of elapsed simulation time to elasped wall clock time that was achieved.")); mainToolBar.add( speedUpDisplay ); } private void addCursorPosition(JToolBar mainToolBar, Insets margin) { locatorPos = new JLabel( "", JLabel.CENTER ); locatorPos.setPreferredSize( new Dimension( 140, 16 ) ); locatorPos.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); locatorPos.setToolTipText(formatToolTip("Cursor Position", "The coordinates of the cursor on the x-y plane.")); mainToolBar.add( locatorPos ); } // ****************************************************************************************************** // RUN STATUS UPDATES // ****************************************************************************************************** private long resumeSystemTime; private long lastSystemTime; private double lastSimTime; private double speedUp; public void initSpeedUp(double simTime) { resumeSystemTime = System.currentTimeMillis(); lastSystemTime = resumeSystemTime; lastSimTime = simTime; } /** * Sets the values for the simulation time, run progress, speedup factor, * and remaining run time in the Control Panel's status bar. * * @param simTime - the present simulation time in seconds. */ void setClock(double simTime) { // Set the simulation time display String unit = getJaamSimModel().getDisplayedUnit(TimeUnit.class); double factor = getJaamSimModel().getDisplayedUnitFactor(TimeUnit.class); clockDisplay.setText(String.format("%,.2f %s", simTime/factor, unit)); // Set the run progress bar display long cTime = System.currentTimeMillis(); Simulation simulation = sim.getSimulation(); if (simulation == null) { setProgress(0); return; } double duration = simulation.getRunDuration() + simulation.getInitializationTime(); double timeElapsed = simTime - simulation.getStartTime(); int progress = (int)(timeElapsed * 100.0d / duration); this.setProgress(progress); // Do nothing further if the simulation is not executing events if (sim.getSimState() != JaamSimModel.SIM_STATE_RUNNING) return; // Set the speedup factor display if (cTime - lastSystemTime > 5000L || cTime - resumeSystemTime < 5000L) { long elapsedMillis = cTime - lastSystemTime; double elapsedSimTime = timeElapsed - lastSimTime; // Determine the speed-up factor speedUp = (elapsedSimTime * 1000.0d) / elapsedMillis; setSpeedUp(speedUp); if (elapsedMillis > 5000L) { lastSystemTime = cTime; lastSimTime = timeElapsed; } } // Set the remaining time display setRemaining( (duration - timeElapsed)/speedUp ); } /** * Displays the given value on the Control Panel's progress bar. * * @param val - the percent of the run that has completed. */ public void setProgress( int val ) { if (lastValue == val) return; progressBar.setValue( val ); progressBar.repaint(25); lastValue = val; if (sim.getSimState() >= JaamSimModel.SIM_STATE_CONFIGURED) { setTitle(sim, val); } } /** * Write the given value on the Control Panel's speed up factor box. * * @param val - the speed up factor to write. */ public void setSpeedUp( double val ) { if (val == 0.0) { speedUpDisplay.setText("-"); } else if (val >= 0.99) { speedUpDisplay.setText(String.format("%,.0f", val)); } else { speedUpDisplay.setText(String.format("%,.6f", val)); } } /** * Write the given value on the Control Panel's remaining run time box. * * @param val - the remaining run time in seconds. */ public void setRemaining( double val ) { if (val == 0.0) remainingDisplay.setText("-"); else if (val < 60.0) remainingDisplay.setText(String.format("%.0f seconds left", val)); else if (val < 3600.0) remainingDisplay.setText(String.format("%.1f minutes left", val/60.0)); else if (val < 3600.0*24.0) remainingDisplay.setText(String.format("%.1f hours left", val/3600.0)); else if (val < 3600.0*8760.0) remainingDisplay.setText(String.format("%.1f days left", val/(3600.0*24.0))); else remainingDisplay.setText(String.format("%.1f years left", val/(3600.0*8760.0))); } // ****************************************************************************************************** // SIMULATION CONTROLS // ****************************************************************************************************** /** * Starts or resumes the simulation run. * @return true if the simulation was started or resumed; false if cancel or close was selected */ public boolean startSimulation() { if (sim.getSimState() <= JaamSimModel.SIM_STATE_CONFIGURED) { boolean confirmed = true; if (sim.isSessionEdited()) { confirmed = GUIFrame.showSaveChangesDialog(this); } if (confirmed) { sim.start(); } return confirmed; } else if (sim.getSimState() == JaamSimModel.SIM_STATE_PAUSED) { sim.resume(sim.getSimulation().getPauseTime()); return true; } else throw new ErrorException( "Invalid Simulation State for Start/Resume" ); } /** * Pauses the simulation run. */ private void pauseSimulation() { if (sim.getSimState() == JaamSimModel.SIM_STATE_RUNNING) sim.pause(); else throw new ErrorException( "Invalid Simulation State for pause" ); } /** * Stops the simulation run. */ public void stopSimulation() { if (sim.getSimState() == JaamSimModel.SIM_STATE_RUNNING || sim.getSimState() == JaamSimModel.SIM_STATE_PAUSED || sim.getSimState() == JaamSimModel.SIM_STATE_ENDED) { sim.reset(); FrameBox.stop(); this.updateForSimulationState(JaamSimModel.SIM_STATE_CONFIGURED); } else throw new ErrorException( "Invalid Simulation State for stop" ); } public static void updateForSimState(int state) { GUIFrame inst = GUIFrame.getInstance(); if (inst == null) return; inst.updateForSimulationState(state); } /** * Sets the state of the simulation run to the given state value. * * @param state - an index that designates the state of the simulation run. */ void updateForSimulationState(int state) { sim.setSimState(state); switch (sim.getSimState()) { case JaamSimModel.SIM_STATE_LOADED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { if (fileMenu.getItem(i) == null) continue; fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < toolsMenu.getItemCount(); i++ ) { if (toolsMenu.getItem(i) == null) continue; toolsMenu.getItem(i).setEnabled(true); } speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); setSpeedUp(0); setRemaining(0); setProgress(0); controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText(RUN_TOOLTIP); controlStop.setEnabled( false ); controlStop.setSelected( false ); lockViewXYPlane.setEnabled( true ); progressBar.setEnabled( false ); break; case JaamSimModel.SIM_STATE_UNCONFIGURED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { if (fileMenu.getItem(i) == null) continue; fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < toolsMenu.getItemCount(); i++ ) { if (toolsMenu.getItem(i) == null) continue; toolsMenu.getItem(i).setEnabled(true); } speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); setSpeedUp(0); setRemaining(0); setProgress(0); controlStartResume.setEnabled( false ); controlStartResume.setSelected( false ); controlStop.setSelected( false ); controlStop.setEnabled( false ); lockViewXYPlane.setEnabled( true ); progressBar.setEnabled( false ); break; case JaamSimModel.SIM_STATE_CONFIGURED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { if (fileMenu.getItem(i) == null) continue; fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < toolsMenu.getItemCount(); i++ ) { if (toolsMenu.getItem(i) == null) continue; toolsMenu.getItem(i).setEnabled(true); } speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); setSpeedUp(0); setRemaining(0); setProgress(0); controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText(RUN_TOOLTIP); controlStop.setSelected( false ); controlStop.setEnabled( false ); lockViewXYPlane.setEnabled( true ); progressBar.setEnabled( true ); break; case JaamSimModel.SIM_STATE_RUNNING: speedUpDisplay.setEnabled( true ); remainingDisplay.setEnabled( true ); controlStartResume.setEnabled( true ); controlStartResume.setSelected( true ); controlStartResume.setToolTipText(PAUSE_TOOLTIP); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; case JaamSimModel.SIM_STATE_PAUSED: controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText(RUN_TOOLTIP); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; case JaamSimModel.SIM_STATE_ENDED: controlStartResume.setEnabled( false ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText(RUN_TOOLTIP); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; default: throw new ErrorException( "Unrecognized Graphics State" ); } fileMenu.setEnabled( true ); } @Override public void updateAll() { GUIFrame.updateUI(); } @Override public void updateObjectSelector() { ObjectSelector.allowUpdate(); GUIFrame.updateUI(); } @Override public void updateModelBuilder() { EntityPallet.update(); } private void clearButtons() { if (createLinks.isSelected()) createLinks.doClick(); if (reverseButton.isSelected()) reverseButton.doClick(); } public void updateControls() { Simulation simulation = sim.getSimulation(); if (simulation == null) return; updateControls(simulation); } public void updateControls(Simulation simulation) { updateSaveButton(); updateUndoButtons(); updateForRealTime(simulation.isRealTime(), simulation.getRealTimeFactor()); updateForPauseTime(simulation.getPauseTimeString()); update2dButton(); updateShowAxesButton(); updateShowGridButton(); updateNextPrevButtons(); updateFindButton(); updateFormatButtons(selectedEntity); updateForSnapToGrid(simulation.isSnapToGrid()); updateForSnapGridSpacing(simulation.getSnapGridSpacingString()); updateShowLabelsButton(simulation.isShowLabels()); updateShowSubModelsButton(simulation.isShowSubModels()); updateShowEntityFlowButton(simulation.isShowEntityFlow()); updateToolVisibilities(simulation); updateToolSizes(simulation); updateToolLocations(simulation); updateViewVisibilities(); updateViewSizes(); updateViewLocations(); setControlPanelWidth(simulation.getControlPanelWidth()); } private void updateSaveButton() { fileSave.setEnabled(sim.isSessionEdited()); } /** * updates RealTime button and Spinner */ private synchronized void updateForRealTime(boolean executeRT, double factorRT) { sim.getEventManager().setExecuteRealTime(executeRT, factorRT); controlRealTime.setSelected(executeRT); spinner.setValue(factorRT); spinner.setEnabled(executeRT); } /** * updates PauseTime entry */ private void updateForPauseTime(String str) { if (pauseTime.getText().equals(str) || pauseTime.isFocusOwner()) return; pauseTime.setText(str); } /** * Sets the PauseTime keyword for Simulation. * @param str - value to assign. */ private void setPauseTime(String str) { String prevVal = sim.getSimulation().getPauseTimeString(); if (prevVal.equals(str)) return; // If the time is in RFC8601 format, enclose in single quotes if (str.contains("-") || str.contains(":")) Parser.addQuotesIfNeeded(str); ArrayList<String> tokens = new ArrayList<>(); Parser.tokenize(tokens, str, true); // if we only got one token, and it isn't RFC8601 - add a unit if (tokens.size() == 1 && !tokens.get(0).contains("-") && !tokens.get(0).contains(":")) tokens.add(getJaamSimModel().getDisplayedUnit(TimeUnit.class)); try { // Parse the keyword inputs KeywordIndex kw = new KeywordIndex("PauseTime", tokens, null); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } catch (InputErrorException e) { pauseTime.setText(prevVal); GUIFrame.showErrorDialog("Input Error", e.getMessage()); } } /** * Assigns a new name to the given entity. * @param ent - entity to be renamed * @param newName - new absolute name for the entity */ @Override public void renameEntity(Entity ent, String newName) { // If the name has not changed, do nothing if (ent.getName().equals(newName)) return; // Check that the entity was defined AFTER the RecordEdits command if (!ent.isAdded()) throw new ErrorException("Cannot rename an entity that was defined before the RecordEdits command."); // Get the new local name String localName = newName; if (newName.contains(".")) { String[] names = newName.split("\\."); if (names.length == 0) throw new ErrorException(InputAgent.INP_ERR_BADNAME, localName); localName = names[names.length - 1]; names = Arrays.copyOf(names, names.length - 1); Entity parent = sim.getEntityFromNames(names); if (parent != ent.getParent()) throw new ErrorException("Cannot rename the entity's parent"); } // Check that the new name is valid if (!InputAgent.isValidName(localName)) throw new ErrorException(InputAgent.INP_ERR_BADNAME, localName); // Check that the new name does not conflict with another entity if (sim.getNamedEntity(newName) != null) throw new ErrorException(InputAgent.INP_ERR_DEFINEUSED, newName, sim.getNamedEntity(newName).getClass().getSimpleName()); // Rename the entity InputAgent.storeAndExecute(new RenameCommand(ent, newName)); } @Override public void deleteEntity(Entity ent) { if (ent.isGenerated()) throw new ErrorException("Cannot delete an entity that was generated by a simulation " + "object."); if (!ent.isAdded()) throw new ErrorException("Cannot delete an entity that was defined prior to " + "RecordEdits in the input file."); if (ent instanceof DisplayEntity && !((DisplayEntity) ent).isMovable()) throw new ErrorException("Cannot delete an entity that is not movable."); // Delete any child entities for (Entity child : ent.getChildren()) { if (child.isGenerated() || child instanceof EntityLabel) child.kill(); else deleteEntity(child); } // Region if (ent instanceof Region) { // Reset the Region input for the entities in this region KeywordIndex kw = InputAgent.formatArgs("Region"); for (DisplayEntity e : sim.getClonesOfIterator(DisplayEntity.class)) { if (e == ent || e.getInput("Region").getValue() != ent) continue; InputAgent.storeAndExecute(new CoordinateCommand(e, kw)); } } // DisplayEntity if (ent instanceof DisplayEntity) { DisplayEntity dEnt = (DisplayEntity) ent; // Kill the label EntityLabel label = EntityLabel.getLabel(dEnt); if (label != null) deleteEntity(label); // Reset the RelativeEntity input for entities KeywordIndex kw = InputAgent.formatArgs("RelativeEntity"); for (DisplayEntity e : sim.getClonesOfIterator(DisplayEntity.class)) { if (e == ent || e.getInput("RelativeEntity").getValue() != ent) continue; InputAgent.storeAndExecute(new CoordinateCommand(e, kw)); } } // Delete any references to this entity in the inputs to other entities for (Entity e : sim.getClonesOfIterator(Entity.class)) { if (e == ent) continue; ArrayList<KeywordIndex> oldKwList = new ArrayList<>(); ArrayList<KeywordIndex> newKwList = new ArrayList<>(); for (Input<?> in : e.getEditableInputs()) { ArrayList<String> oldTokens = in.getValueTokens(); boolean changed = in.removeReferences(ent); if (!changed) continue; KeywordIndex oldKw = new KeywordIndex(in.getKeyword(), oldTokens, null); KeywordIndex newKw = new KeywordIndex(in.getKeyword(), in.getValueTokens(), null); oldKwList.add(oldKw); newKwList.add(newKw); } // Reload any inputs that have changed so that redo/undo works correctly if (newKwList.isEmpty()) continue; KeywordIndex[] oldKws = new KeywordIndex[oldKwList.size()]; KeywordIndex[] newKws = new KeywordIndex[newKwList.size()]; oldKws = oldKwList.toArray(oldKws); newKws = newKwList.toArray(newKws); InputAgent.storeAndExecute(new KeywordCommand(e, 0, oldKws, newKws)); } // Execute the delete command InputAgent.storeAndExecute(new DeleteCommand(ent)); } @Override public void storeAndExecute(Command cmd) { synchronized (undoList) { if (!cmd.isChange()) return; // Execute the command and catch an error if it occurs cmd.execute(); // Attempt to merge the command with the previous one Command mergedCmd = null; if (!undoList.isEmpty()) { Command lastCmd = undoList.get(undoList.size() - 1); mergedCmd = lastCmd.tryMerge(cmd); } // If the new command can be combined, then change the entry for previous command if (mergedCmd != null) { if (mergedCmd.isChange()) undoList.set(undoList.size() - 1, mergedCmd); else undoList.remove(undoList.size() - 1); } // If the new command cannot be combined, then add it to the undo list else { undoList.add(cmd); } // Clear the re-do list redoList.clear(); } updateUI(); } public void undo() { synchronized (undoList) { if (undoList.isEmpty()) return; Command cmd = undoList.remove(undoList.size() - 1); redoList.add(cmd); cmd.undo(); } updateUI(); } public void redo() { synchronized (undoList) { if (redoList.isEmpty()) return; Command cmd = redoList.remove(redoList.size() - 1); undoList.add(cmd); cmd.execute(); } updateUI(); } public void undo(int n) { synchronized (undoList) { for (int i = 0; i < n; i++) { undo(); } } } public void redo(int n) { synchronized (undoList) { for (int i = 0; i < n; i++) { redo(); } } } public void invokeUndo() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { undo(); } }); } public void invokeRedo() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { redo(); } }); } public void updateUndoButtons() { synchronized (undoList) { undo.setEnabled(!undoList.isEmpty()); undoDropdown.setEnabled(!undoList.isEmpty()); undoMenuItem.setEnabled(!undoList.isEmpty()); redo.setEnabled(!redoList.isEmpty()); redoDropdown.setEnabled(!redoList.isEmpty()); redoMenuItem.setEnabled(!redoList.isEmpty()); } } public void clearUndoRedo() { synchronized (undoList) { undoList.clear(); redoList.clear(); } updateUI(); } private void updateForSnapGridSpacing(String str) { if (gridSpacing.getText().equals(str) || gridSpacing.hasFocus()) return; gridSpacing.setText(str); } private void setSnapGridSpacing(String str) { Input<?> in = sim.getSimulation().getInput("SnapGridSpacing"); String prevVal = in.getValueString(); if (prevVal.equals(str)) return; if (str.isEmpty()) { gridSpacing.setText(prevVal); return; } try { KeywordIndex kw = InputAgent.formatInput("SnapGridSpacing", str); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } catch (InputErrorException e) { gridSpacing.setText(prevVal); GUIFrame.showErrorDialog("Input Error", e.getMessage()); } } private void updateForSnapToGrid(boolean bool) { snapToGrid.setSelected(bool); gridSpacing.setEnabled(bool); } private void update2dButton() { if (!RenderManager.isGood()) return; View view = RenderManager.inst().getActiveView(); if (view == null) return; lockViewXYPlane.setSelected(view.is2DLocked()); } private void updateShowAxesButton() { DisplayEntity ent = (DisplayEntity) sim.getNamedEntity("XYZ-Axis"); xyzAxis.setSelected(ent != null && ent.getShow()); } private void updateShowGridButton() { DisplayEntity ent = (DisplayEntity) sim.getNamedEntity("XY-Grid"); grid.setSelected(ent != null && ent.getShow()); } private void updateNextPrevButtons() { if (selectedEntity != null && selectedEntity instanceof DisplayEntity) { boolean dir = !reverseButton.isSelected(); DisplayEntity selectedDEnt = (DisplayEntity) selectedEntity; prevButton.setEnabled(!selectedDEnt.getPreviousList(dir).isEmpty()); nextButton.setEnabled(!selectedDEnt.getNextList(dir).isEmpty()); return; } prevButton.setEnabled(false); nextButton.setEnabled(false); } private void updateFindButton() { boolean bool = FindBox.getInstance().isVisible(); find.setSelected(bool); } public static void setSelectedEntity(Entity ent) { if (instance == null) return; instance.setSelectedEnt(ent); } public void setSelectedEnt(Entity ent) { selectedEntity = ent; } private void updateFormatButtons(Entity ent) { updateEditButtons(ent); updateDisplayModelButtons(ent); updateClearFormattingButton(ent); updateTextButtons(ent); updateZButtons(ent); updateLineButtons(ent); updateFillButtons(ent); } private void updateEditButtons(Entity ent) { boolean bool = (ent != null && ent != sim.getSimulation()); copyButton.setEnabled(bool); copyMenuItem.setEnabled(bool); deleteMenuItem.setEnabled(bool); } public void updateDisplayModelButtons(Entity ent) { boolean bool = ent instanceof DisplayEntity && ((DisplayEntity)ent).isDisplayModelNominal() && ((DisplayEntity)ent).getDisplayModelList().size() == 1; dispModel.setEnabled(bool); modelSelector.setEnabled(bool); editDmButton.setEnabled(bool); if (!bool) { dispModel.setText(""); return; } DisplayEntity dispEnt = (DisplayEntity) ent; String name = dispEnt.getDisplayModelList().get(0).getName(); if (!dispModel.getText().equals(name)) dispModel.setText(name); } public void updateClearFormattingButton(Entity ent) { if (ent == null) { clearButton.setEnabled(false); return; } boolean bool = false; for (Input<?> in : ent.getEditableInputs()) { String cat = in.getCategory(); if (!cat.equals(Entity.FORMAT) && !cat.equals(Entity.FONT)) continue; if (!in.isDefault()) { bool = true; break; } } clearButton.setEnabled(bool); } private void updateTextButtons(Entity ent) { boolean bool = ent instanceof TextEntity; boolean isAlignable = bool && ent instanceof DisplayEntity && !(ent instanceof OverlayText) && !(ent instanceof BillboardText); alignLeft.setEnabled(isAlignable); alignCentre.setEnabled(isAlignable); alignRight.setEnabled(isAlignable); if (!isAlignable) { alignmentGroup.clearSelection(); } bold.setEnabled(bool); italic.setEnabled(bool); font.setEnabled(bool); fontSelector.setEnabled(bool); textHeight.setEnabled(bool); largerText.setEnabled(bool); smallerText.setEnabled(bool); fontColour.setEnabled(bool); if (!bool) { font.setText(""); textHeight.setText(null); bold.setSelected(false); italic.setSelected(false); colourIcon.setFillColor(Color.LIGHT_GRAY); colourIcon.setOutlineColor(Color.LIGHT_GRAY); return; } if (isAlignable) { int val = (int) Math.signum(((DisplayEntity) ent).getAlignment().x); alignLeft.setSelected(val == -1); alignCentre.setSelected(val == 0); alignRight.setSelected(val == 1); } TextEntity textEnt = (TextEntity) ent; bold.setSelected(textEnt.isBold()); italic.setSelected(textEnt.isItalic()); String fontName = textEnt.getFontName(); if (!font.getText().equals(fontName)) font.setText(fontName); updateTextHeight(textEnt.getTextHeightString()); Color4d col = textEnt.getFontColor(); colourIcon.setFillColor(new Color((float)col.r, (float)col.g, (float)col.b, (float)col.a)); colourIcon.setOutlineColor(Color.DARK_GRAY); fontColour.repaint(); } private void updateTextHeight(String str) { if (textHeight.getText().equals(str) || textHeight.hasFocus()) return; textHeight.setText(str); } private void updateZButtons(Entity ent) { boolean bool = ent instanceof DisplayEntity; bool = bool && !(ent instanceof OverlayEntity); bool = bool && !(ent instanceof BillboardText); increaseZ.setEnabled(bool); decreaseZ.setEnabled(bool); } private void updateLineButtons(Entity ent) { boolean bool = ent instanceof LineEntity; outline.setEnabled(bool && ent instanceof FillEntity); lineWidth.setEnabled(bool); lineColour.setEnabled(bool); if (!bool) { lineWidth.setValue(1); lineColourIcon.setFillColor(Color.LIGHT_GRAY); lineColourIcon.setOutlineColor(Color.LIGHT_GRAY); return; } LineEntity lineEnt = (LineEntity) ent; outline.setSelected(lineEnt.isOutlined()); lineWidth.setEnabled(lineEnt.isOutlined()); lineColour.setEnabled(lineEnt.isOutlined()); lineWidth.setValue(Integer.valueOf(lineEnt.getLineWidth())); Color4d col = lineEnt.getLineColour(); lineColourIcon.setFillColor(new Color((float)col.r, (float)col.g, (float)col.b, (float)col.a)); lineColourIcon.setOutlineColor(Color.DARK_GRAY); lineColour.repaint(); } private void updateFillButtons(Entity ent) { boolean bool = ent instanceof FillEntity; fill.setEnabled(bool); fillColour.setEnabled(bool); if (!bool) { fillColourIcon.setFillColor(Color.LIGHT_GRAY); fillColourIcon.setOutlineColor(Color.LIGHT_GRAY); return; } FillEntity fillEnt = (FillEntity) ent; fill.setSelected(fillEnt.isFilled()); fillColour.setEnabled(fillEnt.isFilled()); Color4d col = fillEnt.getFillColour(); fillColourIcon.setFillColor(new Color((float)col.r, (float)col.g, (float)col.b, (float)col.a)); fillColourIcon.setOutlineColor(Color.DARK_GRAY); fillColour.repaint(); } private void setTextHeight(String str) { if (!(selectedEntity instanceof TextEntity)) return; TextEntity textEnt = (TextEntity) selectedEntity; if (str.equals(textEnt.getTextHeightString())) return; try { KeywordIndex kw = InputAgent.formatInput("TextHeight", str); InputAgent.storeAndExecute(new KeywordCommand((Entity)textEnt, kw)); } catch (InputErrorException e) { textHeight.setText(textEnt.getTextHeightString()); GUIFrame.showErrorDialog("Input Error", e.getMessage()); } } public static ArrayList<Image> getWindowIcons() { return iconImages; } public void copyLocationToClipBoard(Vec3d pos) { String data = String.format("(%.3f, %.3f, %.3f)", pos.x, pos.y, pos.z); StringSelection stringSelection = new StringSelection(data); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents( stringSelection, null ); } public static void showLocatorPosition(Vec3d pos) { GUIFrame inst = GUIFrame.getInstance(); if (inst == null) return; inst.showLocator(pos); } private void showLocator(Vec3d pos) { if( pos == null ) { locatorPos.setText( "-" ); return; } String unit = getJaamSimModel().getDisplayedUnit(DistanceUnit.class); double factor = getJaamSimModel().getDisplayedUnitFactor(DistanceUnit.class); locatorPos.setText(String.format((Locale)null, "%.3f %.3f %.3f %s", pos.x/factor, pos.y/factor, pos.z/factor, unit)); } public void enableSave(boolean bool) { saveConfigurationMenuItem.setEnabled(bool); } /** * Sets variables used to determine the position and size of various * windows based on the size of the computer display being used. */ private void calcWindowDefaults() { Dimension guiSize = this.getSize(); Rectangle winSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); DEFAULT_GUI_WIDTH = winSize.width; COL1_WIDTH = 220; COL4_WIDTH = 520; int middleWidth = DEFAULT_GUI_WIDTH - COL1_WIDTH - COL4_WIDTH; COL2_WIDTH = Math.max(520, middleWidth / 2); COL3_WIDTH = Math.max(420, middleWidth - COL2_WIDTH); VIEW_WIDTH = DEFAULT_GUI_WIDTH - COL1_WIDTH; COL1_START = this.getX(); COL2_START = COL1_START + COL1_WIDTH; COL3_START = COL2_START + COL2_WIDTH; COL4_START = Math.min(COL3_START + COL3_WIDTH, winSize.width - COL4_WIDTH); HALF_TOP = (winSize.height - guiSize.height) / 2; HALF_BOTTOM = (winSize.height - guiSize.height - HALF_TOP); LOWER_HEIGHT = Math.min(250, (winSize.height - guiSize.height) / 3); VIEW_HEIGHT = winSize.height - guiSize.height - LOWER_HEIGHT; TOP_START = this.getY() + guiSize.height; BOTTOM_START = TOP_START + HALF_TOP; LOWER_START = TOP_START + VIEW_HEIGHT; } public void setShowLabels(boolean bool) { for (DisplayEntity ent : sim.getClonesOfIterator(DisplayEntity.class)) { if (!EntityLabel.canLabel(ent)) continue; EntityLabel.showTemporaryLabel(ent, bool); } } public void setShowSubModels(boolean bool) { for (CompoundEntity submodel : sim.getClonesOfIterator(CompoundEntity.class)) { submodel.showTemporaryComponents(bool); } } public void setShowEntityFlow(boolean bool) { if (!RenderManager.isGood()) return; RenderManager.inst().setShowLinks(bool); } private void updateShowLabelsButton(boolean bool) { if (showLabels.isSelected() == bool) return; showLabels.setSelected(bool); setShowLabels(bool); updateUI(); } private void updateShowSubModelsButton(boolean bool) { if (showSubModels.isSelected() == bool) return; showSubModels.setSelected(bool); setShowSubModels(bool); updateUI(); } private void updateShowEntityFlowButton(boolean bool) { if (showLinks.isSelected() == bool) return; showLinks.setSelected(bool); setShowEntityFlow(bool); updateUI(); } /** * Re-open any Tools windows that have been closed temporarily. */ public void showActiveTools(Simulation simulation) { EntityPallet.getInstance().setVisible(simulation.isModelBuilderVisible()); ObjectSelector.getInstance().setVisible(simulation.isObjectSelectorVisible()); EditBox.getInstance().setVisible(simulation.isInputEditorVisible()); OutputBox.getInstance().setVisible(simulation.isOutputViewerVisible()); PropertyBox.getInstance().setVisible(simulation.isPropertyViewerVisible()); LogBox.getInstance().setVisible(simulation.isLogViewerVisible()); if (!simulation.isEventViewerVisible()) { if (EventViewer.hasInstance()) EventViewer.getInstance().dispose(); return; } EventViewer.getInstance().setVisible(true); } /** * Closes all the Tools windows temporarily. */ public void closeAllTools() { EntityPallet.getInstance().setVisible(false); ObjectSelector.getInstance().setVisible(false); EditBox.getInstance().setVisible(false); OutputBox.getInstance().setVisible(false); PropertyBox.getInstance().setVisible(false); LogBox.getInstance().setVisible(false); if (EventViewer.hasInstance()) EventViewer.getInstance().setVisible(false); } public boolean isIconified() { return getExtendedState() == Frame.ICONIFIED; } private void updateToolVisibilities(Simulation simulation) { boolean iconified = isIconified(); setFrameVisibility(EntityPallet.getInstance(), !iconified && simulation.isModelBuilderVisible()); setFrameVisibility(ObjectSelector.getInstance(), !iconified && simulation.isObjectSelectorVisible()); setFrameVisibility(EditBox.getInstance(), !iconified && simulation.isInputEditorVisible()); setFrameVisibility(OutputBox.getInstance(), !iconified && simulation.isOutputViewerVisible()); setFrameVisibility(PropertyBox.getInstance(), !iconified && simulation.isPropertyViewerVisible()); setFrameVisibility(LogBox.getInstance(), !iconified && simulation.isLogViewerVisible()); if (!simulation.isEventViewerVisible()) { if (EventViewer.hasInstance()) EventViewer.getInstance().dispose(); return; } setFrameVisibility(EventViewer.getInstance(), !iconified); } private void setFrameVisibility(JFrame frame, boolean bool) { if (frame.isVisible() == bool) return; frame.setVisible(bool); if (bool) frame.toFront(); } public void updateToolSizes(Simulation simulation) { EntityPallet.getInstance().setSize(simulation.getModelBuilderSize().get(0), simulation.getModelBuilderSize().get(1)); ObjectSelector.getInstance().setSize(simulation.getObjectSelectorSize().get(0), simulation.getObjectSelectorSize().get(1)); EditBox.getInstance().setSize(simulation.getInputEditorSize().get(0), simulation.getInputEditorSize().get(1)); OutputBox.getInstance().setSize(simulation.getOutputViewerSize().get(0), simulation.getOutputViewerSize().get(1)); PropertyBox.getInstance().setSize(simulation.getPropertyViewerSize().get(0), simulation.getPropertyViewerSize().get(1)); LogBox.getInstance().setSize(simulation.getLogViewerSize().get(0), simulation.getLogViewerSize().get(1)); if (EventViewer.hasInstance()) { EventViewer.getInstance().setSize(simulation.getEventViewerSize().get(0), simulation.getEventViewerSize().get(1)); } } public void updateToolLocations(Simulation simulation) { setToolLocation(EntityPallet.getInstance(), simulation.getModelBuilderPos().get(0), simulation.getModelBuilderPos().get(1)); setToolLocation(ObjectSelector.getInstance(), simulation.getObjectSelectorPos().get(0), simulation.getObjectSelectorPos().get(1)); setToolLocation(EditBox.getInstance(), simulation.getInputEditorPos().get(0), simulation.getInputEditorPos().get(1)); setToolLocation(OutputBox.getInstance(), simulation.getOutputViewerPos().get(0), simulation.getOutputViewerPos().get(1)); setToolLocation(PropertyBox.getInstance(), simulation.getPropertyViewerPos().get(0), simulation.getPropertyViewerPos().get(1)); setToolLocation(LogBox.getInstance(), simulation.getLogViewerPos().get(0), simulation.getLogViewerPos().get(1)); if (EventViewer.hasInstance()) { setToolLocation(EventViewer.getInstance(), simulation.getEventViewerPos().get(0), simulation.getEventViewerPos().get(1)); } } public void setToolLocation(JFrame tool, int x, int y) { Point pt = getGlobalLocation(x, y); tool.setLocation(pt); } private void updateViewVisibilities() { if (!RenderManager.isGood()) return; boolean iconified = isIconified(); for (View v : views) { boolean isVisible = RenderManager.inst().isVisible(v); if (!iconified && v.showWindow()) { if (!isVisible) { RenderManager.inst().createWindow(v); } } else { if (isVisible) { RenderManager.inst().closeWindow(v); } } } } private void updateViewSizes() { for (View v : views) { final Frame window = RenderManager.getOpenWindowForView(v); if (window == null) continue; IntegerVector size = getWindowSize(v); window.setSize(size.get(0), size.get(1)); } } public void updateViewLocations() { for (View v : views) { final Frame window = RenderManager.getOpenWindowForView(v); if (window == null) continue; IntegerVector pos = getWindowPos(v); window.setLocation(pos.get(0), pos.get(1)); } } public void setControlPanelWidth(int width) { int height = getSize().height; setSize(width, height); } public void setWindowDefaults(Simulation simulation) { // Set the defaults from the AWT thread to avoid synchronization problems with updateUI and // the SizePosAdapter for the tool windows SwingUtilities.invokeLater(new Runnable() { @Override public void run() { simulation.setModelBuilderDefaults( COL1_START, TOP_START, COL1_WIDTH, HALF_TOP ); simulation.setObjectSelectorDefaults( COL1_START, BOTTOM_START, COL1_WIDTH, HALF_BOTTOM ); simulation.setInputEditorDefaults( COL2_START, LOWER_START, COL2_WIDTH, LOWER_HEIGHT); simulation.setOutputViewerDefaults( COL3_START, LOWER_START, COL3_WIDTH, LOWER_HEIGHT); simulation.setPropertyViewerDefaults( COL4_START, LOWER_START, COL4_WIDTH, LOWER_HEIGHT); simulation.setLogViewerDefaults( COL4_START, LOWER_START, COL4_WIDTH, LOWER_HEIGHT); simulation.setEventViewerDefaults( COL4_START, LOWER_START, COL4_WIDTH, LOWER_HEIGHT); simulation.setControlPanelWidthDefault(DEFAULT_GUI_WIDTH); View.setDefaultPosition(COL2_START, TOP_START); View.setDefaultSize(VIEW_WIDTH, VIEW_HEIGHT); updateControls(simulation); clearUndoRedo(); } }); } public ArrayList<View> getViews() { synchronized (views) { return views; } } @Override public void addView(View v) { synchronized (views) { views.add(v); } } @Override public void removeView(View v) { synchronized (views) { views.remove(v); } } @Override public void createWindow(View v) { if (!RenderManager.isGood()) return; RenderManager.inst().createWindow(v); } @Override public void closeWindow(View v) { if (!RenderManager.isGood()) return; RenderManager.inst().closeWindow(v); } @Override public int getNextViewID() { nextViewID++; return nextViewID; } private void resetViews() { synchronized (views) { views.clear(); for (View v : getJaamSimModel().getClonesOfIterator(View.class)) { views.add(v); } } } public IntegerVector getWindowPos(View v) { Point fix = OSFix.getLocationAdustment(); //FIXME IntegerVector ret = new IntegerVector(v.getWindowPos()); Point pt = getGlobalLocation(ret.get(0), ret.get(1)); ret.set(0, pt.x + fix.x); ret.set(1, pt.y + fix.y); return ret; } public IntegerVector getWindowSize(View v) { Point fix = OSFix.getSizeAdustment(); //FIXME IntegerVector ret = new IntegerVector(v.getWindowSize()); ret.addAt(fix.x, 0); ret.addAt(fix.y, 1); return ret; } public void setWindowPos(View v, int x, int y, int width, int height) { Point posFix = OSFix.getLocationAdustment(); Point sizeFix = OSFix.getSizeAdustment(); Point pt = getRelativeLocation(x - posFix.x, y - posFix.y); v.setWindowPos(pt.x, pt.y, width - sizeFix.x, height - sizeFix.y); } @Override public Vec3d getPOI(View v) { if (!RenderManager.isGood()) return new Vec3d(); return RenderManager.inst().getPOI(v); } // ****************************************************************************************************** // MAIN // ****************************************************************************************************** public static void main( String args[] ) { // Process the input arguments and filter out directives ArrayList<String> configFiles = new ArrayList<>(args.length); boolean batch = false; boolean minimize = false; boolean quiet = false; boolean scriptMode = false; boolean headless = false; for (String each : args) { // Batch mode if (each.equalsIgnoreCase("-b") || each.equalsIgnoreCase("-batch")) { batch = true; continue; } // Script mode (command line I/O) if (each.equalsIgnoreCase("-s") || each.equalsIgnoreCase("-script")) { scriptMode = true; continue; } // z-buffer offset if (each.equalsIgnoreCase("-z") || each.equalsIgnoreCase("-zbuffer")) { // Parse the option, but do nothing continue; } // Minimize model window if (each.equalsIgnoreCase("-m") || each.equalsIgnoreCase("-minimize")) { minimize = true; continue; } // Minimize model window if (each.equalsIgnoreCase("-h") || each.equalsIgnoreCase("-headless")) { headless = true; batch = true; continue; } // Do not open default windows if (each.equalsIgnoreCase("-q") || each.equalsIgnoreCase("-quiet")) { quiet = true; continue; } if (each.equalsIgnoreCase("-sg") || each.equalsIgnoreCase("-safe_graphics")) { SAFE_GRAPHICS = true; continue; } // Not a program directive, add to list of config files configFiles.add(each); } // If not running in batch mode, create the splash screen JWindow splashScreen = null; if (!batch) { URL splashImage = GUIFrame.class.getResource("/resources/images/splashscreen.png"); ImageIcon imageIcon = new ImageIcon(splashImage); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int splashX = (screen.width - imageIcon.getIconWidth()) / 2; int splashY = (screen.height - imageIcon.getIconHeight()) / 2; // Set the window's bounds, centering the window splashScreen = new JWindow(); splashScreen.setAlwaysOnTop(true); splashScreen.setBounds(splashX, splashY, imageIcon.getIconWidth(), imageIcon.getIconHeight()); // Build the splash screen splashScreen.getContentPane().add(new JLabel(imageIcon)); // Display it splashScreen.setVisible(true); } // create a graphic simulation LogBox.logLine("Loading Simulation Environment ... "); JaamSimModel simModel = getNextJaamSimModel(); simModel.autoLoad(); Simulation simulation = simModel.getSimulation(); GUIFrame gui = null; if (!headless) { gui = GUIFrame.createInstance(); } setJaamSimModel(simModel); if (!headless) { if (minimize) gui.setExtendedState(JFrame.ICONIFIED); // This is only here to initialize the static cache in the MRG1999a class to avoid future latency // when initializing other objects in drag+drop @SuppressWarnings("unused") MRG1999a cacher = new MRG1999a(); } if (!batch && !headless) { // Begin initializing the rendering system RenderManager.initialize(SAFE_GRAPHICS); } LogBox.logLine("Simulation Environment Loaded"); sim.setBatchRun(batch); sim.setScriptMode(scriptMode); // Show the Control Panel if (gui != null) { gui.setVisible(true); gui.calcWindowDefaults(); gui.setLocation(gui.getX(), gui.getY()); //FIXME remove when setLocation is fixed for Windows 10 gui.setWindowDefaults(simulation); } // Resolve all input arguments against the current working directory File user = new File(System.getProperty("user.dir")); // Process any configuration files passed on command line // (Multiple configuration files are not supported at present) for (int i = 0; i < configFiles.size(); i++) { //InputAgent.configure(gui, new File(configFiles.get(i))); File abs = new File((File)null, configFiles.get(i)); File loadFile; if (abs.exists()) loadFile = abs.getAbsoluteFile(); else loadFile = new File(user, configFiles.get(i)); Throwable t = GUIFrame.configure(loadFile); if (t != null) { // Hide the splash screen if (splashScreen != null) { splashScreen.dispose(); splashScreen = null; } handleConfigError(t, loadFile); } } // If in script mode, load a configuration file from standard in if (scriptMode) { BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); InputAgent.readBufferedStream(sim, buf, null, ""); } // If no configuration files were specified on the command line, then load the default configuration file if (configFiles.size() == 0 && !scriptMode) { // Load the default model from the AWT thread to avoid synchronization problems with updateUI and // setWindowDefaults SwingUtilities.invokeLater(new Runnable() { @Override public void run() { sim.setRecordEdits(true); InputAgent.loadDefault(sim); GUIFrame.updateForSimState(JaamSimModel.SIM_STATE_CONFIGURED); } }); } // If in batch or quiet mode, close the any tools that were opened if (quiet || batch) { if (gui != null) gui.closeAllTools(); } // Set RecordEdits mode (if it has not already been set in the configuration file) sim.setRecordEdits(true); // Start the model if in batch mode if (batch) { if (sim.getNumErrors() > 0) GUIFrame.shutdown(0); sim.start(); return; } // Hide the splash screen if (splashScreen != null) { splashScreen.dispose(); splashScreen = null; } // Bring the Control Panel to the front (along with any open Tools) if (gui != null) gui.toFront(); // Set the selected entity to the Simulation object FrameBox.setSelectedEntity(simulation, false); } /* * this class is created so the next value will be value * 2 and the * previous value will be value / 2 */ public static class SpinnerModel extends SpinnerNumberModel { private double value; public SpinnerModel( double val, double min, double max, double stepSize) { super(val, min, max, stepSize); } @Override public Object getPreviousValue() { value = this.getNumber().doubleValue() / 2.0; if (value >= 1.0) value = Math.floor(value); // Avoid going beyond limit Double min = (Double)this.getMinimum(); if (min.doubleValue() > value) { return min; } return value; } @Override public Object getNextValue() { value = this.getNumber().doubleValue() * 2.0; if (value >= 1.0) value = Math.floor(value); // Avoid going beyond limit Double max = (Double)this.getMaximum(); if (max.doubleValue() < value) { return max; } return value; } } public static boolean getShuttingDownFlag() { return shuttingDown.get(); } public static void shutdown(int errorCode) { shuttingDown.set(true); if (RenderManager.isGood()) { RenderManager.inst().shutdown(); } System.exit(errorCode); } @Override public void exit(int errorCode) { shutdown(errorCode); } volatile long simTicks; private static class UIUpdater implements Runnable { private final GUIFrame frame; UIUpdater(GUIFrame gui) { frame = gui; } @Override public void run() { EventManager evt = GUIFrame.getJaamSimModel().getEventManager(); double callBackTime = evt.ticksToSeconds(frame.simTicks); frame.setClock(callBackTime); frame.updateControls(); FrameBox.updateEntityValues(callBackTime); } } @Override public void tickUpdate(long tick) { if (tick == simTicks) return; simTicks = tick; RenderManager.updateTime(tick); GUIFrame.updateUI(); } @Override public void timeRunning() { EventManager evt = EventManager.current(); long tick = evt.getTicks(); boolean running = evt.isRunning(); if (running) { initSpeedUp(evt.ticksToSeconds(tick)); updateForSimulationState(JaamSimModel.SIM_STATE_RUNNING); } else { int state = JaamSimModel.SIM_STATE_PAUSED; if (!sim.getSimulation().canResume(simTicks)) state = JaamSimModel.SIM_STATE_ENDED; updateForSimulationState(state); } } @Override public void handleInputError(Throwable t, Entity ent) { InputAgent.logMessage(sim, "Validation Error - %s: %s", ent.getName(), t.getMessage()); GUIFrame.showErrorDialog("Input Error", "JaamSim has detected the following input error during validation:", String.format("%s: %-70s", ent.getName(), t.getMessage()), "The error must be corrected before the simulation can be started."); GUIFrame.updateForSimState(JaamSimModel.SIM_STATE_CONFIGURED); } @Override public void handleError(Throwable t) { if (t instanceof OutOfMemoryError) { OutOfMemoryError e = (OutOfMemoryError)t; InputAgent.logMessage(sim, "Out of Memory use the -Xmx flag during execution for more memory"); InputAgent.logMessage(sim, "Further debug information:"); InputAgent.logMessage(sim, "%s", e.getMessage()); InputAgent.logStackTrace(sim, t); GUIFrame.shutdown(1); return; } else { EventManager evt = EventManager.current(); long currentTick = evt.getTicks(); double curSec = evt.ticksToSeconds(currentTick); InputAgent.logMessage(sim, "EXCEPTION AT TIME: %f s", curSec); InputAgent.logMessage(sim, "%s", t.getMessage()); if (t.getCause() != null) { InputAgent.logMessage(sim, "Call Stack of original exception:"); InputAgent.logStackTrace(sim, t.getCause()); } InputAgent.logMessage(sim, "Thrown exception call stack:"); InputAgent.logStackTrace(sim, t); } String msg = t.getMessage(); if (msg == null) msg = "null"; String source = ""; int pos = -1; if (t instanceof InputErrorException) { source = ((InputErrorException) t).source; pos = ((InputErrorException) t).position; } if (t instanceof ErrorException) { source = ((ErrorException) t).source; pos = ((ErrorException) t).position; } GUIFrame.showErrorDialog("Runtime Error", source, pos, "JaamSim has detected the following runtime error condition:", msg, "Programmers can find more information by opening the Log Viewer.\n" + "The simulation run must be reset to zero simulation time before it " + "can be restarted."); } void newModel() { // Create the new JaamSimModel and load the default objects and inputs JaamSimModel simModel = getNextJaamSimModel(); simModel.autoLoad(); setWindowDefaults(simModel.getSimulation()); // Set the Control Panel to the new JaamSimModel and reset the user interface setJaamSimModel(simModel); clear(); // Load the default model sim.setRecordEdits(true); InputAgent.loadDefault(sim); FrameBox.setSelectedEntity(sim.getSimulation(), false); } void load() { LogBox.logLine("Loading..."); // Create a file chooser final JFileChooser chooser = new JFileChooser(getConfigFolder()); // Set the file extension filters chooser.setAcceptAllFileFilterUsed(true); FileNameExtensionFilter cfgFilter = new FileNameExtensionFilter("JaamSim Configuration File (*.cfg)", "CFG"); chooser.addChoosableFileFilter(cfgFilter); chooser.setFileFilter(cfgFilter); // Show the file chooser and wait for selection int returnVal = chooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File chosenfile = chooser.getSelectedFile(); // Delete the present JaamSimModel if it is unedited and unsaved if (sim.getConfigFile() == null && !sim.isSessionEdited()) simList.remove(sim); // Create the new JaamSimModel and load the default objects and inputs JaamSimModel simModel = new JaamSimModel(chosenfile.getName()); simModel.autoLoad(); setWindowDefaults(simModel.getSimulation()); // Set the Control Panel to the new JaamSimModel and reset the user interface setJaamSimModel(simModel); clear(); // Load the selected input file SwingUtilities.invokeLater(new Runnable() { @Override public void run() { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); sim.setRecordEdits(false); Throwable ret = GUIFrame.configure(chosenfile); if (ret != null) { setCursor(Cursor.getDefaultCursor()); handleConfigError(ret, chosenfile); } sim.setRecordEdits(true); resetViews(); FrameBox.setSelectedEntity(sim.getSimulation(), false); setCursor(Cursor.getDefaultCursor()); } }); setConfigFolder(chosenfile.getParent()); } } static Throwable configure(File file) { GUIFrame.updateForSimState(JaamSimModel.SIM_STATE_UNCONFIGURED); Throwable ret = null; try { sim.configure(file); } catch (Throwable t) { ret = t; } if (ret == null) LogBox.logLine("Configuration File Loaded"); else LogBox.logLine("Configuration File Loaded - errors found"); // show the present state in the user interface GUIFrame gui = GUIFrame.getInstance(); if (gui != null) { gui.setProgress(0); gui.setTitle(sim); gui.updateForSimulationState(JaamSimModel.SIM_STATE_CONFIGURED); gui.enableSave(sim.isRecordEditsFound()); } return ret; } static void handleConfigError(Throwable t, File file) { if (t instanceof InputErrorException) { InputAgent.logMessage(sim, "Input Error: %s", t.getMessage()); GUIFrame.showErrorOptionDialog("Input Error", String.format("Input errors were detected while loading file: '%s'\n\n" + "%s\n\n" + "Open '%s' with Log Viewer?", file.getName(), t.getMessage(), sim.getRunName() + ".log")); return; } InputAgent.logMessage(sim, "Fatal Error while loading file '%s': %s\n", file.getName(), t.getMessage()); GUIFrame.showErrorDialog("Fatal Error", String.format("A fatal error has occured while loading the file '%s':", file.getName()), t.getMessage(), ""); } /** * Saves the configuration file. * @param file = file to be saved */ private void setSaveFile(File file) { try { sim.save(file); // Set the title bar to match the new run name setTitle(sim); } catch (Exception e) { GUIFrame.showErrorDialog("File Error", e.getMessage()); } } boolean save() { LogBox.logLine("Saving..."); if( sim.getConfigFile() != null ) { setSaveFile(sim.getConfigFile()); updateUI(); return true; } boolean confirmed = saveAs(); return confirmed; } boolean saveAs() { LogBox.logLine("Save As..."); // Create a file chooser final JFileChooser chooser = new JFileChooser(getConfigFolder()); // Set the file extension filters chooser.setAcceptAllFileFilterUsed(true); FileNameExtensionFilter cfgFilter = new FileNameExtensionFilter("JaamSim Configuration File (*.cfg)", "CFG"); chooser.addChoosableFileFilter(cfgFilter); chooser.setFileFilter(cfgFilter); chooser.setSelectedFile(sim.getConfigFile()); // Show the file chooser and wait for selection int returnVal = chooser.showSaveDialog(this); if (returnVal != JFileChooser.APPROVE_OPTION) return false; File file = chooser.getSelectedFile(); // Add the file extension ".cfg" if needed String filePath = file.getPath(); filePath = filePath.trim(); if (file.getName().trim().indexOf('.') == -1) { filePath = filePath.concat(".cfg"); file = new File(filePath); } // Confirm overwrite if file already exists if (file.exists()) { boolean confirmed = GUIFrame.showSaveAsDialog(file.getName()); if (!confirmed) { return false; } } // Save the configuration file setSaveFile(file); setConfigFolder(file.getParent()); updateUI(); return true; } public void copyToClipboard(Entity ent) { if (ent == sim.getSimulation()) return; Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); clpbrd.setContents(new StringSelection(ent.getName()), null); } public Entity getEntityFromClipboard() { Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); try { String name = (String)clpbrd.getData(DataFlavor.stringFlavor); return sim.getNamedEntity(name); } catch (Throwable err) { return null; } } public void pasteEntityFromClipboard() { Entity ent = getEntityFromClipboard(); if (ent == null || ent == sim.getSimulation()) return; // Identify the region for the new entity Region region = null; if (selectedEntity != null && selectedEntity instanceof DisplayEntity && !(ent instanceof OverlayEntity)) { if (selectedEntity instanceof Region) region = (Region) selectedEntity; else region = ((DisplayEntity) selectedEntity).getCurrentRegion(); } // Create the new entity String copyName = ent.getName(); if (region != null && region.getParent() != sim.getSimulation()) copyName = region.getParent().getName() + "." + ent.getLocalName(); copyName = InputAgent.getUniqueName(sim, copyName, "_Copy"); InputAgent.storeAndExecute(new DefineCommand(sim, ent.getClass(), copyName)); // Copy the inputs Entity copiedEnt = sim.getNamedEntity(copyName); copiedEnt.copyInputs(ent); // Ensure that a random generator has a unique stream number if (copiedEnt instanceof RandomStreamUser) { RandomStreamUser rsu = (RandomStreamUser) copiedEnt; setUniqueRandomSeed(rsu); } // Set the region if (region != null) InputAgent.applyArgs(copiedEnt, "Region", region.getName()); // Set the position if (ent instanceof DisplayEntity) { DisplayEntity dEnt = (DisplayEntity) copiedEnt; // If an entity is not selected, paste the new entity at the point of interest if (selectedEntity == null || !(selectedEntity instanceof DisplayEntity) || selectedEntity instanceof Region) { if (RenderManager.isGood()) RenderManager.inst().dragEntityToMousePosition(dEnt); } // If an entity is selected, paste the new entity next to the selected one else { int x = 0; int y = 0; if (selectedEntity instanceof OverlayEntity) { OverlayEntity olEnt = (OverlayEntity) selectedEntity; x = olEnt.getScreenPosition().get(0) + 10; y = olEnt.getScreenPosition().get(1) + 10; } DisplayEntity selectedDispEnt = (DisplayEntity) selectedEntity; Vec3d pos = selectedDispEnt.getGlobalPosition(); pos.x += 0.5d * selectedDispEnt.getSize().x; pos.y -= 0.5d * selectedDispEnt.getSize().y; pos = dEnt.getLocalPosition(pos); if (sim.getSimulation().isSnapToGrid()) pos = sim.getSimulation().getSnapGridPosition(pos); try { dEnt.dragged(x, y, pos); } catch (InputErrorException e) {} } // Add a label if required if (sim.getSimulation().isShowLabels() && EntityLabel.canLabel(dEnt)) EntityLabel.showTemporaryLabel(dEnt, true); } // Copy the children copyChildren(ent, copiedEnt); // Select the new entity FrameBox.setSelectedEntity(copiedEnt, false); } public void copyChildren(Entity parent0, Entity parent1) { // Create the copied children for (Entity child : parent0.getChildren()) { if (child.isGenerated() || child instanceof EntityLabel) continue; // Construct the new child's name String localName = child.getLocalName(); String name = parent1.getName() + "." + localName; // Create the new child InputAgent.storeAndExecute(new DefineCommand(sim, child.getClass(), name)); // Add a label if necessary if (child instanceof DisplayEntity) { Entity copiedChild = parent1.getChild(localName); EntityLabel label = EntityLabel.getLabel((DisplayEntity) child); if (label != null) { EntityLabel newLabel = EntityLabel.createLabel((DisplayEntity) copiedChild); InputAgent.applyBoolean(newLabel, "Show", label.getShowInput()); newLabel.setShow(label.getShow()); } } } // Set the early and normal inputs for each child for (int seq = 0; seq < 2; seq++) { for (Entity child : parent0.getChildren()) { String localName = child.getLocalName(); Entity copiedChild = parent1.getChild(localName); copiedChild.copyInputs(child, seq, false); } } // Ensure that any random stream inputs have a unique stream number for (Entity copiedChild : parent1.getChildren()) { if (!(copiedChild instanceof RandomStreamUser)) continue; RandomStreamUser rsu = (RandomStreamUser) copiedChild; setUniqueRandomSeed(rsu); } // Copy each child's children for (Entity child : parent0.getChildren()) { String localName = child.getLocalName(); Entity copiedChild = parent1.getChild(localName); copyChildren(child, copiedChild); } } public void setUniqueRandomSeed(RandomStreamUser rsu) { Simulation simulation = sim.getSimulation(); int seed = rsu.getStreamNumber(); if (seed >= 0 && simulation.getRandomStreamUsers(seed).size() <= 1) return; seed = simulation.getLargestStreamNumber() + 1; String key = rsu.getStreamNumberKeyword(); InputAgent.applyIntegers((Entity) rsu, key, seed); } public void invokeNew() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { newModel(); } }); } public void invokeOpen() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { load(); } }); } public void invokeSave() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { save(); } }); } public void invokeSaveAs() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { saveAs(); } }); } public void invokeExit() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { close(); } }); } public void invokeCopy(Entity ent) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { copyToClipboard(ent); } }); } public void invokePaste() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { pasteEntityFromClipboard(); } }); } public void invokeFind() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { FindBox.getInstance().showDialog(); } }); } public void invokeHelp() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String topic = ""; if (selectedEntity != null) topic = selectedEntity.getObjectType().getName(); HelpBox.getInstance().showDialog(topic); } }); } public void invokeRunPause() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { controlStartResume.doClick(); } }); } public void invokeSimSpeedUp() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (!spinner.isEnabled()) return; spinner.setValue(spinner.getNextValue()); } }); } public void invokeSimSpeedDown() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (!spinner.isEnabled()) return; spinner.setValue(spinner.getPreviousValue()); } }); } public static String getConfigFolder() { Preferences prefs = Preferences.userRoot().node(instance.getClass().getName()); return prefs.get(LAST_USED_FOLDER, new File(".").getAbsolutePath()); } public static void setConfigFolder(String path) { Preferences prefs = Preferences.userRoot().node(instance.getClass().getName()); prefs.put(LAST_USED_FOLDER, path); } public static String getImageFolder() { Preferences prefs = Preferences.userRoot().node(instance.getClass().getName()); return prefs.get(LAST_USED_IMAGE_FOLDER, getConfigFolder()); } public static void setImageFolder(String path) { Preferences prefs = Preferences.userRoot().node(instance.getClass().getName()); prefs.put(LAST_USED_IMAGE_FOLDER, path); } public static String get3DFolder() { Preferences prefs = Preferences.userRoot().node(instance.getClass().getName()); return prefs.get(LAST_USED_3D_FOLDER, getConfigFolder()); } public static void set3DFolder(String path) { Preferences prefs = Preferences.userRoot().node(instance.getClass().getName()); prefs.put(LAST_USED_3D_FOLDER, path); } /** * Returns a list of the names of the files contained in the specified resource folder. * @param folder - name of the resource folder * @return names of the files in the folder */ public static ArrayList<String> getResourceFileNames(String folder) { ArrayList<String> ret = new ArrayList<>(); try { URI uri = GUIFrame.class.getResource(folder).toURI(); // When developing in an IDE if (uri.getScheme().equals("file")) { File dir = new File(uri.getPath()); for (File file : dir.listFiles()) { ret.add(file.getName()); } } // When running in a built jar or executable if (uri.getScheme().equals("jar")) { try { FileSystem fs = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap()); Path path = fs.getPath(folder); Stream<Path> walk = Files.walk(path, 1); for (Iterator<Path> it = walk.iterator(); it.hasNext();){ Path each = it.next(); String file = each.toString(); if (file.length() > folder.length()) { ret.add(file.substring(folder.length() + 1)); } } walk.close(); fs.close(); } catch (IOException e) {} } } catch (URISyntaxException e) {} return ret; } // ****************************************************************************************************** // DIALOG BOXES // ****************************************************************************************************** /** * Shows the "Confirm Save As" dialog box * @param fileName - name of the file to be saved * @return true if the file is to be overwritten. */ public static boolean showSaveAsDialog(String fileName) { int userOption = JOptionPane.showConfirmDialog(null, String.format("The file '%s' already exists.\n" + "Do you want to replace it?", fileName), "Confirm Save As", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); return (userOption == JOptionPane.YES_OPTION); } /** * Shows the "Confirm Stop" dialog box. * @return true if the run is to be stopped. */ public static boolean showConfirmStopDialog() { int userOption = JOptionPane.showConfirmDialog( null, "WARNING: Are you sure you want to reset the simulation time to 0?", "Confirm Reset", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); return (userOption == JOptionPane.YES_OPTION); } /** * Shows the "Save Changes" dialog box * @return true for any response other than Cancel or Close. */ public static boolean showSaveChangesDialog(GUIFrame gui) { String message; if (sim.getConfigFile() == null) message = "Do you want to save the changes you made?"; else message = String.format("Do you want to save the changes you made to '%s'?", sim.getConfigFile().getName()); Object[] options = {"Save", "Don't Save", "Cancel"}; int userOption = JOptionPane.showOptionDialog( null, message, "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if (userOption == JOptionPane.YES_OPTION) { boolean confirmed = gui.save(); return confirmed; } else if (userOption == JOptionPane.NO_OPTION) return true; return false; } private static String getErrorMessage(String source, int position, String pre, String message, String post) { StringBuilder sb = new StringBuilder(); sb.append("<html>"); // Initial text prior to the message if (!pre.isEmpty()) { sb.append(html_replace(pre)).append("<br><br>"); } // Error message if (!message.isEmpty()) { sb.append(html_replace(message)).append("<br>"); } // Append the source expression with the error shown in red if (source != null && !source.isEmpty()) { // Use the same font as the Input Builder so that the expression looks the same Font font = UIManager.getDefaults().getFont("TextArea.font"); String preStyle = String.format("<pre style=\"font-family: %s; font-size: %spt\">", font.getFamily(), font.getSize()); // Source expression sb.append(preStyle); sb.append(html_replace(source.substring(0, position))); sb.append("<font color=\"red\">"); sb.append(html_replace(source.substring(position))); sb.append("</font>"); sb.append("</pre>"); } // Final text after the message if (!post.isEmpty()) { if (source == null || source.isEmpty()) { sb.append("<br>"); } sb.append(html_replace(post)); } sb.append("</html>"); return sb.toString(); } /** * Displays the Error Message dialog box * @param title - text for the dialog box name * @param source - expression that cause the error (if applicable) * @param position - location of the error in the expression (if applicable) * @param pre - text to appear prior to the error message * @param message - error message * @param post - text to appear after the error message */ public static void showErrorDialog(String title, String source, int position, String pre, String message, String post) { if (sim == null || sim.isBatchRun()) GUIFrame.shutdown(1); JPanel panel = new JPanel(); panel.setLayout( new BorderLayout() ); // Use the standard font for dialog boxes Font messageFont = UIManager.getDefaults().getFont("OptionPane.messageFont"); // Message JTextPane msgPane = new JTextPane(); msgPane.setOpaque(false); msgPane.setFont(messageFont); msgPane.setText(pre + "\n\n" + message); panel.add(msgPane, BorderLayout.NORTH); // Source if (!source.isEmpty() && position != -1) { JTextPane srcPane = new JTextPane() { @Override public Dimension getPreferredScrollableViewportSize() { Dimension ret = getPreferredSize(); ret.width = Math.min(ret.width, 900); ret.height = Math.min(ret.height, 300); return ret; } }; srcPane.setContentType("text/html"); String msg = GUIFrame.getErrorMessage(source, position, "", "", ""); srcPane.setText(msg); JScrollPane scrollPane = new JScrollPane(srcPane); scrollPane.setBorder(new EmptyBorder(10, 0, 10, 0)); panel.add(scrollPane, BorderLayout.CENTER); } // Additional information JTextPane postPane = new JTextPane(); postPane.setOpaque(false); postPane.setFont(messageFont); postPane.setText(post); panel.add(postPane, BorderLayout.SOUTH); panel.setMinimumSize( new Dimension( 600, 300 ) ); JOptionPane.showMessageDialog(null, panel, title, JOptionPane.ERROR_MESSAGE); } public static void showErrorDialog(String title, String pre, String message, String post) { GUIFrame.showErrorDialog(title, "", -1, pre, message, post); } public static void showErrorDialog(String title, String message) { GUIFrame.showErrorDialog(title, "", -1, "", message, ""); } @Override public void invokeErrorDialogBox(String title, String msg) { GUIFrame.invokeErrorDialog(title, msg); } /** * Shows the Error Message dialog box from a non-Swing thread * @param title - text for the dialog box name * @param msg - error message */ public static void invokeErrorDialog(String title, String msg) { SwingUtilities.invokeLater(new RunnableError(title, msg)); } private static class RunnableError implements Runnable { private final String title; private final String message; public RunnableError(String t, String m) { title = t; message = m; } @Override public void run() { GUIFrame.showErrorDialog(title, message); } } /** * Shows the Error Message dialog box with option to open the Log Viewer * @param title - text for the dialog box name * @param msg - error message */ public static void showErrorOptionDialog(String title, String msg) { if (sim == null || sim.isBatchRun()) GUIFrame.shutdown(1); Object[] options = {"Yes", "No"}; int userOption = JOptionPane.showOptionDialog(null, msg, title, JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]); if (userOption == JOptionPane.YES_OPTION) { KeywordIndex kw = InputAgent.formatBoolean("ShowLogViewer", true); InputAgent.storeAndExecute(new KeywordCommand(sim.getSimulation(), kw)); } } /** * Shows the Error Message dialog box for the Input Editor * @param title - text for the dialog box name * @param source - input text * @param pos - index of the error in the input text * @param pre - text to appear before the error message * @param msg - error message * @param post - text to appear after the error message * @return true if the input is to be re-edited */ public static boolean showErrorEditDialog(String title, String source, int pos, String pre, String msg, String post) { String message = GUIFrame.getErrorMessage(source, pos, pre, msg, post); String[] options = { "Edit", "Reset" }; int reply = JOptionPane.showOptionDialog(null, message, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]); return (reply == JOptionPane.OK_OPTION); } // ****************************************************************************************************** // TOOL TIPS // ****************************************************************************************************** private static final Pattern amp = Pattern.compile("&"); private static final Pattern lt = Pattern.compile("<"); private static final Pattern gt = Pattern.compile(">"); private static final Pattern br = Pattern.compile("\n"); public static final String html_replace(String str) { String desc = str; desc = amp.matcher(desc).replaceAll("&amp;"); desc = lt.matcher(desc).replaceAll("&lt;"); desc = gt.matcher(desc).replaceAll("&gt;"); desc = br.matcher(desc).replaceAll("<BR>"); return desc; } /** * Returns the HTML code for pop-up tooltips in the Model Builder and Control Panel. * @param name - name of the item whose tooltip is to be generated * @param desc - text describing the item's function * @return HTML for the tooltip */ public static String formatToolTip(String name, String desc) { return String.format("<html><p width=\"200px\"><b>%s</b><br>%s</p></html>", name, desc); } /** * Returns the HTML code for a keyword's pop-up tooltip in the Input Editor. * @param className - object whose keyword tooltip is to be displayed * @param keyword - name of the keyword * @param description - description of the keyword * @param exampleList - a list of examples that show how the keyword can be used * @return HTML for the tooltip */ public static String formatKeywordToolTip(String className, String keyword, String description, String validInputs, String... exampleList) { StringBuilder sb = new StringBuilder("<html><p width=\"350px\">"); // Keyword name String key = html_replace(keyword); sb.append("<b>").append(key).append("</b><br>"); // Description String desc = html_replace(description); sb.append(desc).append("<br><br>"); // Valid Inputs if (validInputs != null) { sb.append(validInputs).append("<br><br>"); } // Examples if (exampleList.length > 0) { sb.append("<u>Examples:</u>"); } for (int i=0; i<exampleList.length; i++) { String item = html_replace(exampleList[i]); sb.append("<br>").append(item); } sb.append("</p></html>"); return sb.toString(); } /** * Returns the HTML code for an output's pop-up tooltip in the Output Viewer. * @param name - name of the output * @param description - description of the output * @return HTML for the tooltip */ public static String formatOutputToolTip(String name, String description) { String desc = html_replace(description); return String.format("<html><p width=\"250px\"><b>%s</b><br>%s</p></html>", name, desc); } /** * Returns the HTML code for an entity's pop-up tooltip in the Input Builder. * @param name - entity name * @param type - object type for the entity * @param description - description for the entity * @return HTML for the tooltip */ public static String formatEntityToolTip(String name, String type, String description) { String desc = html_replace(description); return String.format("<html><p width=\"250px\"><b>%s</b> (%s)<br>%s</p></html>", name, type, desc); } static ArrayList<Color4d> getFillColoursInUse(JaamSimModel simModel) { ArrayList<Color4d> ret = new ArrayList<>(); for (DisplayEntity ent : simModel.getClonesOfIterator(DisplayEntity.class, FillEntity.class)) { FillEntity fillEnt = (FillEntity) ent; if (ret.contains(fillEnt.getFillColour())) continue; ret.add(fillEnt.getFillColour()); } Collections.sort(ret, ColourInput.colourComparator); return ret; } static ArrayList<Color4d> getLineColoursInUse(JaamSimModel simModel) { ArrayList<Color4d> ret = new ArrayList<>(); for (DisplayEntity ent : simModel.getClonesOfIterator(DisplayEntity.class, LineEntity.class)) { LineEntity lineEnt = (LineEntity) ent; if (ret.contains(lineEnt.getLineColour())) continue; ret.add(lineEnt.getLineColour()); } Collections.sort(ret, ColourInput.colourComparator); return ret; } static ArrayList<String> getFontsInUse(JaamSimModel simModel) { ArrayList<String> ret = new ArrayList<>(); for (DisplayEntity ent : simModel.getClonesOfIterator(DisplayEntity.class, TextEntity.class)) { TextEntity textEnt = (TextEntity) ent; if (ret.contains(textEnt.getFontName())) continue; ret.add(textEnt.getFontName()); } Collections.sort(ret); return ret; } static ArrayList<Color4d> getFontColoursInUse(JaamSimModel simModel) { ArrayList<Color4d> ret = new ArrayList<>(); for (DisplayEntity ent : simModel.getClonesOfIterator(DisplayEntity.class, TextEntity.class)) { TextEntity textEnt = (TextEntity) ent; if (ret.contains(textEnt.getFontColor())) continue; ret.add(textEnt.getFontColor()); } Collections.sort(ret, ColourInput.colourComparator); return ret; } }
JS: use arrow keys with menus for 'Font Colour', 'Line Colour', and 'Fill Colour' buttons Signed-off-by: Harry King <[email protected]>
src/main/java/com/jaamsim/ui/GUIFrame.java
JS: use arrow keys with menus for 'Font Colour', 'Line Colour', and 'Fill Colour' buttons
<ide><path>rc/main/java/com/jaamsim/ui/GUIFrame.java <ide> public void setColour(String colStr) { <ide> KeywordIndex kw = InputAgent.formatInput("FontColour", colStr); <ide> InputAgent.storeAndExecute(new KeywordCommand(selectedEntity, kw)); <add> controlStartResume.requestFocusInWindow(); <ide> } <ide> <ide> }; <ide> fontMenu.show(fontColour, 0, fontColour.getPreferredSize().height); <del> controlStartResume.requestFocusInWindow(); <ide> } <ide> }); <ide> <ide> public void setColour(String colStr) { <ide> KeywordIndex kw = InputAgent.formatInput("LineColour", colStr); <ide> InputAgent.storeAndExecute(new KeywordCommand(selectedEntity, kw)); <add> controlStartResume.requestFocusInWindow(); <ide> } <ide> <ide> }; <ide> menu.show(lineColour, 0, lineColour.getPreferredSize().height); <del> controlStartResume.requestFocusInWindow(); <ide> } <ide> }); <ide> <ide> public void setColour(String colStr) { <ide> KeywordIndex kw = InputAgent.formatInput("FillColour", colStr); <ide> InputAgent.storeAndExecute(new KeywordCommand(selectedEntity, kw)); <add> controlStartResume.requestFocusInWindow(); <ide> } <ide> <ide> }; <ide> menu.show(fillColour, 0, fillColour.getPreferredSize().height); <del> controlStartResume.requestFocusInWindow(); <ide> } <ide> }); <ide>
Java
lgpl-2.1
fb9337928d9575a619f2dbd3d718b741da905a22
0
xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.model.reference; import java.beans.Transient; import java.io.Serializable; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import javax.inject.Provider; import org.xwiki.component.util.DefaultParameterizedType; import org.xwiki.model.EntityType; /** * Represents a reference to a document (wiki, space and document names). * * @version $Id$ * @since 2.2M1 */ public class DocumentReference extends AbstractLocalizedEntityReference { /** * The {@link Type} for a {@code Provider<DocumentReference>}. * * @since 7.2M1 */ public static final Type TYPE_PROVIDER = new DefaultParameterizedType(null, Provider.class, DocumentReference.class); /** * Parameter key for the locale. */ static final String LOCALE = AbstractLocalizedEntityReference.LOCALE; /** * Cache the {@link LocalDocumentReference} corresponding to this {@link DocumentReference}. */ private LocalDocumentReference localDocumentReference; /** * Special constructor that transforms a generic entity reference into a {@link DocumentReference}. It checks the * validity of the passed reference (ie correct type and correct parent). * * @param reference the reference to convert * @exception IllegalArgumentException if the passed reference is not a valid document reference */ public DocumentReference(EntityReference reference) { super(reference); } /** * Clone an DocumentReference, but replace one of the parent in the chain by a new one. * * @param reference the reference that is cloned * @param oldReference the old parent that will be replaced * @param newReference the new parent that will replace oldReference in the chain * @since 3.3M2 */ protected DocumentReference(EntityReference reference, EntityReference oldReference, EntityReference newReference) { super(reference, oldReference, newReference); } /** * Clone the provided reference and change the Locale. * * @param reference the reference to clone * @param locale the new locale for this reference, if null, locale is removed * @exception IllegalArgumentException if the passed reference is not a valid document reference */ public DocumentReference(EntityReference reference, Locale locale) { super(reference, locale); } /** * Create a new Document reference from wiki, space and page name. * * @param wikiName the name of the wiki containing the document, must not be null * @param spaceName the name of the space containing the document, must not be null * @param pageName the name of the document */ public DocumentReference(String wikiName, String spaceName, String pageName) { this(pageName, new SpaceReference(spaceName, new WikiReference(wikiName))); } /** * Create a new Document reference from wiki name, space name, page name and locale. * * @param wikiName the name of the wiki containing the document, must not be null * @param spaceName the name of the space containing the document, must not be null * @param pageName the name of the document * @param locale the locale of the document reference, may be null */ public DocumentReference(String wikiName, String spaceName, String pageName, Locale locale) { this(pageName, new SpaceReference(spaceName, new WikiReference(wikiName)), locale); } /** * Create a new Document reference from wiki name, space name, page name and language. This is an helper function * during transition from language to locale, it will be deprecated ASAP. * * @param wikiName the name of the wiki containing the document, must not be null * @param spaceName the name of the space containing the document, must not be null * @param pageName the name of the document * @param language the language of the document reference, may be null */ public DocumentReference(String wikiName, String spaceName, String pageName, String language) { this(pageName, new SpaceReference(spaceName, new WikiReference(wikiName)), (language == null) ? null : new Locale(language)); } /** * Create a new Document reference from wiki name, spaces names and page name. * * @param wikiName the name of the wiki containing the document, must not be null * @param spaceNames an ordered list of the names of the spaces containing the document from root space to last one, * must not be null * @param pageName the name of the document */ public DocumentReference(String wikiName, List<String> spaceNames, String pageName) { super(pageName, EntityType.DOCUMENT, new SpaceReference(wikiName, spaceNames)); } /** * Create a new Document reference from wiki name, spaces names, page name and locale. * * @param wikiName the name of the wiki containing the document, must not be null * @param spaceNames an ordered list of the names of the spaces containing the document from root space to last one, * must not be null * @param pageName the name of the document reference * @param locale the locale of the document reference, may be null */ public DocumentReference(String wikiName, List<String> spaceNames, String pageName, Locale locale) { super(pageName, EntityType.DOCUMENT, new SpaceReference(wikiName, spaceNames), locale); } /** * Create a new Document reference from document name and parent space. * * @param pageName the name of the document * @param parent the parent space for the document */ public DocumentReference(String pageName, SpaceReference parent) { super(pageName, EntityType.DOCUMENT, parent); } /** * Create a new Document reference from local document reference and wiki reference. * * @param localDocumentReference the document reference without the wiki reference * @param wikiReference the wiki reference * @since 5.1M1 */ public DocumentReference(LocalDocumentReference localDocumentReference, WikiReference wikiReference) { super(localDocumentReference, null, wikiReference); } /** * Create a new Document reference from document name, parent space and locale. * * @param pageName the name of the document * @param parent the parent space for the document * @param locale the locale of the document reference, may be null */ public DocumentReference(String pageName, SpaceReference parent, Locale locale) { super(pageName, EntityType.DOCUMENT, parent, locale); } /** * @param pageName the name of the document * @param parent the parent space for the document * @param parameters parameters for this reference, may be null * @since 10.6RC1 */ public DocumentReference(String pageName, EntityReference parent, Map<String, Serializable> parameters) { super(pageName, EntityType.DOCUMENT, parent, parameters); } /** * Clone an DocumentReference, but use the specified parent for its new parent. * * @param reference the reference to clone * @param parent the new parent to use * @since 10.8RC1 */ public DocumentReference(EntityReference reference, EntityReference parent) { super(reference, parent); } /** * {@inheritDoc} * <p> * Overridden in order to verify the validity of the passed parent. * </p> * * @see org.xwiki.model.reference.EntityReference#setParent(EntityReference) * @exception IllegalArgumentException if the passed parent is not a valid document reference parent (ie a space * reference) */ @Override protected void setParent(EntityReference parent) { if (parent instanceof SpaceReference) { super.setParent(parent); return; } if (parent == null || parent.getType() != EntityType.SPACE) { throw new IllegalArgumentException("Invalid parent reference [" + parent + "] in a document reference"); } super.setParent(new SpaceReference(parent)); } /** * {@inheritDoc} * <p> * Overridden in order to verify the validity of the passed type. * </p> * * @see org.xwiki.model.reference.EntityReference#setType(org.xwiki.model.EntityType) * @exception IllegalArgumentException if the passed type is not a document type */ @Override protected void setType(EntityType type) { if (type != EntityType.DOCUMENT) { throw new IllegalArgumentException("Invalid type [" + type + "] for a document reference"); } super.setType(EntityType.DOCUMENT); } /** * @return the wiki reference of this document reference */ @Transient public WikiReference getWikiReference() { return (WikiReference) extractReference(EntityType.WIKI); } /** * Create a new DocumentReference with passed wiki reference. * * @param wikiReference the wiki reference to use * @return a new document reference or the same if the passed wiki is already the current wiki * @since 7.2M1 */ @Transient public DocumentReference setWikiReference(WikiReference wikiReference) { WikiReference currentWikiReference = getWikiReference(); if (currentWikiReference.equals(wikiReference)) { return this; } return new DocumentReference(this, currentWikiReference, wikiReference); } /** * @return the space reference of the last space containing this document */ @Transient public SpaceReference getLastSpaceReference() { return (SpaceReference) extractReference(EntityType.SPACE); } /** * @return space references of this document in an ordered list */ @Transient public List<SpaceReference> getSpaceReferences() { List<SpaceReference> references = new ArrayList<SpaceReference>(); EntityReference reference = this; while (reference != null) { if (reference.getType() == EntityType.SPACE) { references.add((SpaceReference) reference); } reference = reference.getParent(); } // Reverse the array so that the last entry is the parent of the Document Reference Collections.reverse(references); return references; } @Override public DocumentReference replaceParent(EntityReference oldParent, EntityReference newParent) { if (newParent == oldParent) { return this; } return new DocumentReference(this, oldParent, newParent); } @Override public DocumentReference replaceParent(EntityReference newParent) { if (newParent == getParent()) { return this; } return new DocumentReference(this, newParent); } /** * @return the {@link LocalDocumentReference} corresponding to this {@link DocumentReference} * @since 8.3 * @deprecated since 9.3RC1/8.4.5, use {@link #getLocalDocumentReference()} instead */ @Deprecated public LocalDocumentReference getLocaleDocumentReference() { return getLocalDocumentReference(); } /** * @return the {@link LocalDocumentReference} corresponding to this {@link DocumentReference} * @since 9.3RC1 * @since 8.4.5 */ public LocalDocumentReference getLocalDocumentReference() { if (this.localDocumentReference == null) { this.localDocumentReference = new LocalDocumentReference(this); } return this.localDocumentReference; } /** * @return this document reference but without the locale if it contains any * @since 13.4RC1 * @since 12.10.8 */ public DocumentReference withoutLocale() { return getLocale() != null ? new DocumentReference(this, (Locale) null) : this; } @Override public String toString() { // Compared to EntityReference we don't print the type since the type is already indicated by the fact that // this is a DocumentReference instance. return TOSTRING_SERIALIZER.serialize(this); } }
xwiki-platform-core/xwiki-platform-model/xwiki-platform-model-api/src/main/java/org/xwiki/model/reference/DocumentReference.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.model.reference; import java.beans.Transient; import java.io.Serializable; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import javax.inject.Provider; import org.xwiki.component.util.DefaultParameterizedType; import org.xwiki.model.EntityType; /** * Represents a reference to a document (wiki, space and document names). * * @version $Id$ * @since 2.2M1 */ public class DocumentReference extends AbstractLocalizedEntityReference { /** * The {@link Type} for a {@code Provider<DocumentReference>}. * * @since 7.2M1 */ public static final Type TYPE_PROVIDER = new DefaultParameterizedType(null, Provider.class, DocumentReference.class); /** * Parameter key for the locale. */ static final String LOCALE = AbstractLocalizedEntityReference.LOCALE; /** * Cache the {@link LocalDocumentReference} corresponding to this {@link DocumentReference}. */ private LocalDocumentReference localDocumentReference; /** * Special constructor that transforms a generic entity reference into a {@link DocumentReference}. It checks the * validity of the passed reference (ie correct type and correct parent). * * @param reference the reference to convert * @exception IllegalArgumentException if the passed reference is not a valid document reference */ public DocumentReference(EntityReference reference) { super(reference); } /** * Clone an DocumentReference, but replace one of the parent in the chain by a new one. * * @param reference the reference that is cloned * @param oldReference the old parent that will be replaced * @param newReference the new parent that will replace oldReference in the chain * @since 3.3M2 */ protected DocumentReference(EntityReference reference, EntityReference oldReference, EntityReference newReference) { super(reference, oldReference, newReference); } /** * Clone the provided reference and change the Locale. * * @param reference the reference to clone * @param locale the new locale for this reference, if null, locale is removed * @exception IllegalArgumentException if the passed reference is not a valid document reference */ public DocumentReference(EntityReference reference, Locale locale) { super(reference, locale); } /** * Create a new Document reference from wiki, space and page name. * * @param wikiName the name of the wiki containing the document, must not be null * @param spaceName the name of the space containing the document, must not be null * @param pageName the name of the document */ public DocumentReference(String wikiName, String spaceName, String pageName) { this(pageName, new SpaceReference(spaceName, new WikiReference(wikiName))); } /** * Create a new Document reference from wiki name, space name, page name and locale. * * @param wikiName the name of the wiki containing the document, must not be null * @param spaceName the name of the space containing the document, must not be null * @param pageName the name of the document * @param locale the locale of the document reference, may be null */ public DocumentReference(String wikiName, String spaceName, String pageName, Locale locale) { this(pageName, new SpaceReference(spaceName, new WikiReference(wikiName)), locale); } /** * Create a new Document reference from wiki name, space name, page name and language. This is an helper function * during transition from language to locale, it will be deprecated ASAP. * * @param wikiName the name of the wiki containing the document, must not be null * @param spaceName the name of the space containing the document, must not be null * @param pageName the name of the document * @param language the language of the document reference, may be null */ public DocumentReference(String wikiName, String spaceName, String pageName, String language) { this(pageName, new SpaceReference(spaceName, new WikiReference(wikiName)), (language == null) ? null : new Locale(language)); } /** * Create a new Document reference from wiki name, spaces names and page name. * * @param wikiName the name of the wiki containing the document, must not be null * @param spaceNames an ordered list of the names of the spaces containing the document from root space to last one, * must not be null * @param pageName the name of the document */ public DocumentReference(String wikiName, List<String> spaceNames, String pageName) { super(pageName, EntityType.DOCUMENT, new SpaceReference(wikiName, spaceNames)); } /** * Create a new Document reference from wiki name, spaces names, page name and locale. * * @param wikiName the name of the wiki containing the document, must not be null * @param spaceNames an ordered list of the names of the spaces containing the document from root space to last one, * must not be null * @param pageName the name of the document reference * @param locale the locale of the document reference, may be null */ public DocumentReference(String wikiName, List<String> spaceNames, String pageName, Locale locale) { super(pageName, EntityType.DOCUMENT, new SpaceReference(wikiName, spaceNames), locale); } /** * Create a new Document reference from document name and parent space. * * @param pageName the name of the document * @param parent the parent space for the document */ public DocumentReference(String pageName, SpaceReference parent) { super(pageName, EntityType.DOCUMENT, parent); } /** * Create a new Document reference from local document reference and wiki reference. * * @param localDocumentReference the document reference without the wiki reference * @param wikiReference the wiki reference * @since 5.1M1 */ public DocumentReference(LocalDocumentReference localDocumentReference, WikiReference wikiReference) { super(localDocumentReference, null, wikiReference); } /** * Create a new Document reference from document name, parent space and locale. * * @param pageName the name of the document * @param parent the parent space for the document * @param locale the locale of the document reference, may be null */ public DocumentReference(String pageName, SpaceReference parent, Locale locale) { super(pageName, EntityType.DOCUMENT, parent, locale); } /** * @param pageName the name of the document * @param parent the parent space for the document * @param parameters parameters for this reference, may be null * @since 10.6RC1 */ public DocumentReference(String pageName, EntityReference parent, Map<String, Serializable> parameters) { super(pageName, EntityType.DOCUMENT, parent, parameters); } /** * Clone an DocumentReference, but use the specified parent for its new parent. * * @param reference the reference to clone * @param parent the new parent to use * @since 10.8RC1 */ public DocumentReference(EntityReference reference, EntityReference parent) { super(reference, parent); } /** * {@inheritDoc} * <p> * Overridden in order to verify the validity of the passed parent. * </p> * * @see org.xwiki.model.reference.EntityReference#setParent(EntityReference) * @exception IllegalArgumentException if the passed parent is not a valid document reference parent (ie a space * reference) */ @Override protected void setParent(EntityReference parent) { if (parent instanceof SpaceReference) { super.setParent(parent); return; } if (parent == null || parent.getType() != EntityType.SPACE) { throw new IllegalArgumentException("Invalid parent reference [" + parent + "] in a document reference"); } super.setParent(new SpaceReference(parent)); } /** * {@inheritDoc} * <p> * Overridden in order to verify the validity of the passed type. * </p> * * @see org.xwiki.model.reference.EntityReference#setType(org.xwiki.model.EntityType) * @exception IllegalArgumentException if the passed type is not a document type */ @Override protected void setType(EntityType type) { if (type != EntityType.DOCUMENT) { throw new IllegalArgumentException("Invalid type [" + type + "] for a document reference"); } super.setType(EntityType.DOCUMENT); } /** * @return the wiki reference of this document reference */ @Transient public WikiReference getWikiReference() { return (WikiReference) extractReference(EntityType.WIKI); } /** * Create a new DocumentReference with passed wiki reference. * * @param wikiReference the wiki reference to use * @return a new document reference or the same if the passed wiki is already the current wiki * @since 7.2M1 */ @Transient public DocumentReference setWikiReference(WikiReference wikiReference) { WikiReference currentWikiReferene = getWikiReference(); if (currentWikiReferene.equals(wikiReference)) { return this; } return new DocumentReference(this, currentWikiReferene, wikiReference); } /** * @return the space reference of the last space containing this document */ @Transient public SpaceReference getLastSpaceReference() { return (SpaceReference) extractReference(EntityType.SPACE); } /** * @return space references of this document in an ordered list */ @Transient public List<SpaceReference> getSpaceReferences() { List<SpaceReference> references = new ArrayList<SpaceReference>(); EntityReference reference = this; while (reference != null) { if (reference.getType() == EntityType.SPACE) { references.add((SpaceReference) reference); } reference = reference.getParent(); } // Reverse the array so that the last entry is the parent of the Document Reference Collections.reverse(references); return references; } @Override public DocumentReference replaceParent(EntityReference oldParent, EntityReference newParent) { if (newParent == oldParent) { return this; } return new DocumentReference(this, oldParent, newParent); } @Override public DocumentReference replaceParent(EntityReference newParent) { if (newParent == getParent()) { return this; } return new DocumentReference(this, newParent); } /** * @return the {@link LocalDocumentReference} corresponding to this {@link DocumentReference} * @since 8.3 * @deprecated since 9.3RC1/8.4.5, use {@link #getLocalDocumentReference()} instead */ @Deprecated public LocalDocumentReference getLocaleDocumentReference() { return getLocalDocumentReference(); } /** * @return the {@link LocalDocumentReference} corresponding to this {@link DocumentReference} * @since 9.3RC1 * @since 8.4.5 */ public LocalDocumentReference getLocalDocumentReference() { if (this.localDocumentReference == null) { this.localDocumentReference = new LocalDocumentReference(this); } return this.localDocumentReference; } /** * @return this document reference but without the locale if it contains any * @since 13.4RC1 * @since 12.10.8 */ public DocumentReference withoutLocale() { return getLocale() != null ? new DocumentReference(this, (Locale) null) : this; } @Override public String toString() { // Compared to EntityReference we don't print the type since the type is already indicated by the fact that // this is a DocumentReference instance. return TOSTRING_SERIALIZER.serialize(this); } }
[Misc] Fix a typo in a variable name
xwiki-platform-core/xwiki-platform-model/xwiki-platform-model-api/src/main/java/org/xwiki/model/reference/DocumentReference.java
[Misc] Fix a typo in a variable name
<ide><path>wiki-platform-core/xwiki-platform-model/xwiki-platform-model-api/src/main/java/org/xwiki/model/reference/DocumentReference.java <ide> @Transient <ide> public DocumentReference setWikiReference(WikiReference wikiReference) <ide> { <del> WikiReference currentWikiReferene = getWikiReference(); <del> <del> if (currentWikiReferene.equals(wikiReference)) { <add> WikiReference currentWikiReference = getWikiReference(); <add> <add> if (currentWikiReference.equals(wikiReference)) { <ide> return this; <ide> } <ide> <del> return new DocumentReference(this, currentWikiReferene, wikiReference); <add> return new DocumentReference(this, currentWikiReference, wikiReference); <ide> } <ide> <ide> /**
JavaScript
mit
bba78223173c38cffe02a4b010adf294a12fd155
0
Guernouille/Pokemon-Showdown,gustavo515/final,Enigami/Pokemon-Showdown,hayleysworld/Pokemon-Showdown,Flareninja/Pokemon-Showdown,kuroscafe/Paradox,Celecitia/Plux-Pokemon-Showdown,AWailOfATail/awoat,Legit99/Lightning-Storm-Server,gustavo515/gashoro,Disaster-Area/Pokemon-Showdown,cadaeic/Pokemon-Showdown,InvalidDN/Pokemon-Showdown,DarkSuicune/Kakuja-2.0,gustavo515/batata,azum4roll/Pokemon-Showdown,SerperiorBae/Pokemon-Showdown-1,zek7rom/SpacialGaze,gustavo515/batata,MeliodasBH/Articuno-Land,DarkSuicune/Kakuja-2.0,k3naan/Pokemon-Showdown,AWailOfATail/awoat,MasterFloat/Pokemon-Showdown,panpawn/Pokemon-Showdown,Yggdrasil-League/Yggdrasil,Bryan-0/Pokemon-Showdown,SkyeTheFemaleSylveon/Pokemon-Showdown,Extradeath/advanced,SerperiorBae/Bae-Showdown-2,Breakfastqueen/advanced,MayukhKundu/Flame-Savior,TbirdClanWish/Pokemon-Showdown,kuroscafe/Showdown-Boilerplate,Pikachuun/Joimmon-Showdown,Alpha-Devs/OmegaRuby-Server,lFernanl/Lumen-Pokemon-Showdown,Wando94/Pokemon-Showdown,BlakJack/Kill-The-Noise,Darkshadow6/git-remote-add-scalingo-git-scalingo.com-pokemoonforums,ankailou/Pokemon-Showdown,kubetz/Pokemon-Showdown,xfix/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,gustavo515/final,hayleysworld/Pokemon-Showdown,BuzzyOG/Pokemon-Showdown,Celecitia/Plux-Pokemon-Showdown,SerperiorBae/Pokemon-Showdown,UniversalMan12/Universe-Server,EienSeiryuu/Pokemon-Showdown,lAlejandro22/lolipoop,MeliodasBH/boarhat,Flareninja/Sora,Adithya4Uberz/The-Tsunami-League,SilverTactic/Pokemon-Showdown,yashagl/pokecommunity,KaitoV4X/Showdown,Irraquated/Showdown-Boilerplate,Pablo000/aaa,Ecuacion/Pokemon-Showdown,Irraquated/EOS-Master,Guernouille/Pokemon-Showdown,TheManwithskills/Server-2,LegendBorned/PS-Boilerplate,LustyAsh/EOS-Master,TheManwithskills/serenity,ShowdownHelper/Saffron,danpantry/Pokemon-Showdown,scotchkorean27/Pokemon-Showdown,DesoGit/Tsunami_PS,Flareninja/Lumen-Pokemon-Showdown,hayleysworld/serenityserver,KewlStatics/Shit,theodelhay/test,TheDiabolicGift/Showdown-Boilerplate,theodelhay/test,Adithya4Uberz/KTN,AvinashSwaminathan/lotus-v3,Zarel/Pokemon-Showdown,KaitoV4X/Showdown,Johto-Serverr/Werfin-Boilerplate,yashagl/pokemon,Pikachuun/Joimmon-Showdown,AnaRitaTorres/Pokemon-Showdown,TogeSR/Lumen-Pokemon-Showdown,sama2/Lumen-Pokemon-Showdown,MayukhKundu/Technogear-Final,Volcos/SpacialGaze,panpawn/Gold-Server,brettjbush/Pokemon-Showdown,Pikachuun/Pokemon-Showdown,SilverTactic/Dragotica-Pokemon-Showdown,EmmaKitty/Pokemon-Showdown,ehk12/bigbangtempclone,hayleysworld/serenityserver,BlazingAura/Showdown-Boilerplate,CreaturePhil/Showdown-Boilerplate,Evil-kun/Pokemon-Showdown,abrulochp/Lumen-Pokemon-Showdown,LightningStormServer/Lightning-Storm,urkerab/Pokemon-Showdown,Wando94/Spite,psnsVGC/Wish-Server,Gold-Solox/Pokemon-Showdown,gustavo515/gashoro,Zipzapadam/Server,yashagl/yash-showdown,AWailOfATail/Pokemon-Showdown,megaslowbro1/Pokemon-Showdown-Server-for-megaslowbro1,InvalidDN/Pokemon-Showdown,Flareninja/Hispano-Pokemon-Showdown,Raina4uberz/Light-server,Hidden-Mia/Roleplay-PS,Flareninja/Pokemon-Showdown-1,kuroscafe/Paradox,CreaturePhil/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,Darkshadow6/git-remote-add-scalingo-git-scalingo.com-pokemoonforums,ehk12/coregit,MasterFloat/LQP-Server-Showdown,bai2/Dropp,ehk12/clone,JellalTheMage/PS-,Darkshadow6/PokeMoon-Creation,sama2/Lumen-Pokemon-Showdown,Kill-The-Noise/BlakJack-Boilerplate,TheManwithskills/Server-2,DB898/theregalias,DesoGit/Tsunami_PS,SerperiorBae/Bae-Showdown,asdfghjklohhnhn/Pokemon-Showdown,Ransei1/Alt,SerperiorBae/BaeShowdown,QuiteQuiet/Pokemon-Showdown,TogeSR/Lumen-Pokemon-Showdown,Ridukuo/Test2,Ridukuo/Test,sama2/Dropp-Pokemon-Showdown,TheManwithskills/COC,Lord-Haji/SpacialGaze,sama2/Universe-Pokemon-Showdown,kupochu/Pokemon-Showdown,PS-Spectral/Spectral,MayukhKundu/Technogear-Final,TbirdClanWish/Pokemon-Showdown,NoahVSGamingYT/Pokemon-Showdown,panpawn/Gold-Server,Atwar/ServerClassroom,comedianchameleon/test,DesoGit/Tsunami_PS,Ridukuo/Test,Pikachuun/Pokemon-Showdown,superman8900/Pokemon-Showdown,gustavo515/test,Flareninja/Lumen-Pokemon-Showdown,Firestatics/omega,yashagl/yash-showdown,TheManwithskills/Creature-phil-boiler,ZeroParadox/BlastBurners,DesoGit/TsunamiPS,Flareninja/Hispano-Pokemon-Showdown,Lord-Haji/SpacialGaze,TheManwithskills/Server---Thermal,HoeenCoder/SpacialGaze,hayleysworld/asdfasdf,Sora-Server/Sora,Kenny-/Pokemon-Showdown,SSJGVegito007/Vegito-s-Server,NoahVSGamingYT/Pokemon-Showdown,Atwar/server-epilogueleague.rhcloud.com,MasterFloat/Pokemon-Showdown,MayukhKundu/Flame-Savior,megaslowbro1/Showdown-Server-again,Syurra/Pokemon-Showdown,SerperiorBae/Bae-Showdown-2,KewlStatics/Pokeindia-Codes,AvinashSwaminathan/lotus-v2,Neosweiss/Pokemon-Showdown,Ecuacion/Lumen-Pokemon-Showdown,svivian/Pokemon-Showdown,SolarisFox/Pokemon-Showdown,lAlejandro22/lolipoop,lFernanl/Mudkip-Server,ZestOfLife/FestiveLife,Enigami/Pokemon-Showdown,jd4564/Pokemon-Showdown,TheManwithskills/Server,CharizardtheFireMage/Showdown-Boilerplate,hayleysworld/harmonia,Ridukuo/Test2,UniversalMan12/Universe-Server,Kill-The-Noise/BlakJack-Boilerplate,Flareninja/Sora,Luobata/Pokemon-Showdown,HoeenKid/Pokemon-Showdown-Johto,BuzzyOG/Pokemon-Showdown,Sora-Server/Sora,PrimalGallade45/Lumen-Pokemon-Showdown,SerperiorBae/Bae-Showdown,Atwar/server-epilogueleague.rhcloud.com,TheManwithskills/Creature-phil-boiler,yashagl/pokemon,Parukia/Pokemon-Showdown,comedianchameleon/test,Lauc1an/Perulink-Showdown,DesoGit/TsunamiPS,kubetz/Pokemon-Showdown,SilverTactic/Showdown-Boilerplate,Atwar/http-server-femalehq.rhcloud.com-80.psim.us-,JellalTheMage/Jellals-Server,hayleysworld/serenity,Alpha-Devs/Alpha-Server,Darkshadow6/PokeMoon-Creation,AvinashSwaminathan/lotus,asdfghjklohhnhn/Pokemon-Showdown,Alpha-Devs/Alpha-Server,SubZeroo99/Pokemon-Showdown,Pikachuun/Pokemon-Showdown-SMCMDM,arkanox/MistShowdown,megaslowbro1/Showdown-Server-again,hayleysworld/Showdown-Boilerplate,comedianchameleon/servertest1,hayleysworld/asdfasdf,TheDiabolicGift/Lumen-Pokemon-Showdown,hayleysworld/Showdown-Boilerplate,TheManwithskills/Server---Thermal,comedianchameleon/test,xfix/Pokemon-Showdown,Wando94/Pokemon-Showdown,sama2/Universe-Pokemon-Showdown,TheManwithskills/Server-2,Zipzapadam/Server,Firestatics/Firestatics46,Tesarand/Pokemon-Showdown,Enigami/Pokemon-Showdown,ehk12/clone,Pikachuun/Touhoumon-Showdown,miahjennatills/Pokemon-Showdown,Evil-kun/Pokemon-Showdown,Mystifi/Exiled,Checkinator/Pokemon-Showdown,AWailOfATail/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,Pokemon-Devs/Pokemon-Showdown,FakeSloth/Infinite,Ecuacion/Lumen-Pokemon-Showdown,urkerab/Pokemon-Showdown,TheManwithskills/Dusk--Showdown,kotarou3/Krister-Pokemon-Showdown,SkyeTheFemaleSylveon/Pokemon-Showdown,Zarel/Pokemon-Showdown,hayleysworld/harmonia,MayukhKundu/Mudkip-Server,JennyPRO/Jenny,psnsVGC/Wish-Server,FakeSloth/Infinite,Nineage/Showdown-Boilerplate,jd4564/Pokemon-Showdown,Neosweiss/Pokemon-Showdown,megaslowbro1/Pokemon-Showdown,Articuno-I/Pokemon-Showdown,SerperiorBae/Bae-Showdown,Legendaryhades/Oblivion,forbiddennightmare/Pokemon-Showdown-1,Firestatics/Omega-Alpha,svivian/Pokemon-Showdown,Flareninja/Showdown-Boilerplate,Vacate/Pokemon-Showdown,EmmaKitty/Pokemon-Showdown,Kokonoe-san/Glacia-PS,xfix/Pokemon-Showdown,ehk12/coregit,yashagl/pokemon-showdown,svivian/Pokemon-Showdown,CreaturePhil/Pokemon-Showdown,lFernanl/Pokemon-Showdown,ScottehMax/Pokemon-Showdown,KewlStatics/Showdown-Template,Tesarand/Pokemon-Showdown,AustinXII/Pokemon-Showdown,Stroke123/POKEMON,Hopenub/Pokemon-Showdown,ZestOfLife/FestiveLife,Vacate/Pokemon-Showdown,cadaeic/Pokemon-Showdown,Stroke123/POKEMON,Breakfastqueen/advanced,AbsolitoSweep/Absol-server,BadSteel/Pokemon-Showdown,johtooo/PS,iFaZe/SliverX,Darkshadow6/PokeMoon-Creation,KewlStatics/Showdown-Template,Gold-Solox/Pokemon-Showdown,SilverTactic/Pokemon-Showdown,Nineage/Origin,catanatron/pokemon-rebalance,Fusxfaranto/Pokemon-Showdown,SerperiorBae/Pokemon-Showdown,megaslowbro1/Pokemon-Showdown,ZeroParadox/ugh,Breakfastqueen/advanced,superman8900/Pokemon-Showdown,xfix/Pokemon-Showdown,KewlStatics/Alliance,SerperiorBae/Pokemon-Showdown-1,Zarel/Pokemon-Showdown,anubhabsen/Pokemon-Showdown,Pokemon-Devs/Pokemon-Showdown,BuzzyOG/Pokemon-Showdown,TheManwithskills/Server,LustyAsh/EOS-Master,sama2/Viridian-Pokemon-Showdown,abulechu/Lumen-Pokemon-Showdown,AustinXII/Pokemon-Showdown,SerperiorBae/Bae-Showdown-2,QuiteQuiet/Pokemon-Showdown,Firestatics/Firestatics46,scotchkorean27/Pokemon-Showdown,TheDiabolicGift/Lumen-Pokemon-Showdown,EienSeiryuu/Pokemon-Showdown,AbsolitoSweep/Absol-server,AvinashSwaminathan/Pokelegends,iFaZe/SilverZ,panpawn/Gold-Server,CharizardtheFireMage/Showdown-Boilerplate,SolarisFox/Pokemon-Showdown,ZestOfLife/PSserver,danpantry/Pokemon-Showdown,VoltStorm/Server-pokemon-showdown,Git-Worm/City-PS,HoeenCoder/SpacialGaze,HoeenCoder/SpacialGaze,kupochu/Pokemon-Showdown,abrulochp/Dropp-Pokemon-Showdown,xCrystal/Pokemon-Showdown,Mystifi/Exiled,Alpha-Devs/OmegaRuby-Server,Sora-Server/Sora,ZestOfLife/PSserver,CreaturePhil/Showdown-Boilerplate,sirDonovan/Pokemon-Showdown,lFernanl/Pokemon-Showdown,k3naan/Pokemon-Showdown,Ransei1/Alt,RustServer/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,Pikachuun/Pokemon-Showdown-SMCMDM,abulechu/Lumen-Pokemon-Showdown,UniversalMan12/Universe-Server,aakashrajput/Pokemon-Showdown,SilverTactic/Showdown-Boilerplate,javi501/Lumen-Pokemon-Showdown,AnaRitaTorres/Pokemon-Showdown,lFernanl/Mudkip-Server,PrimalGallade45/Dropp-Pokemon-Showdown,Elveman/RPCShowdownServer,TheManwithskills/DS,kuroscafe/Showdown-Boilerplate,LightningStormServer/Lightning-Storm,BasedGod7/PH,BadSteel/Omega-Pokemon-Showdown,MeliodasBH/boarhat,TheDiabolicGift/Showdown-Boilerplate,yashagl/pokecommunity,LegendBorned/PS-Boilerplate,Kevinxzllz/PS-Openshift-Server,MeliodasBH/Articuno-Land,Bryan-0/Pokemon-Showdown,Irraquated/Pokemon-Showdown,abrulochp/Lumen-Pokemon-Showdown,Sora-League/Sora,DalleTest/Pokemon-Showdown,Parukia/Pokemon-Showdown,SilverTactic/Dragotica-Pokemon-Showdown,Kevinxzllz/PS-Openshift-Server,SerperiorBae/Pokemon-Showdown-1,miahjennatills/Pokemon-Showdown,Extradeath/psserver,Pablo000/aaa,abrulochp/Dropp-Pokemon-Showdown,TheFenderStory/Showdown-Boilerplate,svivian/Pokemon-Showdown,Firestatics/Omega-Alpha,Enigami/Pokemon-Showdown,MayukhKundu/Pokemon-Domain,ZeroParadox/BlastBurners,Flareninja/Showdown-Boilerplate,Nineage/Origin,xfix/Pokemon-Showdown,forbiddennightmare/Pokemon-Showdown-1,lFernanl/Lumen-Pokemon-Showdown,AustinXII/Pokemon-Showdown,javi501/Lumen-Pokemon-Showdown,PrimalGallade45/Lumen-Pokemon-Showdown,Extradeath/advanced,kotarou3/Krister-Pokemon-Showdown,DB898/theregalias,Ecuacion/Pokemon-Showdown,TheManwithskills/DS,Irraquated/Showdown-Boilerplate,Legit99/Lightning-Storm-Server,hayleysworld/serenity,PS-Spectral/Spectral,sirDonovan/Pokemon-Showdown,anubhabsen/Pokemon-Showdown,Sora-League/Sora,aakashrajput/Pokemon-Showdown,JellalTheMage/Jellals-Server,Firestatics/omega,TheFenderStory/Pokemon-Showdown,ankailou/Pokemon-Showdown,Werfin96/Ultimate,TheFenderStory/Pokemon-Showdown,sama2/Dropp-Pokemon-Showdown,DarkSuicune/Pokemon-Showdown,Flareninja/Sora,ShowdownHelper/Saffron,BlazingAura/Showdown-Boilerplate,comedianchameleon/servertest1,PS-Spectral/Spectral,SkyeTheFemaleSylveon/Mudkip-Server,bai2/Dropp,TheFenderStory/Showdown-Boilerplate,gustavo515/test,yashagl/pokemon-showdown,panpawn/Pokemon-Showdown,SerperiorBae/BaeShowdown,piiiikachuuu/Pokemon-Showdown,KewlStatics/Shit,MayukhKundu/Technogear,SkyeTheFemaleSylveon/Mudkip-Server,TheManwithskills/New-boiler-test,TheManwithskills/Dusk--Showdown,Irraquated/Pokemon-Showdown,ZeroParadox/ugh,lFernanl/Zero-Pokemon-Showdown,Checkinator/Pokemon-Showdown,brettjbush/Pokemon-Showdown,DarkSuicune/Pokemon-Showdown,ShowdownHelper/Saffron,JennyPRO/Jenny,zczd/enculer,RustServer/Pokemon-Showdown,sama2/Viridian-Pokemon-Showdown,KewlStatics/Alliance,Hidden-Mia/Roleplay-PS,Atwar/http-server-femalehq.rhcloud.com-80.psim.us-,Kokonoe-san/Glacia-PS,Chespin14/Custom-Platform-Pokemon-Showdown,Yggdrasil-League/Yggdrasil,Mystifi/Exiled,PauLucario/LQP-Server-Showdown,Disaster-Area/Pokemon-Showdown,hayleysworld/serenityc9,Darkshadow6/git-remote-add-scalingo-git-scalingo.com-pokemoonforums,CreaturePhil/Showdown-Boilerplate,Git-Worm/City-PS,zek7rom/SpacialGaze,PauLucario/LQP-Server-Showdown,Adithya4Uberz/The-Tsunami-League,SSJGVegito007/Vegito-s-Server,SubZeroo99/Pokemon-Showdown,SerperiorBae/PokemonShowdown2,abulechu/Dropp-Pokemon-Showdown,urkerab/Pokemon-Showdown,xCrystal/Pokemon-Showdown,MayukhKundu/Pokemon-Domain,Psyientist/Showdown-Boilerplate,MayukhKundu/Mudkip-Server,JellalTheMage/PS-,Kill-The-Noise/BlakJack-Boilerplate,Articuno-I/Pokemon-Showdown,AWailOfATail/Pokemon-Showdown,Tesarand/Pokemon-Showdown,Elveman/RPCShowdownServer,Syurra/Pokemon-Showdown,abulechu/Dropp-Pokemon-Showdown,Flareninja/Pokemon-Showdown-1,lFernanl/Zero-Pokemon-Showdown,azum4roll/Pokemon-Showdown,ScottehMax/Pokemon-Showdown,HoeenCoder/SpacialGaze,CrestfallPS/Pokemon-Showdown,Oiawesome/DPPtServ2,SerperiorBae/PokemonShowdown2,johtooo/PS,hayleysworld/serenityc9,TheManwithskills/COC,Flareninja/Pokemon-Showdown,Sora-League/Sora,LightningStormServer/Lightning-Storm,TheManwithskills/New-boiler-test,Lord-Haji/SpacialGaze,xCrystal/Pokemon-Showdown,aakashrajput/Pokemon-Showdown,MasterFloat/LQP-Server-Showdown,Irraquated/Pokemon-Showdown,Psyientist/Showdown-Boilerplate,PrimalGallade45/Dropp-Pokemon-Showdown,Wando94/Spite,arkanox/MistShowdown,Atwar/ServerClassroom,svivian/Pokemon-Showdown,Oiawesome/DPPtServ2,catanatron/pokemon-rebalance,KewlStatics/Pokeindia-Codes,Extradeath/psserver,Irraquated/EOS-Master,SerperiorBae/Pokemon-Showdown,FakeSloth/wulu,Parukia/Pokemon-Showdown,MayukhKundu/Technogear,DalleTest/Pokemon-Showdown,Thiediev/Pokemon-Showdown,Lauc1an/Perulink-Showdown,piiiikachuuu/Pokemon-Showdown,SerperiorBae/BaeShowdown,sirDonovan/Pokemon-Showdown,ehk12/bigbangtempclone,Volcos/SpacialGaze,zczd/enculer,Raina4uberz/Light-server,TheManwithskills/serenity,megaslowbro1/Pokemon-Showdown-Server-for-megaslowbro1
// Note: This is the list of formats // The rules that formats use are stored in data/formats.js exports.Formats = [ // XY Singles /////////////////////////////////////////////////////////////////// { name: "OU (beta)", section: "XY Singles", ruleset: ['Pokemon', 'Standard', 'Team Preview'], noPokebank: true, banlist: ['Uber', 'Soul Dew', 'Gengarite', 'Kangaskhanite'] }, { name: "Ubers (beta)", section: "XY Singles", ruleset: ['Pokemon', 'Standard Ubers', 'Team Preview'], noPokebank: true, banlist: [] }, { name: "LC (beta)", section: "XY Singles", maxLevel: 5, ruleset: ['Pokemon', 'Standard', 'Team Preview', 'Little Cup'], noPokebank: true, banlist: ['Sonicboom', 'Dragon Rage', 'Scyther', 'Sneasel'] }, { name: "XY Battle Spot Singles (beta)", section: "XY Singles", onBegin: function() { this.debug('cutting down to 3'); this.p1.pokemon = this.p1.pokemon.slice(0,3); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0,3); this.p2.pokemonLeft = this.p2.pokemon.length; }, maxForcedLevel: 50, ruleset: ['Pokemon', 'Standard GBU', 'Team Preview GBU'], noPokebank: true, banlist: [], // The neccessary bans are in Standard GBU validateTeam: function(team, format) { if (team.length < 3) return ['You must bring at least 3 Pokemon.']; } }, { name: "XY Battle Spot Special (beta)", section: "XY Singles", onBegin: function() { this.debug('cutting down to 3'); this.p1.pokemon = this.p1.pokemon.slice(0,3); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0,3); this.p2.pokemonLeft = this.p2.pokemon.length; }, maxForcedLevel: 50, ruleset: ['Pokemon', 'Standard GBU', 'Team Preview GBU'], noPokebank: true, banlist: [], // The neccessary bans are in Standard GBU validateTeam: function(team, format) { for (var i = 0; i < team.length; i++) { var template = this.getTemplate(team[i].species); if (template.num < 650) { return ['You may only use Pokemon from Gen 6']; } } if (team.length < 3) return ['You must bring at least 3 Pokemon.']; } }, { name: "Pokebank OU (beta)", section: "XY Singles", ruleset: ['Pokemon', 'Standard Pokebank', 'Team Preview'], banlist: ['Uber', 'Soul Dew', 'Gengarite', 'Kangaskhanite'] }, { name: "Pokebank Ubers (beta)", section: "XY Singles", ruleset: ['Pokemon', 'Standard Pokebank', 'Team Preview'], banlist: [] }, { name: "Pokebank LC (beta)", section: "XY Singles", maxLevel: 5, ruleset: ['Pokemon', 'Standard Pokebank', 'Team Preview', 'Little Cup'], banlist: ['Sonicboom', 'Dragon Rage', 'Scyther', 'Sneasel'] }, { name: "Custom Game", section: "XY Singles", searchShow: false, canUseRandomTeam: true, debug: true, maxLevel: 9999, defaultLevel: 100, // no restrictions, for serious (other than team preview) ruleset: ['Team Preview'] }, // BW2 Singles /////////////////////////////////////////////////////////////////// // { // name: "[Gen 5] CAP Cawmodore Playtest", // section: "BW2 Singles", // mod: 'gen5', // ruleset: ['CAP Pokemon', 'Standard', 'Evasion Abilities Clause', 'Team Preview'], // banlist: ['Uber', 'Drizzle ++ Swift Swim', 'Soul Dew', "Tomohawk", "Necturna", "Mollux", "Aurumoth", "Malaconda", "Syclant", "Revenankh", "Pyroak", "Fidgit", "Stratagem", "Arghonaut", "Kitsunoh", "Cyclohm", "Colossoil", "Krilowatt", "Voodoom"] // }, { name: "[Gen 5] Random Battle", section: "BW2 Singles", mod: 'gen5', team: 'random', ruleset: ['PotD', 'Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod'] }, { name: "[Gen 5] Unrated Random Battle", section: "BW2 Singles", mod: 'gen5', team: 'random', challengeShow: false, rated: false, ruleset: ['Random Battle'] }, { name: "[Gen 5] OU", section: "BW2 Singles", mod: 'gen5', ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Team Preview'], banlist: ['Uber', 'Drizzle ++ Swift Swim', 'Soul Dew'] }, { name: "[Gen 5] Ubers", section: "BW2 Singles", mod: 'gen5', ruleset: ['Pokemon', 'Team Preview', 'Standard Ubers'], banlist: [] }, { name: "[Gen 5] UU", section: "BW2 Singles", mod: 'gen5', ruleset: ['[Gen 5] OU'], banlist: ['OU', 'BL', 'Drought', 'Sand Stream'] }, { name: "[Gen 5] RU", section: "BW2 Singles", mod: 'gen5', ruleset: ['[Gen 5] UU'], banlist: ['UU', 'BL2', 'Shell Smash + Baton Pass', 'Snow Warning'] }, { name: "[Gen 5] NU", section: "BW2 Singles", mod: 'gen5', ruleset: ['[Gen 5] RU'], banlist: ['RU','BL3', 'Prankster + Assist'] }, { name: "[Gen 5] LC", section: "BW2 Singles", mod: 'gen5', maxLevel: 5, ruleset: ['Pokemon', 'Standard', 'Team Preview', 'Little Cup'], banlist: ['Sonicboom', 'Dragon Rage', 'Berry Juice', 'Carvanha', 'Meditite', 'Gligar', 'Scyther', 'Sneasel', 'Tangela', 'Vulpix', 'Yanma', 'Soul Dew'] }, { name: "[Gen 5] GBU Singles", section: "BW2 Singles", mod: 'gen5', validateSet: function(set) { if (!set.level || set.level >= 50) set.forcedLevel = 50; return []; }, onBegin: function() { this.debug('cutting down to 3'); this.p1.pokemon = this.p1.pokemon.slice(0,3); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0,3); this.p2.pokemonLeft = this.p2.pokemon.length; }, ruleset: ['Pokemon', 'Species Clause', 'Item Clause', 'Team Preview GBU'], banlist: ['Unreleased', 'Illegal', 'Sky Drop', 'Dark Void', 'Soul Dew', 'Mewtwo', 'Mew', 'Lugia', 'Ho-Oh', 'Celebi', 'Kyogre', 'Groudon', 'Rayquaza', 'Jirachi', 'Deoxys', 'Deoxys-Attack', 'Deoxys-Speed', 'Deoxys-Defense', 'Chatot', 'Dialga', 'Palkia', 'Giratina', 'Giratina-Origin', 'Phione', 'Manaphy', 'Darkrai', 'Shaymin', 'Shaymin-Sky', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Victini', 'Reshiram', 'Zekrom', 'Kyurem', 'Kyurem-Black', 'Kyurem-White', 'Keldeo', 'Keldeo-Resolute', 'Meloetta', 'Genesect' ] }, { name: "[Gen 5] Custom Game", section: "BW2 Singles", mod: 'gen5', searchShow: false, canUseRandomTeam: true, debug: true, maxLevel: 9999, defaultLevel: 100, // no restrictions, for serious (other than team preview) ruleset: ['Team Preview'] }, // XY Doubles /////////////////////////////////////////////////////////////////// { name: "Smogon Doubles (beta)", section: "XY Doubles", column: 2, gameType: 'doubles', ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Team Preview'], noPokebank: true, banlist: ['Dark Void', 'Soul Dew', 'Mewtwo', 'Mewtwo-Mega-X', 'Mewtwo-Mega-Y', 'Lugia', 'Ho-Oh', 'Kyogre', 'Groudon', 'Rayquaza', 'Dialga', 'Palkia', 'Giratina', 'Giratina-Origin', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fairy', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Reshiram', 'Zekrom', 'Kyurem-White', 'Xerneas', 'Yveltal' ] }, { name: "Pokebank Smogon Doubles (beta)", section: "XY Doubles", column: 2, gameType: 'doubles', ruleset: ['Pokemon', 'Standard Pokebank', 'Evasion Abilities Clause', 'Team Preview'], banlist: ['Dark Void', 'Soul Dew', 'Mewtwo', 'Mewtwo-Mega-X', 'Mewtwo-Mega-Y', 'Lugia', 'Ho-Oh', 'Kyogre', 'Groudon', 'Rayquaza', 'Dialga', 'Palkia', 'Giratina', 'Giratina-Origin', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fairy', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Reshiram', 'Zekrom', 'Kyurem-White', 'Xerneas', 'Yveltal' ] }, { name: "XY Battle Spot Doubles (beta)", section: "XY Doubles", column: 2, gameType: 'doubles', onBegin: function() { this.debug('cutting down to 4'); this.p1.pokemon = this.p1.pokemon.slice(0,4); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0,4); this.p2.pokemonLeft = this.p2.pokemon.length; }, maxForcedLevel: 50, ruleset: ['Pokemon', 'Standard GBU', 'Team Preview VGC'], noPokebank: true, banlist: ['Dark Void'], // Banning Dark Void here because technically Smeargle cannot learn it yet. validateTeam: function(team, format) { if (team.length < 4) return ['You must bring at least 4 Pokemon.']; } }, { name: "VGC 2014 (beta)", section: "XY Doubles", column: 2, gameType: 'doubles', onBegin: function() { this.debug('cutting down to 4'); this.p1.pokemon = this.p1.pokemon.slice(0,4); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0,4); this.p2.pokemonLeft = this.p2.pokemon.length; }, maxForcedLevel: 50, ruleset: ['Pokemon', 'Standard GBU', 'Team Preview VGC', 'Kalos Pokedex'], requirePentagon: true, banlist: [], // The neccessary bans are in Standard GBU validateTeam: function(team, format) { if (team.length < 4) return ['You must bring at least 4 Pokemon.']; } }, { name: "Doubles Challenge Cup", section: 'XY Doubles', gameType: 'doubles', team: 'randomCC', searchShow: false, ruleset: ['Pokemon', 'HP Percentage Mod'] }, { name: "Doubles Custom Game", section: "XY Doubles", column: 2, gameType: 'doubles', searchShow: false, canUseRandomTeam: true, maxLevel: 9999, defaultLevel: 100, debug: true, ruleset: ['Team Preview'] }, // BW2 Doubles /////////////////////////////////////////////////////////////////// { name: "[Gen 5] Smogon Doubles", section: 'BW2 Doubles', column: 2, mod: 'gen5', gameType: 'doubles', ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Team Preview'], banlist: ['Unreleased', 'Illegal', 'Dark Void', 'Soul Dew', 'Sky Drop', 'Mewtwo', 'Lugia', 'Ho-Oh', 'Kyogre', 'Groudon', 'Rayquaza', 'Dialga', 'Palkia', 'Giratina', 'Giratina-Origin', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Reshiram', 'Zekrom', 'Kyurem-White' ] }, { name: "[Gen 5] Doubles VGC 2013", section: 'BW2 Doubles', mod: 'gen5', gameType: 'doubles', onBegin: function() { this.debug('cutting down to 4'); this.p1.pokemon = this.p1.pokemon.slice(0,4); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0,4); this.p2.pokemonLeft = this.p2.pokemon.length; }, maxForcedLevel: 50, ruleset: ['Pokemon', 'Team Preview VGC', 'Species Clause', 'Item Clause'], banlist: ['Unreleased', 'Illegal', 'Sky Drop', 'Dark Void', 'Soul Dew', 'Mewtwo', 'Mew', 'Lugia', 'Ho-Oh', 'Celebi', 'Kyogre', 'Groudon', 'Rayquaza', 'Jirachi', 'Deoxys', 'Deoxys-Attack', 'Deoxys-Speed', 'Deoxys-Defense', 'Chatot', 'Dialga', 'Palkia', 'Giratina', 'Giratina-Origin', 'Phione', 'Manaphy', 'Darkrai', 'Shaymin', 'Shaymin-Sky', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Victini', 'Reshiram', 'Zekrom', 'Kyurem', 'Kyurem-Black', 'Kyurem-White', 'Keldeo', 'Keldeo-Resolute', 'Meloetta', 'Genesect' ] }, { name: "[Gen 5] Doubles Custom Game", section: 'BW2 Doubles', mod: 'gen5', gameType: 'doubles', searchShow: false, canUseRandomTeam: true, debug: true, maxLevel: 9999, defaultLevel: 100, // no restrictions, for serious (other than team preview) ruleset: ['Team Preview'] }, // Other Metagames /////////////////////////////////////////////////////////////////// { name: "[Seasonal] Christmas Charade", section: "OM of the Month", team: 'randomSeasonalCC', ruleset: ['HP Percentage Mod', 'Sleep Clause Mod'], onBegin: function() { this.setWeather('Hail'); delete this.weatherData.duration; }, onModifyMove: function(move) { if (move.id === 'present') { move.category = 'Status'; move.basePower = 0; delete move.heal; move.accuracy = 100; switch (this.random(19)) { case 0: move.onTryHit = function() { this.add('-message', "The present was a bomb!"); }; move.category = 'Physical'; move.basePower = 250; break; case 1: move.onTryHit = function() { this.add('-message', "The present was confusion!"); }; move.volatileStatus = 'confusion'; break; case 2: move.onTryHit = function() { this.add('-message', "The present was Disable!"); }; move.volatileStatus = 'disable'; break; case 3: move.onTryHit = function() { this.add('-message', "The present was a taunt!"); }; move.volatileStatus = 'taunt'; break; case 4: move.onTryHit = function() { this.add('-message', "The present was some seeds!"); }; move.volatileStatus = 'leechseed'; break; case 5: move.onTryHit = function() { this.add('-message', "The present was an embargo!"); }; move.volatileStatus = 'embargo'; break; case 6: move.onTryHit = function() { this.add('-message', "The present was a music box!"); }; move.volatileStatus = 'perishsong'; break; case 7: move.onTryHit = function() { this.add('-message', "The present was a curse!"); }; move.volatileStatus = 'curse'; break; case 8: move.onTryHit = function() { this.add('-message', "The present was Torment!"); }; move.volatileStatus = 'torment'; break; case 9: move.onTryHit = function() { this.add('-message', "The present was a trap!"); }; move.volatileStatus = 'partiallytrapped'; break; case 10: move.onTryHit = function() { this.add('-message', "The present was a root!"); }; move.volatileStatus = 'ingrain'; break; case 11: move.onTryHit = function() { this.add('-message', "The present was a makeover!"); }; var boosts = {}; var possibleBoosts = ['atk','def','spa','spd','spe','accuracy','evasion'].randomize(); boosts[possibleBoosts[0]] = 1; boosts[possibleBoosts[1]] = -1; boosts[possibleBoosts[2]] = -1; move.boosts = boosts; break; case 12: move.onTryHit = function() { this.add('-message', "The present was psychic powers!"); }; move.volatileStatus = 'telekinesis'; break; case 13: move.onTryHit = function() { this.add('-message', "The present was fatigue!"); }; move.volatileStatus = 'mustrecharge'; break; case 14: case 15: move.onTryHit = function() { this.add('-message', "The present was a snowball hit!"); }; move.category = 'Ice'; move.basePower = 250; break; case 16: move.onTryHit = function() { this.add('-message', "The present was a crafty shield!"); }; move.volatileStatus = 'craftyshield'; break; case 17: move.onTryHit = function() { this.add('-message', "The present was an electrification!"); }; move.volatileStatus = 'electrify'; break; case 18: move.onTryHit = function() { this.add('-message', "The present was an ion deluge!"); }; move.volatileStatus = 'iondeluge'; break; } } } }, { name: "Sky Battles", section: "OM of the Month", validateSet: function(set) { var template = this.getTemplate(set.species || set.name); if (template.types.indexOf('Flying') === -1 && set.ability !== 'Levitate') { return [set.species+" is not a Flying type and does not have the ability Levitate."]; } }, ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Team Preview'], banlist: [ // Banned items 'Soul Dew', 'Iron Ball', 'Pinsirite', 'Gengarite', // Banned moves 'Body Slam', 'Bulldoze', 'Dig', 'Dive', 'Earth Power', 'Earthquake', 'Electric Terrain', 'Fire Pledge', 'Fissure', 'Flying Press', 'Frenzy Plant', 'Geomancy', 'Grass Knot', 'Grass Pledge', 'Grassy Terrain', 'Gravity', 'Heavy Slam', 'Ingrain', "Land's Wrath", 'Magnitude', 'Mat Block', 'Misty Terrain', 'Mud Sport', 'Muddy Water', 'Rototiller', 'Seismic Toss', 'Slam', 'Smack Down', 'Spikes', 'Stomp', 'Substitute', 'Surf', 'Toxic Spikes', 'Water Pledge', 'Water Sport', // Banned Pokémon // Illegal Flying-types 'Pidgey', 'Spearow', "Farfetch'd", 'Doduo', 'Dodrio', 'Hoothoot', 'Natu', 'Murkrow', 'Delibird', 'Taillow', 'Starly', 'Chatot', 'Shaymin-Sky', 'Pidove', 'Archen', 'Ducklett', 'Rufflet', 'Vullaby', 'Fletchling', 'Hawlucha', // Illegal Levitators 'Gastly', 'Gengar', // Illegal Megas 'Pinsir-Mega', 'Gengar-Mega', // Illegal Ubers 'Arceus-Flying', 'Giratina', 'Giratina-Origin', 'Ho-Oh', 'Lugia', 'Rayquaza', 'Yveltal' ] }, { name: "CAP (beta)", section: "Other Metagames", ruleset: ['CAP Pokemon', 'Standard Pokebank', 'Team Preview'], banlist: ['Uber', 'Soul Dew'] }, { name: "Challenge Cup", section: "Other Metagames", team: 'randomCC', ruleset: ['Pokemon', 'HP Percentage Mod'] }, { name: "Challenge Cup 1-vs-1", section: "Other Metagames", team: 'randomCC', ruleset: ['Pokemon', 'Team Preview 1v1', 'HP Percentage Mod'], onBegin: function() { this.debug('Cutting down to 1'); this.p1.pokemon = this.p1.pokemon.slice(0, 1); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0, 1); this.p2.pokemonLeft = this.p2.pokemon.length; } }, { name: "Hackmons", section: "Other Metagames", ruleset: ['Pokemon'], banlist: [] }, { name: "Balanced Hackmons", section: "Other Metagames", ruleset: ['Pokemon', 'OHKO Clause'], banlist: ['Wonder Guard', 'Shadow Tag', 'Arena Trap', 'Pure Power', 'Huge Power', 'Parental Bond'] }, { name: "Gen-NEXT OU", section: "Other Metagames", mod: 'gennext', searchShow: false, ruleset: ['Pokemon', 'Standard NEXT', 'Team Preview'], banlist: ['Uber'] }, { name: "Inverse Battle", section: "Other Metagames", mod: 'inverse', ruleset: ['Pokemon', 'Standard', 'Team Preview'], banlist: [ 'Ho-Oh', 'Kangaskhanite', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fairy', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Mewtwo', 'Mewtwo-Mega-X', 'Mewtwo-Mega-Y', 'Yveltal', 'Xerneas' ] }, { name: "OU Monotype", section: "Other Metagames", ruleset: ['Pokemon', 'Standard', 'Same Type Clause', 'Evasion Abilities Clause', 'Team Preview'], banlist: ['Uber', 'Soul Dew', 'Gengarite', 'Kangaskhanite'] }, { name: "[Gen 5] Glitchmons", section: "Other Metagames", mod: 'gen5', searchShow: false, ruleset: ['Pokemon', 'Team Preview', 'HP Percentage Mod'], banlist: ['Illegal', 'Unreleased'], mimicGlitch: true }, { name: "[Gen 5] 1v1", section: 'Other Metagames', mod: 'gen5', onBegin: function() { this.p1.pokemon = this.p1.pokemon.slice(0,1); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0,1); this.p2.pokemonLeft = this.p2.pokemon.length; }, ruleset: ['Pokemon', 'Standard'], banlist: ['Unreleased', 'Illegal', 'Soul Dew', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Blaziken', 'Darkrai', 'Deoxys', 'Deoxys-Attack', 'Dialga', 'Giratina', 'Giratina-Origin', 'Groudon', 'Ho-Oh', 'Kyogre', 'Kyurem-White', 'Lugia', 'Mewtwo', 'Palkia', 'Rayquaza', 'Reshiram', 'Shaymin-Sky', 'Zekrom', 'Memento', 'Explosion', 'Perish Song', 'Destiny Bond', 'Healing Wish', 'Selfdestruct', 'Lunar Dance', 'Final Gambit', 'Focus Sash' ] }, { name: "[Gen 5] PU", section: "Other Metagames", mod: 'gen5', searchShow: false, ruleset: ['NU'], banlist: ["Charizard", "Wartortle", "Kadabra", "Golem", "Haunter", "Exeggutor", "Weezing", "Kangaskhan", "Pinsir", "Lapras", "Ampharos", "Misdreavus", "Piloswine", "Miltank", "Ludicolo", "Swellow", "Gardevoir", "Ninjask", "Torkoal", "Cacturne", "Altaria", "Armaldo", "Gorebyss", "Regirock", "Regice", "Bastiodon", "Floatzel", "Drifblim", "Skuntank", "Lickilicky", "Probopass", "Rotom-Fan", "Samurott", "Musharna", "Gurdurr", "Sawk", "Carracosta", "Garbodor", "Sawsbuck", "Alomomola", "Golurk", "Braviary", "Electabuzz", "Electrode", "Liepard", "Tangela", "Eelektross", "Ditto", "Seismitoad", "Zangoose", "Roselia", "Serperior", "Metang", "Tauros", "Cradily", "Primeape", "Scolipede", "Jynx", "Basculin", "Gigalith", "Camerupt", "Golbat"] }, { name: "[Gen 5] STABmons", section: "Other Metagames", mod: 'gen5', ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Team Preview'], banlist: ['Drizzle ++ Swift Swim', 'Soul Dew', 'Soul Dew', 'Mewtwo', 'Lugia', 'Ho-Oh', 'Blaziken', 'Kyogre', 'Groudon', 'Rayquaza', 'Deoxys', 'Deoxys-Attack', 'Dialga', 'Palkia', 'Giratina', 'Giratina-Origin', 'Manaphy', 'Shaymin-Sky', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Reshiram', 'Zekrom', 'Kyurem-White', 'Genesect' ] }, { name: "[Gen 5] Budgetmons", section: "Other Metagames", mod: 'gen5', searchShow: false, ruleset: ['OU'], banlist: [], validateTeam: function(team, format) { var bst = 0; for (var i=0; i<team.length; i++) { var template = this.getTemplate(team[i].species); Object.values(template.baseStats, function(value) { bst += value; }); } if (bst > 2300) return ['The combined BST of your team is greater than 2300.']; } }, { name: "[Gen 5] Ability Exchange", section: "Other Metagames", mod: 'gen5', searchShow: false, ruleset: ['Pokemon', 'Ability Exchange Pokemon', 'Sleep Clause Mod', 'Species Clause', 'OHKO Clause', 'Moody Clause', 'Evasion Moves Clause', 'HP Percentage Mod', 'Team Preview'], banlist: ['Unreleased', 'Illegal', 'Ignore Illegal Abilities', 'Drizzle ++ Swift Swim', 'Soul Dew', 'Drought ++ Chlorophyll', 'Sand Stream ++ Sand Rush', 'Mewtwo', 'Lugia', 'Ho-Oh', 'Blaziken', 'Kyogre', 'Groudon', 'Rayquaza', 'Deoxys', 'Deoxys-Attack', 'Deoxys-Defense', 'Deoxys-Speed', 'Dialga', 'Palkia', 'Giratina', 'Giratina-Origin', 'Manaphy', 'Darkrai', 'Shaymin-Sky', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Excadrill', 'Tornadus-Therian', 'Thundurus', 'Reshiram', 'Zekrom', 'Landorus', 'Kyurem-White', 'Genesect', 'Slaking', 'Regigigas' ] }, // Past Generations /////////////////////////////////////////////////////////////////// { name: "[Gen 4] OU (beta)", section: "Past Generations", mod: 'gen4', ruleset: ['Pokemon', 'Standard'], banlist: ['Uber'], column: 2 }, { name: "[Gen 4] UU (beta)", section: "Past Generations", mod: 'gen4', ruleset: ['Pokemon', 'Standard'], banlist: ['Uber', 'OU', 'BL'] }, { name: "[Gen 4] Hackmons", section: "Past Generations", mod: 'gen4', searchShow: false, ruleset: ['Pokemon', 'HP Percentage Mod'], banlist: [] }, { name: "[Gen 4] Custom Game", section: "Past Generations", mod: 'gen4', searchShow: false, debug: true, ruleset: [] }, { name: "[Gen 3] Hackmons", section: "Past Generations", mod: 'gen3', searchShow: false, debug: true, ruleset: ['Pokemon', 'HP Percentage Mod'], banlist: [] }, { name: "[Gen 3] Custom Game", section: "Past Generations", mod: 'gen3', searchShow: false, debug: true, ruleset: [] }, { name: "[Gen 2] OU (beta)", section: "Past Generations", mod: 'gen2', debug: true, ruleset: ['Pokemon', 'Standard'], banlist: ['Uber', 'Mean Look + Hypnosis + Perish Song'] }, { name: "[Gen 2] Custom Game", section: "Past Generations", mod: 'gen2', searchShow: false, debug: true, ruleset: ['Pokemon'] }, { name: "[Gen 1] OU (beta)", section: "Past Generations", mod: 'gen1', ruleset: ['Pokemon', 'Standard'], banlist: ['Uber'] }, { name: "[Gen 1] Custom Game", section: "Past Generations", mod: 'gen1', searchShow: false, debug: true, ruleset: ['Pokemon'] } ];
config/formats.js
// Note: This is the list of formats // The rules that formats use are stored in data/formats.js exports.Formats = [ // XY Singles /////////////////////////////////////////////////////////////////// { name: "OU (beta)", section: "XY Singles", ruleset: ['Pokemon', 'Standard', 'Team Preview'], noPokebank: true, banlist: ['Uber', 'Soul Dew', 'Gengarite', 'Kangaskhanite'] }, { name: "Ubers (beta)", section: "XY Singles", ruleset: ['Pokemon', 'Standard Ubers', 'Team Preview'], noPokebank: true, banlist: [] }, { name: "LC (beta)", section: "XY Singles", maxLevel: 5, ruleset: ['Pokemon', 'Standard', 'Team Preview', 'Little Cup'], noPokebank: true, banlist: ['Sonicboom', 'Dragon Rage', 'Scyther', 'Sneasel'] }, { name: "XY Battle Spot Singles (beta)", section: "XY Singles", onBegin: function() { this.debug('cutting down to 3'); this.p1.pokemon = this.p1.pokemon.slice(0,3); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0,3); this.p2.pokemonLeft = this.p2.pokemon.length; }, maxForcedLevel: 50, ruleset: ['Pokemon', 'Standard GBU', 'Team Preview GBU'], noPokebank: true, banlist: [], // The neccessary bans are in Standard GBU validateTeam: function(team, format) { if (team.length < 3) return ['You must bring at least 3 Pokemon.']; } }, { name: "XY Battle Spot Special (beta)", section: "XY Singles", onBegin: function() { this.debug('cutting down to 3'); this.p1.pokemon = this.p1.pokemon.slice(0,3); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0,3); this.p2.pokemonLeft = this.p2.pokemon.length; }, maxForcedLevel: 50, ruleset: ['Pokemon', 'Standard GBU', 'Team Preview GBU'], noPokebank: true, banlist: [], // The neccessary bans are in Standard GBU validateTeam: function(team, format) { for (var i = 0; i < team.length; i++) { var template = this.getTemplate(team[i].species); if (template.num < 650) { return ['You may only use Pokemon from Gen 6']; } } if (team.length < 3) return ['You must bring at least 3 Pokemon.']; } }, { name: "Pokebank OU (beta)", section: "XY Singles", ruleset: ['Pokemon', 'Standard Pokebank', 'Team Preview'], banlist: ['Uber', 'Soul Dew', 'Gengarite', 'Kangaskhanite'] }, { name: "Pokebank Ubers (beta)", section: "XY Singles", ruleset: ['Pokemon', 'Standard Pokebank', 'Team Preview'], banlist: [] }, { name: "Pokebank LC (beta)", section: "XY Singles", maxLevel: 5, ruleset: ['Pokemon', 'Standard Pokebank', 'Team Preview', 'Little Cup'], banlist: ['Sonicboom', 'Dragon Rage', 'Scyther', 'Sneasel'] }, { name: "Custom Game", section: "XY Singles", searchShow: false, canUseRandomTeam: true, debug: true, maxLevel: 9999, defaultLevel: 100, // no restrictions, for serious (other than team preview) ruleset: ['Team Preview'] }, // BW2 Singles /////////////////////////////////////////////////////////////////// // { // name: "[Gen 5] CAP Cawmodore Playtest", // section: "BW2 Singles", // mod: 'gen5', // ruleset: ['CAP Pokemon', 'Standard', 'Evasion Abilities Clause', 'Team Preview'], // banlist: ['Uber', 'Drizzle ++ Swift Swim', 'Soul Dew', "Tomohawk", "Necturna", "Mollux", "Aurumoth", "Malaconda", "Syclant", "Revenankh", "Pyroak", "Fidgit", "Stratagem", "Arghonaut", "Kitsunoh", "Cyclohm", "Colossoil", "Krilowatt", "Voodoom"] // }, { name: "[Gen 5] Random Battle", section: "BW2 Singles", mod: 'gen5', team: 'random', ruleset: ['PotD', 'Pokemon', 'Sleep Clause Mod', 'HP Percentage Mod'] }, { name: "[Gen 5] Unrated Random Battle", section: "BW2 Singles", mod: 'gen5', team: 'random', challengeShow: false, rated: false, ruleset: ['Random Battle'] }, { name: "[Gen 5] OU", section: "BW2 Singles", mod: 'gen5', ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Team Preview'], banlist: ['Uber', 'Drizzle ++ Swift Swim', 'Soul Dew'] }, { name: "[Gen 5] Ubers", section: "BW2 Singles", mod: 'gen5', ruleset: ['Pokemon', 'Team Preview', 'Standard Ubers'], banlist: [] }, { name: "[Gen 5] UU", section: "BW2 Singles", mod: 'gen5', ruleset: ['[Gen 5] OU'], banlist: ['OU', 'BL', 'Drought', 'Sand Stream'] }, { name: "[Gen 5] RU", section: "BW2 Singles", mod: 'gen5', ruleset: ['[Gen 5] UU'], banlist: ['UU', 'BL2', 'Shell Smash + Baton Pass', 'Snow Warning'] }, { name: "[Gen 5] NU", section: "BW2 Singles", mod: 'gen5', ruleset: ['[Gen 5] RU'], banlist: ['RU','BL3', 'Prankster + Assist'] }, { name: "[Gen 5] LC", section: "BW2 Singles", mod: 'gen5', maxLevel: 5, ruleset: ['Pokemon', 'Standard', 'Team Preview', 'Little Cup'], banlist: ['Sonicboom', 'Dragon Rage', 'Berry Juice', 'Carvanha', 'Meditite', 'Gligar', 'Scyther', 'Sneasel', 'Tangela', 'Vulpix', 'Yanma', 'Soul Dew'] }, { name: "[Gen 5] GBU Singles", section: "BW2 Singles", mod: 'gen5', validateSet: function(set) { if (!set.level || set.level >= 50) set.forcedLevel = 50; return []; }, onBegin: function() { this.debug('cutting down to 3'); this.p1.pokemon = this.p1.pokemon.slice(0,3); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0,3); this.p2.pokemonLeft = this.p2.pokemon.length; }, ruleset: ['Pokemon', 'Species Clause', 'Item Clause', 'Team Preview GBU'], banlist: ['Unreleased', 'Illegal', 'Sky Drop', 'Dark Void', 'Soul Dew', 'Mewtwo', 'Mew', 'Lugia', 'Ho-Oh', 'Celebi', 'Kyogre', 'Groudon', 'Rayquaza', 'Jirachi', 'Deoxys', 'Deoxys-Attack', 'Deoxys-Speed', 'Deoxys-Defense', 'Chatot', 'Dialga', 'Palkia', 'Giratina', 'Giratina-Origin', 'Phione', 'Manaphy', 'Darkrai', 'Shaymin', 'Shaymin-Sky', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Victini', 'Reshiram', 'Zekrom', 'Kyurem', 'Kyurem-Black', 'Kyurem-White', 'Keldeo', 'Keldeo-Resolute', 'Meloetta', 'Genesect' ] }, { name: "[Gen 5] Custom Game", section: "BW2 Singles", mod: 'gen5', searchShow: false, canUseRandomTeam: true, debug: true, maxLevel: 9999, defaultLevel: 100, // no restrictions, for serious (other than team preview) ruleset: ['Team Preview'] }, // XY Doubles /////////////////////////////////////////////////////////////////// { name: "Smogon Doubles (beta)", section: "XY Doubles", column: 2, gameType: 'doubles', ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Team Preview'], noPokebank: true, banlist: ['Dark Void', 'Soul Dew', 'Mewtwo', 'Mewtwo-Mega-X', 'Mewtwo-Mega-Y', 'Lugia', 'Ho-Oh', 'Kyogre', 'Groudon', 'Rayquaza', 'Dialga', 'Palkia', 'Giratina', 'Giratina-Origin', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fairy', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Reshiram', 'Zekrom', 'Kyurem-White', 'Xerneas', 'Yveltal' ] }, { name: "Pokebank Smogon Doubles (beta)", section: "XY Doubles", column: 2, gameType: 'doubles', ruleset: ['Pokemon', 'Standard Pokebank', 'Evasion Abilities Clause', 'Team Preview'], banlist: ['Dark Void', 'Soul Dew', 'Mewtwo', 'Mewtwo-Mega-X', 'Mewtwo-Mega-Y', 'Lugia', 'Ho-Oh', 'Kyogre', 'Groudon', 'Rayquaza', 'Dialga', 'Palkia', 'Giratina', 'Giratina-Origin', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fairy', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Reshiram', 'Zekrom', 'Kyurem-White', 'Xerneas', 'Yveltal' ] }, { name: "XY Battle Spot Doubles (beta)", section: "XY Doubles", column: 2, gameType: 'doubles', onBegin: function() { this.debug('cutting down to 4'); this.p1.pokemon = this.p1.pokemon.slice(0,4); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0,4); this.p2.pokemonLeft = this.p2.pokemon.length; }, maxForcedLevel: 50, ruleset: ['Pokemon', 'Standard GBU', 'Team Preview VGC'], noPokebank: true, banlist: ['Dark Void'], // Banning Dark Void here because technically Smeargle cannot learn it yet. validateTeam: function(team, format) { if (team.length < 4) return ['You must bring at least 4 Pokemon.']; } }, { name: "VGC 2014 (beta)", section: "XY Doubles", column: 2, gameType: 'doubles', onBegin: function() { this.debug('cutting down to 4'); this.p1.pokemon = this.p1.pokemon.slice(0,4); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0,4); this.p2.pokemonLeft = this.p2.pokemon.length; }, maxForcedLevel: 50, ruleset: ['Pokemon', 'Standard GBU', 'Team Preview VGC', 'Kalos Pokedex'], requirePentagon: true, banlist: [], // The neccessary bans are in Standard GBU validateTeam: function(team, format) { if (team.length < 4) return ['You must bring at least 4 Pokemon.']; } }, { name: "Doubles Challenge Cup", section: 'XY Doubles', gameType: 'doubles', team: 'randomCC', searchShow: false, ruleset: ['Pokemon', 'HP Percentage Mod'] }, { name: "Doubles Custom Game", section: "XY Doubles", column: 2, gameType: 'doubles', searchShow: false, canUseRandomTeam: true, maxLevel: 9999, defaultLevel: 100, debug: true, ruleset: ['Team Preview'] }, // BW2 Doubles /////////////////////////////////////////////////////////////////// { name: "[Gen 5] Smogon Doubles", section: 'BW2 Doubles', column: 2, mod: 'gen5', gameType: 'doubles', ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Team Preview'], banlist: ['Unreleased', 'Illegal', 'Dark Void', 'Soul Dew', 'Sky Drop', 'Mewtwo', 'Lugia', 'Ho-Oh', 'Kyogre', 'Groudon', 'Rayquaza', 'Dialga', 'Palkia', 'Giratina', 'Giratina-Origin', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Reshiram', 'Zekrom', 'Kyurem-White' ] }, { name: "[Gen 5] Doubles VGC 2013", section: 'BW2 Doubles', mod: 'gen5', gameType: 'doubles', onBegin: function() { this.debug('cutting down to 4'); this.p1.pokemon = this.p1.pokemon.slice(0,4); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0,4); this.p2.pokemonLeft = this.p2.pokemon.length; }, maxForcedLevel: 50, ruleset: ['Pokemon', 'Team Preview VGC', 'Species Clause', 'Item Clause'], banlist: ['Unreleased', 'Illegal', 'Sky Drop', 'Dark Void', 'Soul Dew', 'Mewtwo', 'Mew', 'Lugia', 'Ho-Oh', 'Celebi', 'Kyogre', 'Groudon', 'Rayquaza', 'Jirachi', 'Deoxys', 'Deoxys-Attack', 'Deoxys-Speed', 'Deoxys-Defense', 'Chatot', 'Dialga', 'Palkia', 'Giratina', 'Giratina-Origin', 'Phione', 'Manaphy', 'Darkrai', 'Shaymin', 'Shaymin-Sky', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Victini', 'Reshiram', 'Zekrom', 'Kyurem', 'Kyurem-Black', 'Kyurem-White', 'Keldeo', 'Keldeo-Resolute', 'Meloetta', 'Genesect' ] }, { name: "[Gen 5] Doubles Custom Game", section: 'BW2 Doubles', mod: 'gen5', gameType: 'doubles', searchShow: false, canUseRandomTeam: true, debug: true, maxLevel: 9999, defaultLevel: 100, // no restrictions, for serious (other than team preview) ruleset: ['Team Preview'] }, // Other Metagames /////////////////////////////////////////////////////////////////// { name: "[Seasonal] Christmas Charade", section: "OM of the Month", team: 'randomSeasonalCC', ruleset: ['HP Percentage Mod', 'Sleep Clause Mod'], onBegin: function() { this.setWeather('Hail'); delete this.weatherData.duration; }, onModifyMove: function(move) { if (move.id === 'present') { move.category = 'Status'; move.basePower = 0; delete move.heal; move.accuracy = 100; switch (this.random(19)) { case 0: move.onTryHit = function() { this.add('-message', "The present was a bomb!"); }; move.category = 'Physical'; move.basePower = 250; break; case 1: move.onTryHit = function() { this.add('-message', "The present was confusion!"); }; move.volatileStatus = 'confusion'; break; case 2: move.onTryHit = function() { this.add('-message', "The present was Disable!"); }; move.volatileStatus = 'disable'; break; case 3: move.onTryHit = function() { this.add('-message', "The present was a taunt!"); }; move.volatileStatus = 'taunt'; break; case 4: move.onTryHit = function() { this.add('-message', "The present was some seeds!"); }; move.volatileStatus = 'leechseed'; break; case 5: move.onTryHit = function() { this.add('-message', "The present was an embargo!"); }; move.volatileStatus = 'embargo'; break; case 6: move.onTryHit = function() { this.add('-message', "The present was a music box!"); }; move.volatileStatus = 'perishsong'; break; case 7: move.onTryHit = function() { this.add('-message', "The present was a curse!"); }; move.volatileStatus = 'curse'; break; case 8: move.onTryHit = function() { this.add('-message', "The present was Torment!"); }; move.volatileStatus = 'torment'; break; case 9: move.onTryHit = function() { this.add('-message', "The present was a trap!"); }; move.volatileStatus = 'partiallytrapped'; break; case 10: move.onTryHit = function() { this.add('-message', "The present was a root!"); }; move.volatileStatus = 'ingrain'; break; case 11: move.onTryHit = function() { this.add('-message', "The present was a makeover!"); }; var boosts = {}; var possibleBoosts = ['atk','def','spa','spd','spe','accuracy','evasion'].randomize(); boosts[possibleBoosts[0]] = 1; boosts[possibleBoosts[1]] = -1; boosts[possibleBoosts[2]] = -1; move.boosts = boosts; break; case 12: move.onTryHit = function() { this.add('-message', "The present was psychic powers!"); }; move.volatileStatus = 'telekinesis'; break; case 13: move.onTryHit = function() { this.add('-message', "The present was fatigue!"); }; move.volatileStatus = 'mustrecharge'; break; case 14: case 15: move.onTryHit = function() { this.add('-message', "The present was a snowball hit!"); }; move.category = 'Ice'; move.basePower = 250; break; case 16: move.onTryHit = function() { this.add('-message', "The present was a crafty shield!"); }; move.volatileStatus = 'craftyshield'; break; case 17: move.onTryHit = function() { this.add('-message', "The present was an electrification!"); }; move.volatileStatus = 'electrify'; break; case 18: move.onTryHit = function() { this.add('-message', "The present was an ion deluge!"); }; move.volatileStatus = 'iondeluge'; break; } } } }, { name: "Sky Battles", section: "OM of the Month", validateSet: function(set) { var template = this.getTemplate(set.species || set.name); if (template.types.indexOf('Flying') === -1 && set.ability !== 'Levitate') { return [set.species+" is not a Flying type and does not have the ability Levitate."]; } }, ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Team Preview'], banlist: [ // Banned items 'Soul Dew', 'Iron Ball', 'Pinsirite', 'Gengarite', // Banned moves 'Body Slam', 'Bulldoze', 'Dig', 'Dive', 'Earth Power', 'Earthquake', 'Electric Terrain', 'Fire Pledge', 'Fissure', 'Flying Press', 'Frenzy Plant', 'Geomancy', 'Grass Knot', 'Grass Pledge', 'Grassy Terrain', 'Gravity', 'Heavy Slam', 'Ingrain', "Land's Wrath", 'Magnitude', 'Mat Block', 'Misty Terrain', 'Mud Sport', 'Muddy Water', 'Rototiller', 'Seismic Toss', 'Slam', 'Smack Down', 'Spikes', 'Stomp', 'Substitute', 'Surf', 'Toxic Spikes', 'Water Pledge', 'Water Sport', // Banned Pokémon // Illegal Flying-types 'Pidgey', 'Spearow', "Farfetch'd", 'Doduo', 'Dodrio', 'Hoothoot', 'Natu', 'Murkrow', 'Delibird', 'Taillow', 'Starly', 'Chatot', 'Shaymin-Sky', 'Pidove', 'Archen', 'Ducklett', 'Rufflet', 'Vullaby', 'Fletchling', 'Hawlucha', // Illegal Levitators 'Gastly', 'Gengar', // Illegal Megas 'Pinsir-Mega', 'Gengar-Mega', // Illegal Ubers 'Arceus-Flying', 'Giratina', 'Giratina-Origin', 'Ho-Oh', 'Lugia', 'Rayquaza', 'Yveltal' ] }, { name: "CAP (beta)", section: "Other Metagames", ruleset: ['CAP Pokemon', 'Standard Pokebank', 'Team Preview'], banlist: ['Uber', 'Soul Dew'] }, { name: "Challenge Cup", section: "Other Metagames", team: 'randomCC', ruleset: ['Pokemon', 'HP Percentage Mod'] }, { name: "Challenge Cup 1-vs-1", section: "Other Metagames", team: 'randomCC', ruleset: ['Pokemon', 'Team Preview 1v1', 'HP Percentage Mod'], onBegin: function() { this.debug('Cutting down to 1'); this.p1.pokemon = this.p1.pokemon.slice(0, 1); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0, 1); this.p2.pokemonLeft = this.p2.pokemon.length; } }, { name: "Hackmons", section: "Other Metagames", ruleset: ['Pokemon'], banlist: [] }, { name: "Balanced Hackmons", section: "Other Metagames", ruleset: ['Pokemon', 'OHKO Clause'], banlist: ['Wonder Guard', 'Shadow Tag', 'Arena Trap', 'Pure Power', 'Huge Power', 'Parental Bond'] }, { name: "Gen-NEXT OU", section: "Other Metagames", mod: 'gennext', searchShow: false, ruleset: ['Pokemon', 'Standard NEXT', 'Team Preview'], banlist: ['Uber'] }, { name: "Inverse Battle", section: "Other Metagames", mod: 'inverse', ruleset: ['Pokemon', 'Standard', 'Team Preview'], banlist: [ 'Ho-Oh', 'Kangaskhanite', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fairy', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Mewtwo', 'Mewtwo-Mega-X', 'Mewtwo-Mega-Y', 'Yveltal', 'Xerneas' ] }, { name: "OU Monotype", section: "Other Metagames", ruleset: ['Pokemon', 'Standard', 'Same Type Clause', 'Evasion Abilities Clause', 'Team Preview'], banlist: ['Uber', 'Soul Dew', 'Gengarite'] }, { name: "[Gen 5] Glitchmons", section: "Other Metagames", mod: 'gen5', searchShow: false, ruleset: ['Pokemon', 'Team Preview', 'HP Percentage Mod'], banlist: ['Illegal', 'Unreleased'], mimicGlitch: true }, { name: "[Gen 5] 1v1", section: 'Other Metagames', mod: 'gen5', onBegin: function() { this.p1.pokemon = this.p1.pokemon.slice(0,1); this.p1.pokemonLeft = this.p1.pokemon.length; this.p2.pokemon = this.p2.pokemon.slice(0,1); this.p2.pokemonLeft = this.p2.pokemon.length; }, ruleset: ['Pokemon', 'Standard'], banlist: ['Unreleased', 'Illegal', 'Soul Dew', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Blaziken', 'Darkrai', 'Deoxys', 'Deoxys-Attack', 'Dialga', 'Giratina', 'Giratina-Origin', 'Groudon', 'Ho-Oh', 'Kyogre', 'Kyurem-White', 'Lugia', 'Mewtwo', 'Palkia', 'Rayquaza', 'Reshiram', 'Shaymin-Sky', 'Zekrom', 'Memento', 'Explosion', 'Perish Song', 'Destiny Bond', 'Healing Wish', 'Selfdestruct', 'Lunar Dance', 'Final Gambit', 'Focus Sash' ] }, { name: "[Gen 5] PU", section: "Other Metagames", mod: 'gen5', searchShow: false, ruleset: ['NU'], banlist: ["Charizard", "Wartortle", "Kadabra", "Golem", "Haunter", "Exeggutor", "Weezing", "Kangaskhan", "Pinsir", "Lapras", "Ampharos", "Misdreavus", "Piloswine", "Miltank", "Ludicolo", "Swellow", "Gardevoir", "Ninjask", "Torkoal", "Cacturne", "Altaria", "Armaldo", "Gorebyss", "Regirock", "Regice", "Bastiodon", "Floatzel", "Drifblim", "Skuntank", "Lickilicky", "Probopass", "Rotom-Fan", "Samurott", "Musharna", "Gurdurr", "Sawk", "Carracosta", "Garbodor", "Sawsbuck", "Alomomola", "Golurk", "Braviary", "Electabuzz", "Electrode", "Liepard", "Tangela", "Eelektross", "Ditto", "Seismitoad", "Zangoose", "Roselia", "Serperior", "Metang", "Tauros", "Cradily", "Primeape", "Scolipede", "Jynx", "Basculin", "Gigalith", "Camerupt", "Golbat"] }, { name: "[Gen 5] STABmons", section: "Other Metagames", mod: 'gen5', ruleset: ['Pokemon', 'Standard', 'Evasion Abilities Clause', 'Team Preview'], banlist: ['Drizzle ++ Swift Swim', 'Soul Dew', 'Soul Dew', 'Mewtwo', 'Lugia', 'Ho-Oh', 'Blaziken', 'Kyogre', 'Groudon', 'Rayquaza', 'Deoxys', 'Deoxys-Attack', 'Dialga', 'Palkia', 'Giratina', 'Giratina-Origin', 'Manaphy', 'Shaymin-Sky', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Reshiram', 'Zekrom', 'Kyurem-White', 'Genesect' ] }, { name: "[Gen 5] Budgetmons", section: "Other Metagames", mod: 'gen5', searchShow: false, ruleset: ['OU'], banlist: [], validateTeam: function(team, format) { var bst = 0; for (var i=0; i<team.length; i++) { var template = this.getTemplate(team[i].species); Object.values(template.baseStats, function(value) { bst += value; }); } if (bst > 2300) return ['The combined BST of your team is greater than 2300.']; } }, { name: "[Gen 5] Ability Exchange", section: "Other Metagames", mod: 'gen5', searchShow: false, ruleset: ['Pokemon', 'Ability Exchange Pokemon', 'Sleep Clause Mod', 'Species Clause', 'OHKO Clause', 'Moody Clause', 'Evasion Moves Clause', 'HP Percentage Mod', 'Team Preview'], banlist: ['Unreleased', 'Illegal', 'Ignore Illegal Abilities', 'Drizzle ++ Swift Swim', 'Soul Dew', 'Drought ++ Chlorophyll', 'Sand Stream ++ Sand Rush', 'Mewtwo', 'Lugia', 'Ho-Oh', 'Blaziken', 'Kyogre', 'Groudon', 'Rayquaza', 'Deoxys', 'Deoxys-Attack', 'Deoxys-Defense', 'Deoxys-Speed', 'Dialga', 'Palkia', 'Giratina', 'Giratina-Origin', 'Manaphy', 'Darkrai', 'Shaymin-Sky', 'Arceus', 'Arceus-Bug', 'Arceus-Dark', 'Arceus-Dragon', 'Arceus-Electric', 'Arceus-Fighting', 'Arceus-Fire', 'Arceus-Flying', 'Arceus-Ghost', 'Arceus-Grass', 'Arceus-Ground', 'Arceus-Ice', 'Arceus-Poison', 'Arceus-Psychic', 'Arceus-Rock', 'Arceus-Steel', 'Arceus-Water', 'Excadrill', 'Tornadus-Therian', 'Thundurus', 'Reshiram', 'Zekrom', 'Landorus', 'Kyurem-White', 'Genesect', 'Slaking', 'Regigigas' ] }, // Past Generations /////////////////////////////////////////////////////////////////// { name: "[Gen 4] OU (beta)", section: "Past Generations", mod: 'gen4', ruleset: ['Pokemon', 'Standard'], banlist: ['Uber'], column: 2 }, { name: "[Gen 4] UU (beta)", section: "Past Generations", mod: 'gen4', ruleset: ['Pokemon', 'Standard'], banlist: ['Uber', 'OU', 'BL'] }, { name: "[Gen 4] Hackmons", section: "Past Generations", mod: 'gen4', searchShow: false, ruleset: ['Pokemon', 'HP Percentage Mod'], banlist: [] }, { name: "[Gen 4] Custom Game", section: "Past Generations", mod: 'gen4', searchShow: false, debug: true, ruleset: [] }, { name: "[Gen 3] Hackmons", section: "Past Generations", mod: 'gen3', searchShow: false, debug: true, ruleset: ['Pokemon', 'HP Percentage Mod'], banlist: [] }, { name: "[Gen 3] Custom Game", section: "Past Generations", mod: 'gen3', searchShow: false, debug: true, ruleset: [] }, { name: "[Gen 2] OU (beta)", section: "Past Generations", mod: 'gen2', debug: true, ruleset: ['Pokemon', 'Standard'], banlist: ['Uber', 'Mean Look + Hypnosis + Perish Song'] }, { name: "[Gen 2] Custom Game", section: "Past Generations", mod: 'gen2', searchShow: false, debug: true, ruleset: ['Pokemon'] }, { name: "[Gen 1] OU (beta)", section: "Past Generations", mod: 'gen1', ruleset: ['Pokemon', 'Standard'], banlist: ['Uber'] }, { name: "[Gen 1] Custom Game", section: "Past Generations", mod: 'gen1', searchShow: false, debug: true, ruleset: ['Pokemon'] } ];
Ban Kangaskhanite on OU Monotype OU Monotype is following OU's banlist.
config/formats.js
Ban Kangaskhanite on OU Monotype
<ide><path>onfig/formats.js <ide> section: "Other Metagames", <ide> <ide> ruleset: ['Pokemon', 'Standard', 'Same Type Clause', 'Evasion Abilities Clause', 'Team Preview'], <del> banlist: ['Uber', 'Soul Dew', 'Gengarite'] <add> banlist: ['Uber', 'Soul Dew', 'Gengarite', 'Kangaskhanite'] <ide> }, <ide> { <ide> name: "[Gen 5] Glitchmons",
Java
apache-2.0
e44e43de71bb3b613c255156c0a5842f8eb408ab
0
OpenGamma/OG-Tools
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.maven; import static org.twdata.maven.mojoexecutor.MojoExecutor.artifactId; import static org.twdata.maven.mojoexecutor.MojoExecutor.configuration; import static org.twdata.maven.mojoexecutor.MojoExecutor.element; import static org.twdata.maven.mojoexecutor.MojoExecutor.executeMojo; import static org.twdata.maven.mojoexecutor.MojoExecutor.executionEnvironment; import static org.twdata.maven.mojoexecutor.MojoExecutor.goal; import static org.twdata.maven.mojoexecutor.MojoExecutor.groupId; import static org.twdata.maven.mojoexecutor.MojoExecutor.plugin; import static org.twdata.maven.mojoexecutor.MojoExecutor.version; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.opengamma.scripts.ScriptGenerator; import com.opengamma.scripts.ScriptUtils; import com.opengamma.scripts.Scriptable; import freemarker.template.Template; // CSOFF for Javadoc tags /** * Generates scripts from a template based on annotated classes. * * @goal generate-scripts * @phase prepare-package * @requiresDependencyResolution compile * @threadSafe * @description */ // CSON public class ScriptableScriptGeneratorMojo extends AbstractMojo { // no underscore makes m2e auto-complete correct /** * Set to true to skip all processing, default false. * @parameter alias="skip" property="opengamma.generate.scripts.skip" */ private boolean skip; // CSIGNORE /** * Where the scripts should be generated. * @parameter alias="outputDir" default-value="${project.build.directory}/scripts" * @required */ private File outputDir; // CSIGNORE /** * The type to generate. * This is a shortcut, allowing all the files stored in the scripts project * to be accessed without needing to specify lots of config everywhere. * The only recognized value at present is 'tool'. * If this is set, then the unixTemplate and windowsTemplate fields will be * set, and a standard set of additional scripts added. * Use the 'unix' and 'windows' boolean flags to control which is output. * @parameter alias="type" property="opengamma.generate.scripts.type" */ private String type; // CSIGNORE /** * True to generate unix scripts, default true. * @parameter alias="unix" property="opengamma.generate.scripts.unix" default-value="true" */ private boolean unix; // CSIGNORE /** * The basic template file name on Unix. * This is used as the default template file name. * It effectively maps to 'java.lang.Object' in the unixTemplatesMap. * @parameter alias="unixTemplate" */ private String unixTemplate; // CSIGNORE /** * A map of class name to template file name on Unix. * @parameter alias="baseClassTemplateMap" */ private Map<String, String> unixTemplatesMap; // CSIGNORE /** * True to generate windows scripts, default true. * @parameter alias="windows" property="opengamma.generate.scripts.windows" default-value="true" */ private boolean windows; // CSIGNORE /** * The basic template file name on Windows. * This is used as the default template file name. * It effectively maps to 'java.lang.Object' in the windowsTemplatesMap. * @parameter alias="windowsTemplate" */ private String windowsTemplate; // CSIGNORE /** * A map of class name to template file name on Windows. * @parameter alias="baseClassTemplateMap" */ private Map<String, String> windowsTemplatesMap; // CSIGNORE /** * Additional scripts to copy unchanged. * @parameter alias="additionalScripts" */ private String[] additionalScripts; // CSIGNORE /** * Set to true to create an attached zip archive, default true. * @parameter alias="zip" property="opengamma.generate.scripts.zip" default-value="false" */ private boolean zip; // CSIGNORE /** * The project base directory. * @parameter default-value="${project.basedir}" * @required * @readonly */ private File baseDir; // CSIGNORE /** * @parameter default-value="${project}" * @required * @readonly */ private MavenProject project; // CSIGNORE /** * The current Maven session. * * @parameter default-value="${session}" * @required * @readonly */ private MavenSession mavenSession; // CSIGNORE /** * The Maven BuildPluginManager component. * * @component * @required */ private BuildPluginManager mavenPluginManager; // CSIGNORE //------------------------------------------------------------------------- /** * Maven plugin for generating scripts to run tools annotated with {@link Scriptable}. * <p> * Variables available in the Freemarker template are: * <ul> * <li> className - the fully-qualified Java class name * </ul> */ @Override public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { return; } if (type != null) { processType(); } // make the output directory try { FileUtils.forceMkdir(outputDir); } catch (Exception ex) { throw new MojoExecutionException("Error creating output directory " + outputDir.getAbsolutePath(), ex); } // resolve the input Map<String, String> unixMap = buildInputMap(unixTemplate, unixTemplatesMap); Map<String, String> windowsMap = buildInputMap(windowsTemplate, windowsTemplatesMap); URL[] classpathUrls = buildProjectClasspath(project); ClassLoader classLoader = new URLClassLoader(classpathUrls, this.getClass().getClassLoader()); // build the scripts if (unixMap.isEmpty() == false || windowsMap.isEmpty() == false) { List<Class<?>> scriptableClasses = buildScriptableClasses(classpathUrls, classLoader); getLog().info("Generating " + scriptableClasses.size() + " scripts"); if (unix) { generateScripts(unixMap, scriptableClasses, classLoader, false); } if (windows) { generateScripts(windowsMap, scriptableClasses, classLoader, true); } } else { getLog().info("No scripts to generate"); } copyAdditionalScripts(classLoader); if (zip) { buildZip(); } } //------------------------------------------------------------------------- // processes the type, avoiding leaking config everywhere private void processType() throws MojoExecutionException { if (type.equals("tool") == false) { throw new MojoExecutionException("Invalid type, only 'tool' is valid: " + type); } if (StringUtils.isNotEmpty(unixTemplate) || StringUtils.isNotEmpty(windowsTemplate)) { throw new MojoExecutionException("When type is set, unixTemplate and windowsTemplate must not be set"); } Set<String> additional = new HashSet<>(); if (additionalScripts != null) { additional.addAll(Arrays.asList(additionalScripts)); } if (unix) { unixTemplate = "com/opengamma/scripts/templates/tool-template-unix.ftl"; additional.add("com/opengamma/scripts/run-tool.sh"); additional.add("com/opengamma/scripts/java-utils.sh"); additional.add("com/opengamma/scripts/componentserver-init-utils.sh"); additional.add("com/opengamma/scripts/templates/project-utils.sh.ftl"); } if (windows) { windowsTemplate = "com/opengamma/scripts/templates/tool-template-windows.ftl"; additional.add("com/opengamma/scripts/run-tool.bat"); additional.add("com/opengamma/scripts/run-tool-deprecated.bat"); } additionalScripts = (String[]) additional.toArray(new String[additional.size()]); } //------------------------------------------------------------------------- // merges the input template and templateMap private static Map<String, String> buildInputMap(String template, Map<String, String> tempateMap) throws MojoExecutionException { Map<String, String> result = Maps.newHashMap(); if (tempateMap != null) { result.putAll(tempateMap); } if (template != null) { if (result.containsKey("java.lang.Object")) { throw new MojoExecutionException("Cannot specify template if templateMap contains key 'java.lang.Object'"); } result.put("java.lang.Object", template); } return result; } //------------------------------------------------------------------------- // extracts the project classpath from Maven @SuppressWarnings("unchecked") private static URL[] buildProjectClasspath(MavenProject project) throws MojoExecutionException { List<String> classpathElementList; try { classpathElementList = project.getCompileClasspathElements(); } catch (DependencyResolutionRequiredException ex) { throw new MojoExecutionException("Error obtaining dependencies", ex); } return ScriptUtils.getClasspathURLs(classpathElementList); } //------------------------------------------------------------------------- // scans for the Scriptable annotation private static List<Class<?>> buildScriptableClasses(URL[] classpathUrls, ClassLoader classLoader) throws MojoExecutionException { Set<String> scriptableClassNames = ScriptUtils.findClassAnnotation(classpathUrls, Scriptable.class); List<Class<?>> result = Lists.newArrayList(); for (String scriptable : scriptableClassNames) { result.add(resolveClass(scriptable, classLoader)); } return result; } //------------------------------------------------------------------------- // generates the scripts private void generateScripts(Map<String, String> templates, List<Class<?>> scriptableClasses, ClassLoader classLoader, boolean windows) throws MojoExecutionException { if (templates.isEmpty()) { return; } Map<Class<?>, Template> templateMap = resolveTemplateMap(templates, classLoader); for (Class<?> scriptableClass : scriptableClasses) { Map<String, Object> templateData = new HashMap<String, Object>(); templateData.put("className", scriptableClass); templateData.put("project", project.getArtifactId()); Template template = lookupTempate(scriptableClass, templateMap); ScriptGenerator.generate(scriptableClass.getName(), outputDir, template, templateData, windows); } } //------------------------------------------------------------------------- // resolves the template names to templates private Map<Class<?>, Template> resolveTemplateMap(Map<String, String> templates, ClassLoader classLoader) throws MojoExecutionException { Map<Class<?>, Template> templateMap = Maps.newHashMap(); for (Map.Entry<String, String> unresolvedEntry : templates.entrySet()) { String className = unresolvedEntry.getKey(); Class<?> clazz = resolveClass(className, classLoader); Template template = getTemplate(unresolvedEntry.getValue(), classLoader); templateMap.put(clazz, template); } return templateMap; } //------------------------------------------------------------------------- // load a template private Template getTemplate(String templateName, ClassLoader classLoader) throws MojoExecutionException { try { return ScriptGenerator.loadTemplate(baseDir, templateName, classLoader); } catch (Exception ex) { throw new MojoExecutionException("Error loading Freemarker template: " + templateName, ex); } } //------------------------------------------------------------------------- // lookup and find the best matching template private static Template lookupTempate(Class<?> scriptableClass, Map<Class<?>, Template> templateMap) throws MojoExecutionException { Class<?> clazz = scriptableClass; while (clazz != null) { Template template = templateMap.get(clazz); if (template != null) { return template; } clazz = clazz.getSuperclass(); } throw new MojoExecutionException("No template found: " + scriptableClass); } //------------------------------------------------------------------------- // copies any additional scripts private void copyAdditionalScripts(ClassLoader classLoader) throws MojoExecutionException { if (additionalScripts == null || additionalScripts.length == 0) { getLog().info("No additional scripts to copy"); return; } getLog().info("Copying " + additionalScripts.length + " additional script(s)"); for (String script : additionalScripts) { File scriptFile = new File(baseDir, script); // process ftl if necessary if (script.endsWith(".ftl")) { generateAdditionalFile(classLoader, script, scriptFile); } else { // simple copy, either file or resource if (scriptFile.exists()) { copyAdditionalFile(classLoader, script, scriptFile); } else { copyAdditionalResource(classLoader, script, scriptFile); } } } } private void generateAdditionalFile(ClassLoader classLoader, String script, File scriptFile) throws MojoExecutionException { File destinationFile = new File(outputDir, scriptFile.getName().substring(0, scriptFile.getName().length() - 4)); Map<String, Object> templateData = new HashMap<String, Object>(); templateData.put("project", project.getArtifactId()); Template template = getTemplate(script, classLoader); ScriptGenerator.generate(destinationFile, template, templateData); destinationFile.setReadable(true, false); destinationFile.setExecutable(true, false); } private void copyAdditionalFile(ClassLoader classLoader, String script, File scriptFile) throws MojoExecutionException { if (scriptFile.isFile() == false) { throw new MojoExecutionException("Additional script is not a file, directories cannot be copied: " + scriptFile); } try { File destinationFile = new File(outputDir, scriptFile.getName()); FileUtils.copyFileToDirectory(scriptFile, outputDir); destinationFile.setReadable(true, false); destinationFile.setExecutable(true, false); } catch (IOException ex) { throw new MojoExecutionException("Unable to copy additional script file: " + script, ex); } } private void copyAdditionalResource(ClassLoader classLoader, String script, File scriptFile) throws MojoExecutionException { try (InputStream resourceStream = classLoader.getResourceAsStream(script)) { if (resourceStream == null) { throw new MojoExecutionException("Additional script cannot be found: " + script); } File destinationFile = new File(outputDir, scriptFile.getName()); FileUtils.writeByteArrayToFile(destinationFile, IOUtils.toByteArray(resourceStream)); destinationFile.setReadable(true, false); destinationFile.setExecutable(true, false); } catch (IOException ex) { throw new MojoExecutionException("Unable to copy additional script resource: " + script, ex); } } //------------------------------------------------------------------------- // loads a class private static Class<?> resolveClass(String className, ClassLoader classLoader) throws MojoExecutionException { try { return classLoader.loadClass(className); } catch (ClassNotFoundException e) { throw new MojoExecutionException("Unable to resolve class " + className); } } //------------------------------------------------------------------------- // process the zipping private void buildZip() throws MojoExecutionException { // pick correct assembly xml String descriptorResource = "assembly-scripts.xml"; if (unix && !windows) { descriptorResource = "assembly-unix.xml"; } else if (windows && !unix) { descriptorResource = "assembly-windows.xml"; } // copy it to a real file location File descriptorFile = new File(outputDir, new File(descriptorResource).getName()); try (InputStream resourceStream = getClass().getResourceAsStream(descriptorResource)) { if (resourceStream == null) { throw new MojoExecutionException("Assembly descriptor cannot be found: " + descriptorResource); } FileUtils.writeByteArrayToFile(descriptorFile, IOUtils.toByteArray(resourceStream)); descriptorFile.setReadable(true, false); descriptorFile.setExecutable(true, false); } catch (IOException ex) { throw new MojoExecutionException("Unable to copy additional script: " + descriptorFile, ex); } // run the assembly plugin executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-assembly-plugin"), version("2.4") ), goal("single"), configuration( element("descriptors", element("descriptor", descriptorFile.getAbsolutePath())) ), executionEnvironment( project, mavenSession, mavenPluginManager ) ); // delete the temp file descriptorFile.delete(); } }
opengamma-maven-plugin/src/main/java/com/opengamma/maven/ScriptableScriptGeneratorMojo.java
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.maven; import static org.twdata.maven.mojoexecutor.MojoExecutor.artifactId; import static org.twdata.maven.mojoexecutor.MojoExecutor.configuration; import static org.twdata.maven.mojoexecutor.MojoExecutor.element; import static org.twdata.maven.mojoexecutor.MojoExecutor.executeMojo; import static org.twdata.maven.mojoexecutor.MojoExecutor.executionEnvironment; import static org.twdata.maven.mojoexecutor.MojoExecutor.goal; import static org.twdata.maven.mojoexecutor.MojoExecutor.groupId; import static org.twdata.maven.mojoexecutor.MojoExecutor.plugin; import static org.twdata.maven.mojoexecutor.MojoExecutor.version; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.opengamma.scripts.ScriptGenerator; import com.opengamma.scripts.ScriptUtils; import com.opengamma.scripts.Scriptable; import freemarker.template.Template; // CSOFF for Javadoc tags /** * Generates scripts from a template based on annotated classes. * * @goal generate-scripts * @phase prepare-package * @requiresDependencyResolution compile * @threadSafe * @description */ // CSON public class ScriptableScriptGeneratorMojo extends AbstractMojo { // no underscore makes m2e auto-complete correct /** * Set to true to skip all processing, default false. * @parameter alias="skip" property="opengamma.generate.scripts.skip" */ private boolean skip; // CSIGNORE /** * Where the scripts should be generated. * @parameter alias="outputDir" default-value="${project.build.directory}/scripts" * @required */ private File outputDir; // CSIGNORE /** * The type to generate. * This is a shortcut, allowing all the files stored in the scripts project * to be accessed without needing to specify lots of config everywhere. * The only recognized value at present is 'tool'. * If this is set, then the unixTemplate and windowsTemplate fields will be * set, and a standard set of additional scripts added. * Use the 'unix' and 'windows' boolean flags to control which is output. * @parameter alias="type" property="opengamma.generate.scripts.type" */ private String type; // CSIGNORE /** * True to generate unix scripts, default true. * @parameter alias="unix" property="opengamma.generate.scripts.unix" default-value="true" */ private boolean unix; // CSIGNORE /** * The basic template file name on Unix. * This is used as the default template file name. * It effectively maps to 'java.lang.Object' in the unixTemplatesMap. * @parameter alias="unixTemplate" */ private String unixTemplate; // CSIGNORE /** * A map of class name to template file name on Unix. * @parameter alias="baseClassTemplateMap" */ private Map<String, String> unixTemplatesMap; // CSIGNORE /** * True to generate windows scripts, default true. * @parameter alias="windows" property="opengamma.generate.scripts.windows" default-value="true" */ private boolean windows; // CSIGNORE /** * The basic template file name on Windows. * This is used as the default template file name. * It effectively maps to 'java.lang.Object' in the windowsTemplatesMap. * @parameter alias="windowsTemplate" */ private String windowsTemplate; // CSIGNORE /** * A map of class name to template file name on Windows. * @parameter alias="baseClassTemplateMap" */ private Map<String, String> windowsTemplatesMap; // CSIGNORE /** * Additional scripts to copy unchanged. * @parameter alias="additionalScripts" */ private String[] additionalScripts; // CSIGNORE /** * Set to true to create an attached zip archive, default true. * @parameter alias="zip" property="opengamma.generate.scripts.zip" default-value="false" */ private boolean zip; // CSIGNORE /** * The project base directory. * @parameter default-value="${project.basedir}" * @required * @readonly */ private File baseDir; // CSIGNORE /** * @parameter default-value="${project}" * @required * @readonly */ private MavenProject project; // CSIGNORE /** * The current Maven session. * * @parameter default-value="${session}" * @required * @readonly */ private MavenSession mavenSession; // CSIGNORE /** * The Maven BuildPluginManager component. * * @component * @required */ private BuildPluginManager mavenPluginManager; // CSIGNORE //------------------------------------------------------------------------- /** * Maven plugin for generating scripts to run tools annotated with {@link Scriptable}. * <p> * Variables available in the Freemarker template are: * <ul> * <li> className - the fully-qualified Java class name * </ul> */ @Override public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { return; } if (type != null) { processType(); } // make the output directory try { FileUtils.forceMkdir(outputDir); } catch (Exception ex) { throw new MojoExecutionException("Error creating output directory " + outputDir.getAbsolutePath(), ex); } // resolve the input Map<String, String> unixMap = buildInputMap(unixTemplate, unixTemplatesMap); Map<String, String> windowsMap = buildInputMap(windowsTemplate, windowsTemplatesMap); URL[] classpathUrls = buildProjectClasspath(project); ClassLoader classLoader = new URLClassLoader(classpathUrls, this.getClass().getClassLoader()); // build the scripts if (unixMap.isEmpty() == false || windowsMap.isEmpty() == false) { List<Class<?>> scriptableClasses = buildScriptableClasses(classpathUrls, classLoader); getLog().info("Generating " + scriptableClasses.size() + " scripts"); if (unix) { generateScripts(unixMap, scriptableClasses, classLoader, false); } if (windows) { generateScripts(windowsMap, scriptableClasses, classLoader, true); } } else { getLog().info("No scripts to generate"); } copyAdditionalScripts(classLoader); if (zip) { buildZip(); } } //------------------------------------------------------------------------- // processes the type, avoiding leaking config everywhere private void processType() throws MojoExecutionException { if (type.equals("tool") == false) { throw new MojoExecutionException("Invalid type, only 'tool' is valid: " + type); } if (StringUtils.isNotEmpty(unixTemplate) || StringUtils.isNotEmpty(windowsTemplate)) { throw new MojoExecutionException("When type is set, unixTemplate and windowsTemplate must not be set"); } Set<String> additional = new HashSet<>(); if (additionalScripts != null) { additional.addAll(Arrays.asList(additionalScripts)); } if (unix) { unixTemplate = "com/opengamma/scripts/templates/tool-template-unix.ftl"; additional.add("com/opengamma/scripts/run-tool.sh"); additional.add("com/opengamma/scripts/java-utils.sh"); additional.add("com/opengamma/scripts/componentserver-init-utils.sh"); } if (windows) { windowsTemplate = "com/opengamma/scripts/templates/tool-template-windows.ftl"; additional.add("com/opengamma/scripts/run-tool.bat"); additional.add("com/opengamma/scripts/run-tool-deprecated.bat"); } additionalScripts = (String[]) additional.toArray(new String[additional.size()]); } //------------------------------------------------------------------------- // merges the input template and templateMap private static Map<String, String> buildInputMap(String template, Map<String, String> tempateMap) throws MojoExecutionException { Map<String, String> result = Maps.newHashMap(); if (tempateMap != null) { result.putAll(tempateMap); } if (template != null) { if (result.containsKey("java.lang.Object")) { throw new MojoExecutionException("Cannot specify template if templateMap contains key 'java.lang.Object'"); } result.put("java.lang.Object", template); } return result; } //------------------------------------------------------------------------- // extracts the project classpath from Maven @SuppressWarnings("unchecked") private static URL[] buildProjectClasspath(MavenProject project) throws MojoExecutionException { List<String> classpathElementList; try { classpathElementList = project.getCompileClasspathElements(); } catch (DependencyResolutionRequiredException ex) { throw new MojoExecutionException("Error obtaining dependencies", ex); } return ScriptUtils.getClasspathURLs(classpathElementList); } //------------------------------------------------------------------------- // scans for the Scriptable annotation private static List<Class<?>> buildScriptableClasses(URL[] classpathUrls, ClassLoader classLoader) throws MojoExecutionException { Set<String> scriptableClassNames = ScriptUtils.findClassAnnotation(classpathUrls, Scriptable.class); List<Class<?>> result = Lists.newArrayList(); for (String scriptable : scriptableClassNames) { result.add(resolveClass(scriptable, classLoader)); } return result; } //------------------------------------------------------------------------- // generates the scripts private void generateScripts(Map<String, String> templates, List<Class<?>> scriptableClasses, ClassLoader classLoader, boolean windows) throws MojoExecutionException { if (templates.isEmpty()) { return; } Map<Class<?>, Template> templateMap = resolveTemplateMap(templates, classLoader); for (Class<?> scriptableClass : scriptableClasses) { Map<String, Object> templateData = new HashMap<String, Object>(); templateData.put("className", scriptableClass); templateData.put("project", project.getArtifactId()); Template template = lookupTempate(scriptableClass, templateMap); ScriptGenerator.generate(scriptableClass.getName(), outputDir, template, templateData, windows); } } //------------------------------------------------------------------------- // resolves the template names to templates private Map<Class<?>, Template> resolveTemplateMap(Map<String, String> templates, ClassLoader classLoader) throws MojoExecutionException { Map<Class<?>, Template> templateMap = Maps.newHashMap(); for (Map.Entry<String, String> unresolvedEntry : templates.entrySet()) { String className = unresolvedEntry.getKey(); Class<?> clazz = resolveClass(className, classLoader); Template template = getTemplate(unresolvedEntry.getValue(), classLoader); templateMap.put(clazz, template); } return templateMap; } //------------------------------------------------------------------------- // load a template private Template getTemplate(String templateName, ClassLoader classLoader) throws MojoExecutionException { try { return ScriptGenerator.loadTemplate(baseDir, templateName, classLoader); } catch (Exception ex) { throw new MojoExecutionException("Error loading Freemarker template: " + templateName, ex); } } //------------------------------------------------------------------------- // lookup and find the best matching template private static Template lookupTempate(Class<?> scriptableClass, Map<Class<?>, Template> templateMap) throws MojoExecutionException { Class<?> clazz = scriptableClass; while (clazz != null) { Template template = templateMap.get(clazz); if (template != null) { return template; } clazz = clazz.getSuperclass(); } throw new MojoExecutionException("No template found: " + scriptableClass); } //------------------------------------------------------------------------- // copies any additional scripts private void copyAdditionalScripts(ClassLoader classLoader) throws MojoExecutionException { if (additionalScripts == null || additionalScripts.length == 0) { getLog().info("No additional scripts to copy"); return; } getLog().info("Copying " + additionalScripts.length + " additional script(s)"); for (String script : additionalScripts) { // try file File scriptFile = new File(baseDir, script); File destinationFile = new File(outputDir, scriptFile.getName()); if (scriptFile.exists()) { if (scriptFile.isFile() == false) { throw new MojoExecutionException("Additional script is not a file, directories cannot be copied: " + scriptFile); } try { FileUtils.copyFileToDirectory(scriptFile, outputDir); destinationFile.setReadable(true, false); destinationFile.setExecutable(true, false); } catch (IOException ex) { throw new MojoExecutionException("Unable to copy additional script: " + scriptFile, ex); } } else { // then try resource try (InputStream resourceStream = classLoader.getResourceAsStream(script)) { if (resourceStream == null) { throw new MojoExecutionException("Additional script cannot be found: " + script); } FileUtils.writeByteArrayToFile(destinationFile, IOUtils.toByteArray(resourceStream)); destinationFile.setReadable(true, false); destinationFile.setExecutable(true, false); } catch (IOException ex) { throw new MojoExecutionException("Unable to copy additional script: " + scriptFile, ex); } } } } //------------------------------------------------------------------------- // loads a class private static Class<?> resolveClass(String className, ClassLoader classLoader) throws MojoExecutionException { try { return classLoader.loadClass(className); } catch (ClassNotFoundException e) { throw new MojoExecutionException("Unable to resolve class " + className); } } //------------------------------------------------------------------------- // process the zipping private void buildZip() throws MojoExecutionException { // pick correct assembly xml String descriptorResource = "assembly-scripts.xml"; if (unix && !windows) { descriptorResource = "assembly-unix.xml"; } else if (windows && !unix) { descriptorResource = "assembly-windows.xml"; } // copy it to a real file location File descriptorFile = new File(outputDir, new File(descriptorResource).getName()); try (InputStream resourceStream = getClass().getResourceAsStream(descriptorResource)) { if (resourceStream == null) { throw new MojoExecutionException("Assembly descriptor cannot be found: " + descriptorResource); } FileUtils.writeByteArrayToFile(descriptorFile, IOUtils.toByteArray(resourceStream)); descriptorFile.setReadable(true, false); descriptorFile.setExecutable(true, false); } catch (IOException ex) { throw new MojoExecutionException("Unable to copy additional script: " + descriptorFile, ex); } // run the assembly plugin executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-assembly-plugin"), version("2.4") ), goal("single"), configuration( element("descriptors", element("descriptor", descriptorFile.getAbsolutePath())) ), executionEnvironment( project, mavenSession, mavenPluginManager ) ); // delete the temp file descriptorFile.delete(); } }
[PLAT-3579] Allow additional scripts to be generated
opengamma-maven-plugin/src/main/java/com/opengamma/maven/ScriptableScriptGeneratorMojo.java
[PLAT-3579] Allow additional scripts to be generated
<ide><path>pengamma-maven-plugin/src/main/java/com/opengamma/maven/ScriptableScriptGeneratorMojo.java <ide> additional.add("com/opengamma/scripts/run-tool.sh"); <ide> additional.add("com/opengamma/scripts/java-utils.sh"); <ide> additional.add("com/opengamma/scripts/componentserver-init-utils.sh"); <add> additional.add("com/opengamma/scripts/templates/project-utils.sh.ftl"); <ide> } <ide> if (windows) { <ide> windowsTemplate = "com/opengamma/scripts/templates/tool-template-windows.ftl"; <ide> } <ide> getLog().info("Copying " + additionalScripts.length + " additional script(s)"); <ide> for (String script : additionalScripts) { <del> // try file <ide> File scriptFile = new File(baseDir, script); <add> // process ftl if necessary <add> if (script.endsWith(".ftl")) { <add> generateAdditionalFile(classLoader, script, scriptFile); <add> } else { <add> // simple copy, either file or resource <add> if (scriptFile.exists()) { <add> copyAdditionalFile(classLoader, script, scriptFile); <add> } else { <add> copyAdditionalResource(classLoader, script, scriptFile); <add> } <add> } <add> } <add> } <add> <add> private void generateAdditionalFile(ClassLoader classLoader, String script, File scriptFile) throws MojoExecutionException { <add> File destinationFile = new File(outputDir, scriptFile.getName().substring(0, scriptFile.getName().length() - 4)); <add> Map<String, Object> templateData = new HashMap<String, Object>(); <add> templateData.put("project", project.getArtifactId()); <add> Template template = getTemplate(script, classLoader); <add> ScriptGenerator.generate(destinationFile, template, templateData); <add> destinationFile.setReadable(true, false); <add> destinationFile.setExecutable(true, false); <add> } <add> <add> private void copyAdditionalFile(ClassLoader classLoader, String script, File scriptFile) throws MojoExecutionException { <add> if (scriptFile.isFile() == false) { <add> throw new MojoExecutionException("Additional script is not a file, directories cannot be copied: " + scriptFile); <add> } <add> try { <ide> File destinationFile = new File(outputDir, scriptFile.getName()); <del> if (scriptFile.exists()) { <del> if (scriptFile.isFile() == false) { <del> throw new MojoExecutionException("Additional script is not a file, directories cannot be copied: " + scriptFile); <del> } <del> try { <del> FileUtils.copyFileToDirectory(scriptFile, outputDir); <del> destinationFile.setReadable(true, false); <del> destinationFile.setExecutable(true, false); <del> } catch (IOException ex) { <del> throw new MojoExecutionException("Unable to copy additional script: " + scriptFile, ex); <del> } <del> } else { <del> // then try resource <del> try (InputStream resourceStream = classLoader.getResourceAsStream(script)) { <del> if (resourceStream == null) { <del> throw new MojoExecutionException("Additional script cannot be found: " + script); <del> } <del> FileUtils.writeByteArrayToFile(destinationFile, IOUtils.toByteArray(resourceStream)); <del> destinationFile.setReadable(true, false); <del> destinationFile.setExecutable(true, false); <del> } catch (IOException ex) { <del> throw new MojoExecutionException("Unable to copy additional script: " + scriptFile, ex); <del> } <del> } <add> FileUtils.copyFileToDirectory(scriptFile, outputDir); <add> destinationFile.setReadable(true, false); <add> destinationFile.setExecutable(true, false); <add> } catch (IOException ex) { <add> throw new MojoExecutionException("Unable to copy additional script file: " + script, ex); <add> } <add> } <add> <add> private void copyAdditionalResource(ClassLoader classLoader, String script, File scriptFile) throws MojoExecutionException { <add> try (InputStream resourceStream = classLoader.getResourceAsStream(script)) { <add> if (resourceStream == null) { <add> throw new MojoExecutionException("Additional script cannot be found: " + script); <add> } <add> File destinationFile = new File(outputDir, scriptFile.getName()); <add> FileUtils.writeByteArrayToFile(destinationFile, IOUtils.toByteArray(resourceStream)); <add> destinationFile.setReadable(true, false); <add> destinationFile.setExecutable(true, false); <add> } catch (IOException ex) { <add> throw new MojoExecutionException("Unable to copy additional script resource: " + script, ex); <ide> } <ide> } <ide>
JavaScript
mit
68788ab8f2ee38336ae487a49606ee8e7eb86b70
0
Masoumeh/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,PonteIneptique/arethusa,latin-language-toolkit/arethusa,Masoumeh/arethusa,alpheios-project/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa
"use strict"; angular.module('arethusa.depTree').directive('unusedTokenHighlighter', [ 'state', function(state) { return { restrict: 'A', scope: { highlightMode: '@unusedTokenHighlighter', style: '=unusedTokenStyle' }, link: function(scope, element, attrs) { var unusedTokens; var headWatches = []; var style = scope.style || { "background-color": "rgb(255, 216, 216)" }; // a very light red var highlightMode = !!scope.highlightMode; scope.s = state; function tokensWithoutHeadCount() { return state.countTokens(function (token) { return hasNoHead(token); }); } function hasNoHead(token) { return !(token.head || {}).id; } function findUnusedTokens() { angular.forEach(state.tokens, function(token, id) { if (hasNoHead(token)) { scope.unusedCount++; unusedTokens[id] = true; } }); } function initHeadWatches() { destroyOldHeadWatches(); angular.forEach(state.tokens, function(token, id) { var childScope = scope.$new(); childScope.head = token.head; childScope.id = id; childScope.$watch('head.id', function(newVal, oldVal) { if (newVal !== oldVal) { if (newVal) { scope.unusedCount--; delete unusedTokens[id]; if (highlightMode) removeStyle(id); } else { scope.unusedCount++; unusedTokens[id] = true; if (highlightMode) state.addStyle(id, style); } } }); headWatches.push(childScope); }); } function destroyOldHeadWatches() { angular.forEach(headWatches, function(childScope, i) { childScope.$destroy(); }); headWatches = []; } function init() { scope.total = state.totalTokens; scope.unusedCount = 0; unusedTokens = {}; findUnusedTokens(); initHeadWatches(); if (highlightMode) applyHighlighting(); } function applyHighlighting() { angular.forEach(unusedTokens, function(val, id) { state.addStyle(id, style); }); } function removeStyle(id) { var styles = Object.keys(style); state.removeStyle(id, styles); } function unapplyHighlighting() { angular.forEach(unusedTokens, function(val, id) { removeStyle(id); }); } element.bind('click', function() { scope.$apply(function() { if (highlightMode) { unapplyHighlighting(); } else { applyHighlighting(); } }); highlightMode = !highlightMode; }); scope.$watch('s.tokens', function(newVal, oldVal) { init(); }); }, template: '{{ unusedCount }} of {{ total }} unused' }; } ]);
app/js/arethusa.dep_tree/directives/unused_token_highlighter.js
"use strict"; angular.module('arethusa.depTree').directive('unusedTokenHighlighter', [ 'state', function(state) { return { restrict: 'A', scope: { highlightMode: '@unusedTokenHighlighter', style: '=unusedTokenStyle' }, link: function(scope, element, attrs) { var unusedTokens; var headWatches = []; var style = scope.style || { "font-style": "italic" }; var highlightMode = !!scope.highlightMode; scope.s = state; function tokensWithoutHeadCount() { return state.countTokens(function (token) { return hasNoHead(token); }); } function hasNoHead(token) { return !(token.head || {}).id; } function findUnusedTokens() { angular.forEach(state.tokens, function(token, id) { if (hasNoHead(token)) { scope.unusedCount++; unusedTokens[id] = true; } }); } function initHeadWatches() { destroyOldHeadWatches(); angular.forEach(state.tokens, function(token, id) { var childScope = scope.$new(); childScope.head = token.head; childScope.id = id; childScope.$watch('head.id', function(newVal, oldVal) { if (newVal !== oldVal) { if (newVal) { scope.unusedCount--; delete unusedTokens[id]; if (highlightMode) removeStyle(id); } else { scope.unusedCount++; unusedTokens[id] = true; if (highlightMode) state.addStyle(id, style); } } }); headWatches.push(childScope); }); } function destroyOldHeadWatches() { angular.forEach(headWatches, function(childScope, i) { childScope.$destroy(); }); headWatches = []; } function init() { scope.total = state.totalTokens; scope.unusedCount = 0; unusedTokens = {}; findUnusedTokens(); initHeadWatches(); if (highlightMode) applyHighlighting(); } function applyHighlighting() { angular.forEach(unusedTokens, function(val, id) { state.addStyle(id, style); }); } function removeStyle(id) { var styles = Object.keys(style); state.removeStyle(id, styles); } function unapplyHighlighting() { angular.forEach(unusedTokens, function(val, id) { removeStyle(id); }); } element.bind('click', function() { scope.$apply(function() { if (highlightMode) { unapplyHighlighting(); } else { applyHighlighting(); } }); highlightMode = !highlightMode; }); scope.$watch('s.tokens', function(newVal, oldVal) { init(); }); }, template: '{{ unusedCount }} of {{ total }} unused' }; } ]);
More prominent highlighting for uTH by default
app/js/arethusa.dep_tree/directives/unused_token_highlighter.js
More prominent highlighting for uTH by default
<ide><path>pp/js/arethusa.dep_tree/directives/unused_token_highlighter.js <ide> link: function(scope, element, attrs) { <ide> var unusedTokens; <ide> var headWatches = []; <del> var style = scope.style || { "font-style": "italic" }; <add> var style = scope.style || { "background-color": "rgb(255, 216, 216)" }; // a very light red <ide> var highlightMode = !!scope.highlightMode; <ide> scope.s = state; <ide>
JavaScript
mit
d4439d752e775465f3d207e20e61faecce66d468
0
mskalandunas/riverine-docs
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(1); __webpack_require__(5); var _react = __webpack_require__(7); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(38); var _riverine = __webpack_require__(184); var _riverine2 = _interopRequireDefault(_riverine); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Root = function Root() { return _react2.default.createElement( 'div', null, _react2.default.createElement(_riverine2.default, { hover: true, source: 'audio/1.mp3' }) ); }; (0, _reactDom.render)(_react2.default.createElement(Root, null), document.querySelector('#root')); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__(2); if(typeof content === 'string') content = [[module.id, content, '']]; // add the styles to the DOM var update = __webpack_require__(4)(content, {}); if(content.locals) module.exports = content.locals; // Hot Module Replacement if(false) { // When the styles change, update the <style> tags if(!content.locals) { module.hot.accept("!!./../../node_modules/css-loader/index.js!./style.css", function() { var newContent = require("!!./../../node_modules/css-loader/index.js!./style.css"); if(typeof newContent === 'string') newContent = [[module.id, newContent, '']]; update(newContent); }); } // When the module is disposed, remove the <style> tags module.hot.dispose(function() { update(); }); } /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(3)(); // imports // module exports.push([module.id, "html {\n background-color: #f2f2f2;\n}\n\nbody {\n text-rendering: optimizeLegibility;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.004);\n cursor: default;\n color: #2b2b2b;\n}\n\na.link {\n text-decoration: none;\n color: #808080;\n position: relative;\n -moz-transition: all 250ms ease-in-out;\n -webkit-transition: all 250ms ease-in-out;\n -o-transition: all 250ms ease-in-out;\n transition: all 250ms ease-in-out;\n}\n\na.link:after {\n position: absolute;\n bottom: -2px;\n left: 0;\n width: 50%;\n height: 3px;\n background: #808080;\n -ms-filter: \"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)\";\n filter: alpha(opacity=(50));\n opacity: 0.5;\n content: \"\";\n -moz-transition: all 250ms ease-in-out;\n -webkit-transition: all 250ms ease-in-out;\n -o-transition: all 250ms ease-in-out;\n transition: all 250ms ease-in-out;\n}\n\na.link:hover {\n color: #ff5f6d;\n}\n\na.link:hover:after {\n width: 99%;\n background: #ff5f6d;\n}\n\na.mosaic-icon:hover svg g {\n fill: #ffc371;\n}\n\nfooter p {\n text-align: center;\n margin: 2em 0;\n}\n\nfooter p span a {\n text-decoration: none;\n color: #5a5a5a;\n font-size: 1.1em;\n}\n\nfooter p span:not(:first-child) {\n margin-left: 30px;\n}\n\nfooter p span a i:before,\nsvg g {\n transition: 0.3s ease;\n}\n\na:hover i.fa-github {\n color: #4078c0;\n}\n\na:hover i.fa-linkedin {\n color: #0077B5;\n}\n\nh1, h2, h3, h4, h5, h6 {\n font-family: 'Merriweather Sans', sans-serif;\n}\n\nh1 {\n font-size: 4.15em;\n text-align: center;\n letter-spacing: .418em;\n margin-bottom: 2em;\n}\n\nhr {\n height: .2em;\n background-color: rgba(90, 90, 90, 0.5);\n border-style: none;\n border-width: 0;\n margin: 4em 0 3em;\n}\n\nmain {\n padding: 200px 10px 0;\n}\n\np {\n font-family: 'Noto Serif', serif;\n font-size: 1.35em;\n letter-spacing: 0.05em;\n line-height: 1.8em;\n text-align: justify;\n}\n\nsvg {\n width: 20px;\n padding-top: 1px;\n}\n\n.container {\n max-width: 500px;\n margin: 0 auto;\n}\n\n.code {\n font-family: 'Ubuntu Mono', monospace;\n color: #5a5a5a;\n font-size: 1.15em;\n padding-left: 1.5em;\n margin: 4em 0;\n background: -webkit-linear-gradient(right, red, #2b2b2b);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n}\n\n::selection {\n background-color: rgba(0, 0, 0, 0);\n}\n\n@media screen and (max-width: 600px) {\n h1 {\n letter-spacing: .2em;\n font-size: 3.5em;\n margin-bottom: 1em;\n }\n}\n\n@media screen and (max-width: 500px) {\n p {\n font-size: 1em;\n }\n\n .code {\n font-size: .8em;\n }\n\n svg {\n width: .8em;\n }\n}\n", ""]); // exports /***/ }, /* 3 */ /***/ function(module, exports) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ // css base code, injected by the css-loader module.exports = function() { var list = []; // return the list of modules as css string list.toString = function toString() { var result = []; for(var i = 0; i < this.length; i++) { var item = this[i]; if(item[2]) { result.push("@media " + item[2] + "{" + item[1] + "}"); } else { result.push(item[1]); } } return result.join(""); }; // import a list of modules into the list list.i = function(modules, mediaQuery) { if(typeof modules === "string") modules = [[null, modules, ""]]; var alreadyImportedModules = {}; for(var i = 0; i < this.length; i++) { var id = this[i][0]; if(typeof id === "number") alreadyImportedModules[id] = true; } for(i = 0; i < modules.length; i++) { var item = modules[i]; // skip already imported module // this implementation is not 100% perfect for weird media query combinations // when a module is imported multiple times with different media queries. // I hope this will never occur (Hey this way we have smaller bundles) if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) { if(mediaQuery && !item[2]) { item[2] = mediaQuery; } else if(mediaQuery) { item[2] = "(" + item[2] + ") and (" + mediaQuery + ")"; } list.push(item); } } }; return list; }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var stylesInDom = {}, memoize = function(fn) { var memo; return function () { if (typeof memo === "undefined") memo = fn.apply(this, arguments); return memo; }; }, isOldIE = memoize(function() { return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase()); }), getHeadElement = memoize(function () { return document.head || document.getElementsByTagName("head")[0]; }), singletonElement = null, singletonCounter = 0, styleElementsInsertedAtTop = []; module.exports = function(list, options) { if(false) { if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment"); } options = options || {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style> // tags it will allow on a page if (typeof options.singleton === "undefined") options.singleton = isOldIE(); // By default, add <style> tags to the bottom of <head>. if (typeof options.insertAt === "undefined") options.insertAt = "bottom"; var styles = listToStyles(list); addStylesToDom(styles, options); return function update(newList) { var mayRemove = []; for(var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; domStyle.refs--; mayRemove.push(domStyle); } if(newList) { var newStyles = listToStyles(newList); addStylesToDom(newStyles, options); } for(var i = 0; i < mayRemove.length; i++) { var domStyle = mayRemove[i]; if(domStyle.refs === 0) { for(var j = 0; j < domStyle.parts.length; j++) domStyle.parts[j](); delete stylesInDom[domStyle.id]; } } }; } function addStylesToDom(styles, options) { for(var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; if(domStyle) { domStyle.refs++; for(var j = 0; j < domStyle.parts.length; j++) { domStyle.parts[j](item.parts[j]); } for(; j < item.parts.length; j++) { domStyle.parts.push(addStyle(item.parts[j], options)); } } else { var parts = []; for(var j = 0; j < item.parts.length; j++) { parts.push(addStyle(item.parts[j], options)); } stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts}; } } } function listToStyles(list) { var styles = []; var newStyles = {}; for(var i = 0; i < list.length; i++) { var item = list[i]; var id = item[0]; var css = item[1]; var media = item[2]; var sourceMap = item[3]; var part = {css: css, media: media, sourceMap: sourceMap}; if(!newStyles[id]) styles.push(newStyles[id] = {id: id, parts: [part]}); else newStyles[id].parts.push(part); } return styles; } function insertStyleElement(options, styleElement) { var head = getHeadElement(); var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1]; if (options.insertAt === "top") { if(!lastStyleElementInsertedAtTop) { head.insertBefore(styleElement, head.firstChild); } else if(lastStyleElementInsertedAtTop.nextSibling) { head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling); } else { head.appendChild(styleElement); } styleElementsInsertedAtTop.push(styleElement); } else if (options.insertAt === "bottom") { head.appendChild(styleElement); } else { throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'."); } } function removeStyleElement(styleElement) { styleElement.parentNode.removeChild(styleElement); var idx = styleElementsInsertedAtTop.indexOf(styleElement); if(idx >= 0) { styleElementsInsertedAtTop.splice(idx, 1); } } function createStyleElement(options) { var styleElement = document.createElement("style"); styleElement.type = "text/css"; insertStyleElement(options, styleElement); return styleElement; } function createLinkElement(options) { var linkElement = document.createElement("link"); linkElement.rel = "stylesheet"; insertStyleElement(options, linkElement); return linkElement; } function addStyle(obj, options) { var styleElement, update, remove; if (options.singleton) { var styleIndex = singletonCounter++; styleElement = singletonElement || (singletonElement = createStyleElement(options)); update = applyToSingletonTag.bind(null, styleElement, styleIndex, false); remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true); } else if(obj.sourceMap && typeof URL === "function" && typeof URL.createObjectURL === "function" && typeof URL.revokeObjectURL === "function" && typeof Blob === "function" && typeof btoa === "function") { styleElement = createLinkElement(options); update = updateLink.bind(null, styleElement); remove = function() { removeStyleElement(styleElement); if(styleElement.href) URL.revokeObjectURL(styleElement.href); }; } else { styleElement = createStyleElement(options); update = applyToTag.bind(null, styleElement); remove = function() { removeStyleElement(styleElement); }; } update(obj); return function updateStyle(newObj) { if(newObj) { if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) return; update(obj = newObj); } else { remove(); } }; } var replaceText = (function () { var textStore = []; return function (index, replacement) { textStore[index] = replacement; return textStore.filter(Boolean).join('\n'); }; })(); function applyToSingletonTag(styleElement, index, remove, obj) { var css = remove ? "" : obj.css; if (styleElement.styleSheet) { styleElement.styleSheet.cssText = replaceText(index, css); } else { var cssNode = document.createTextNode(css); var childNodes = styleElement.childNodes; if (childNodes[index]) styleElement.removeChild(childNodes[index]); if (childNodes.length) { styleElement.insertBefore(cssNode, childNodes[index]); } else { styleElement.appendChild(cssNode); } } } function applyToTag(styleElement, obj) { var css = obj.css; var media = obj.media; if(media) { styleElement.setAttribute("media", media) } if(styleElement.styleSheet) { styleElement.styleSheet.cssText = css; } else { while(styleElement.firstChild) { styleElement.removeChild(styleElement.firstChild); } styleElement.appendChild(document.createTextNode(css)); } } function updateLink(linkElement, obj) { var css = obj.css; var sourceMap = obj.sourceMap; if(sourceMap) { // http://stackoverflow.com/a/26603875 css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */"; } var blob = new Blob([css], { type: "text/css" }); var oldSrc = linkElement.href; linkElement.href = URL.createObjectURL(blob); if(oldSrc) URL.revokeObjectURL(oldSrc); } /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__(6); if(typeof content === 'string') content = [[module.id, content, '']]; // add the styles to the DOM var update = __webpack_require__(4)(content, {}); if(content.locals) module.exports = content.locals; // Hot Module Replacement if(false) { // When the styles change, update the <style> tags if(!content.locals) { module.hot.accept("!!./../../node_modules/css-loader/index.js!./player.css", function() { var newContent = require("!!./../../node_modules/css-loader/index.js!./player.css"); if(typeof newContent === 'string') newContent = [[module.id, newContent, '']]; update(newContent); }); } // When the module is disposed, remove the <style> tags module.hot.dispose(function() { update(); }); } /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(3)(); // imports // module exports.push([module.id, ".fa-play, .fa-pause {\n background: -webkit-linear-gradient(left, #ff5f6d, #2b2b2b);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n transition: 0.2s ease;\n -moz-transition: 0.2s ease;\n -webkit-transition: 0.2s ease;\n}\n\n.fa-play:hover, .fa-pause:hover {\n opacity: 0.5;\n}\n\n.riverine-player,.riverine-audio {\n width: 100%;\n margin: 25px auto;\n}\n\n.riverine-gui {\n position: relative;\n overflow: hidden;\n margin-top: 10px;\n}\n\n.riverine-seek-bar, .riverine-play-bar {\n max-width: 100%;\n}\n\n.riverine-controls {\n padding: 0;\n margin: 0;\n list-style: none;\n font-family: \"FontAwesome\";\n}\n\n.riverine-controls li {\n display: inline;\n}\n\n.riverine-controls a {\n color: rgba(0, 0, 0, 0.6);\n}\n\n.riverine-play,.riverine-pause {\n width: 14px;\n height: 59px;\n display: inline-block;\n line-height: 59px;\n cursor: pointer;\n}\n\n.riverine-play i {\n transition: 0.2s ease;\n -moz-transition: 0.2s ease;\n -webkit-transition: 0.2s ease;\n}\n\n.riverine-seek-bar {\n width: 0;\n top: 1px;\n height: 2px;\n background-color: rgba(255,255,255,.5);\n}\n\n.riverine-title ul, .riverine-time-holder {\n font-family: 'Ubuntu Mono', monospace;\n color: rgba(0, 0, 0, 0.6);\n font-size: 16px;\n line-height: 30px;\n position: absolute;\n top: 14px;\n pointer-events: none;\n}\n\n.riverine-time-holder {\n right: 15px;\n}\n\n.riverine-title ul {\n left: 35px;\n list-style: none;\n}\n\n.riverine-progress {\n overflow: hidden;\n position: absolute;\n left: 20px;\n top: 0;\n width: calc(100% - 150px);\n cursor: pointer;\n background-color: rgba(0, 0, 0, 0.3);\n height: 2px;\n margin-top: 28px;\n}\n\n.riverine-play-bar {\n width: 0;\n top: 1px;\n height: 2px;\n background-color: #f2f2f2;\n transition: 0.1s ease;\n}\n\n@media (max-width: 1150px) {\n .riverine-title ul {\n font-size: 10px;\n }\n}\n", ""]); // exports /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(8); /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var ReactChildren = __webpack_require__(11); var ReactComponent = __webpack_require__(24); var ReactPureComponent = __webpack_require__(27); var ReactClass = __webpack_require__(28); var ReactDOMFactories = __webpack_require__(30); var ReactElement = __webpack_require__(15); var ReactPropTypes = __webpack_require__(35); var ReactVersion = __webpack_require__(36); var onlyChild = __webpack_require__(37); var warning = __webpack_require__(17); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if (process.env.NODE_ENV !== 'production') { var ReactElementValidator = __webpack_require__(31); createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var __spread = _assign; if (process.env.NODE_ENV !== 'production') { var warned = false; __spread = function () { process.env.NODE_ENV !== 'production' ? warning(warned, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See https://fb.me/react-spread-deprecation for more details.') : void 0; warned = true; return _assign.apply(null, arguments); }; } var React = { // Modern Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, toArray: ReactChildren.toArray, only: onlyChild }, Component: ReactComponent, PureComponent: ReactPureComponent, createElement: createElement, cloneElement: cloneElement, isValidElement: ReactElement.isValidElement, // Classic PropTypes: ReactPropTypes, createClass: ReactClass.createClass, createFactory: createFactory, createMixin: function (mixin) { // Currently a noop. Will be used to validate and trace mixins. return mixin; }, // This looks DOM specific but these are actually isomorphic helpers // since they are just generating DOM strings. DOM: ReactDOMFactories, version: ReactVersion, // Deprecated hook for JSX spread, don't use this for anything. __spread: __spread }; module.exports = React; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 9 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 10 */ /***/ function(module, exports) { /* object-assign (c) Sindre Sorhus @license MIT */ 'use strict'; /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var PooledClass = __webpack_require__(12); var ReactElement = __webpack_require__(15); var emptyFunction = __webpack_require__(18); var traverseAllChildren = __webpack_require__(21); var twoArgumentPooler = PooledClass.twoArgumentPooler; var fourArgumentPooler = PooledClass.fourArgumentPooler; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/'); } /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.func = forEachFunction; this.context = forEachContext; this.count = 0; } ForEachBookKeeping.prototype.destructor = function () { this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func, context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) { this.result = mapResult; this.keyPrefix = keyPrefix; this.func = mapFunction; this.context = mapContext; this.count = 0; } MapBookKeeping.prototype.destructor = function () { this.result = null; this.keyPrefix = null; this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result, keyPrefix = bookKeeping.keyPrefix, func = bookKeeping.func, context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument); } else if (mappedChild != null) { if (ReactElement.isValidElement(mappedChild)) { mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.map * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } function forEachSingleChildDummy(traverseContext, child, name) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.count * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument); return result; } var ReactChildren = { forEach: forEachChildren, map: mapChildren, mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, count: countChildren, toArray: toArray }; module.exports = ReactChildren; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(13); var invariant = __webpack_require__(14); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances. * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { // Casting as any so that flow ignores the actual implementation and trusts // it to match the type we declared var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler }; module.exports = PooledClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 13 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * WARNING: DO NOT manually require this module. * This is a replacement for `invariant(...)` used by the error code system * and will _only_ be required by the corresponding babel pass. * It always throws. */ function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; } module.exports = reactProdInvariant; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if (process.env.NODE_ENV !== 'production') { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var ReactCurrentOwner = __webpack_require__(16); var warning = __webpack_require__(17); var canDefineProperty = __webpack_require__(19); var hasOwnProperty = Object.prototype.hasOwnProperty; var REACT_ELEMENT_TYPE = __webpack_require__(20); var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown; function hasValidRef(config) { if (process.env.NODE_ENV !== 'production') { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { if (process.env.NODE_ENV !== 'production') { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; process.env.NODE_ENV !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0; } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; process.env.NODE_ENV !== 'production' ? warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0; } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, no instanceof check * will work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allow us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; if (process.env.NODE_ENV !== 'production') { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. if (canDefineProperty) { Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); } else { element._store.validated = false; element._self = self; element._source = source; } if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createelement */ ReactElement.createElement = function (type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; } if (hasValidKey(config)) { key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } if (process.env.NODE_ENV !== 'production') { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if (process.env.NODE_ENV !== 'production') { if (key || ref) { if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); }; /** * Return a function that produces ReactElements of a given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory */ ReactElement.createFactory = function (type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. `<Foo />.type === Foo`. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceKey = function (oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; }; /** * Clone and return a new ReactElement using element as the starting point. * See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement */ ReactElement.cloneElement = function (element, config, children) { var propName; // Original props are copied var props = _assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { key = '' + config.key; } // Remaining properties override existing props var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); }; /** * Verifies the object is a ReactElement. * See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function (object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; module.exports = ReactElement; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 16 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyFunction = __webpack_require__(18); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if (process.env.NODE_ENV !== 'production') { (function () { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; })(); } module.exports = warning; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 18 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var canDefineProperty = false; if (process.env.NODE_ENV !== 'production') { try { // $FlowFixMe https://github.com/facebook/flow/issues/285 Object.defineProperty({}, 'x', { get: function () {} }); canDefineProperty = true; } catch (x) { // IE will fail on defineProperty } } module.exports = canDefineProperty; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 20 */ /***/ function(module, exports) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; module.exports = REACT_ELEMENT_TYPE; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(13); var ReactCurrentOwner = __webpack_require__(16); var REACT_ELEMENT_TYPE = __webpack_require__(20); var getIteratorFn = __webpack_require__(22); var invariant = __webpack_require__(14); var KeyEscapeUtils = __webpack_require__(23); var warning = __webpack_require__(17); var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * This is inlined from ReactElement since this file is shared between * isomorphic and renderers. We could extract this to a * */ /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || // The following is inlined from ReactElement. This means we can optimize // some checks. React Fiber also inlines this logic for similar purposes. type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if (process.env.NODE_ENV !== 'production') { var mapsAsChildrenAddendum = ''; if (ReactCurrentOwner.current) { var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName(); if (mapsAsChildrenOwnerName) { mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.'; } } process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if (process.env.NODE_ENV !== 'production') { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 22 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; /***/ }, /* 23 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; module.exports = KeyEscapeUtils; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(13); var ReactNoopUpdateQueue = __webpack_require__(25); var canDefineProperty = __webpack_require__(19); var emptyObject = __webpack_require__(26); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } ReactComponent.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ ReactComponent.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0; this.updater.enqueueSetState(this, partialState); if (callback) { this.updater.enqueueCallback(this, callback, 'setState'); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this); if (callback) { this.updater.enqueueCallback(this, callback, 'forceUpdate'); } }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if (process.env.NODE_ENV !== 'production') { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { if (canDefineProperty) { Object.defineProperty(ReactComponent.prototype, methodName, { get: function () { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : void 0; return undefined; } }); } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } module.exports = ReactComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var warning = __webpack_require__(17); function warnNoop(publicInstance, callerName) { if (process.env.NODE_ENV !== 'production') { var constructor = publicInstance.constructor; process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function (publicInstance, callback) {}, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { warnNoop(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { warnNoop(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { warnNoop(publicInstance, 'setState'); } }; module.exports = ReactNoopUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyObject = {}; if (process.env.NODE_ENV !== 'production') { Object.freeze(emptyObject); } module.exports = emptyObject; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var ReactComponent = __webpack_require__(24); var ReactNoopUpdateQueue = __webpack_require__(25); var emptyObject = __webpack_require__(26); /** * Base class helpers for the updating state of a component. */ function ReactPureComponent(props, context, updater) { // Duplicated from ReactComponent. this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } function ComponentDummy() {} ComponentDummy.prototype = ReactComponent.prototype; ReactPureComponent.prototype = new ComponentDummy(); ReactPureComponent.prototype.constructor = ReactPureComponent; // Avoid an extra prototype jump for these methods. _assign(ReactPureComponent.prototype, ReactComponent.prototype); ReactPureComponent.prototype.isPureReactComponent = true; module.exports = ReactPureComponent; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(13), _assign = __webpack_require__(10); var ReactComponent = __webpack_require__(24); var ReactElement = __webpack_require__(15); var ReactPropTypeLocationNames = __webpack_require__(29); var ReactNoopUpdateQueue = __webpack_require__(25); var emptyObject = __webpack_require__(26); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); var MIXINS_KEY = 'mixins'; // Helper function to allow the creation of anonymous functions which do not // have .name set to the name of the variable being assigned to. function identity(fn) { return fn; } /** * Policies that describe methods in `ReactClassInterface`. */ var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or host components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: 'DEFINE_MANY', /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: 'DEFINE_MANY', /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: 'DEFINE_MANY', /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: 'DEFINE_MANY', /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: 'DEFINE_MANY', // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: 'DEFINE_MANY_MERGED', /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: 'DEFINE_MANY_MERGED', /** * @return {object} * @optional */ getChildContext: 'DEFINE_MANY_MERGED', /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: 'DEFINE_ONCE', // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: 'DEFINE_MANY', /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: 'DEFINE_MANY', /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: 'DEFINE_MANY', /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: 'DEFINE_ONCE', /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: 'DEFINE_MANY', /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: 'DEFINE_MANY', /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: 'DEFINE_MANY', // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: 'OVERRIDE_BASE' }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function (Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function (Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function (Constructor, childContextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, childContextTypes, 'childContext'); } Constructor.childContextTypes = _assign({}, Constructor.childContextTypes, childContextTypes); }, contextTypes: function (Constructor, contextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, contextTypes, 'context'); } Constructor.contextTypes = _assign({}, Constructor.contextTypes, contextTypes); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function (Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function (Constructor, propTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, propTypes, 'prop'); } Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function (Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function () {} }; function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an invariant so components // don't show up in prod but only in __DEV__ process.env.NODE_ENV !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : void 0; } } } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { !(specPolicy === 'OVERRIDE_BASE') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.', name) : _prodInvariant('73', name) : void 0; } // Disallow defining methods more than once unless explicitly allowed. if (isAlreadyDefined) { !(specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('74', name) : void 0; } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if (process.env.NODE_ENV !== 'production') { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; process.env.NODE_ENV !== 'production' ? warning(isMixinValid, '%s: You\'re attempting to include a mixin that is either null ' + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec) : void 0; } return; } !(typeof spec !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component class or function as a mixin. Instead, just use a regular object.') : _prodInvariant('75') : void 0; !!ReactElement.isValidElement(spec) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component as a mixin. Instead, just use a regular object.') : _prodInvariant('76') : void 0; var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. !(isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.', specPolicy, name) : _prodInvariant('77', specPolicy, name) : void 0; // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === 'DEFINE_MANY_MERGED') { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === 'DEFINE_MANY') { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (process.env.NODE_ENV !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; !!isReserved ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.', name) : _prodInvariant('78', name) : void 0; var isInherited = name in Constructor; !!isInherited ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('79', name) : void 0; Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { !(one && two && typeof one === 'object' && typeof two === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : _prodInvariant('80') : void 0; for (var key in two) { if (two.hasOwnProperty(key)) { !(one[key] === undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.', key) : _prodInvariant('81', key) : void 0; one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if (process.env.NODE_ENV !== 'production') { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function (newThis) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : void 0; } else if (!args.length) { process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : void 0; return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { var pairs = component.__reactAutoBindPairs; for (var i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i]; var method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function (newState, callback) { this.updater.enqueueReplaceState(this, newState); if (callback) { this.updater.enqueueCallback(this, callback, 'replaceState'); } }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function () { return this.updater.isMounted(this); } }; var ReactClassComponent = function () {}; _assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); /** * Module for creating composite components. * * @class ReactClass */ var ReactClass = { /** * Creates a composite component class given a class specification. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function (spec) { // To keep our warnings more understandable, we'll use a little hack here to // ensure that Constructor.name !== 'Constructor'. This makes sure we don't // unnecessarily identify a class without displayName as 'Constructor'. var Constructor = identity(function (props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : void 0; } // Wire up auto-binding if (this.__reactAutoBindPairs.length) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (initialState === undefined && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : _prodInvariant('82', Constructor.displayName || 'ReactCompositeComponent') : void 0; this.state = initialState; }); Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; Constructor.prototype.__reactAutoBindPairs = []; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if (process.env.NODE_ENV !== 'production') { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } !Constructor.prototype.render ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : _prodInvariant('83') : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : void 0; } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; }, injection: { injectMixin: function (mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypeLocationNames = {}; if (process.env.NODE_ENV !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactElement = __webpack_require__(15); /** * Create a factory that creates HTML tag elements. * * @private */ var createDOMFactory = ReactElement.createFactory; if (process.env.NODE_ENV !== 'production') { var ReactElementValidator = __webpack_require__(31); createDOMFactory = ReactElementValidator.createFactory; } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOMFactories = { a: createDOMFactory('a'), abbr: createDOMFactory('abbr'), address: createDOMFactory('address'), area: createDOMFactory('area'), article: createDOMFactory('article'), aside: createDOMFactory('aside'), audio: createDOMFactory('audio'), b: createDOMFactory('b'), base: createDOMFactory('base'), bdi: createDOMFactory('bdi'), bdo: createDOMFactory('bdo'), big: createDOMFactory('big'), blockquote: createDOMFactory('blockquote'), body: createDOMFactory('body'), br: createDOMFactory('br'), button: createDOMFactory('button'), canvas: createDOMFactory('canvas'), caption: createDOMFactory('caption'), cite: createDOMFactory('cite'), code: createDOMFactory('code'), col: createDOMFactory('col'), colgroup: createDOMFactory('colgroup'), data: createDOMFactory('data'), datalist: createDOMFactory('datalist'), dd: createDOMFactory('dd'), del: createDOMFactory('del'), details: createDOMFactory('details'), dfn: createDOMFactory('dfn'), dialog: createDOMFactory('dialog'), div: createDOMFactory('div'), dl: createDOMFactory('dl'), dt: createDOMFactory('dt'), em: createDOMFactory('em'), embed: createDOMFactory('embed'), fieldset: createDOMFactory('fieldset'), figcaption: createDOMFactory('figcaption'), figure: createDOMFactory('figure'), footer: createDOMFactory('footer'), form: createDOMFactory('form'), h1: createDOMFactory('h1'), h2: createDOMFactory('h2'), h3: createDOMFactory('h3'), h4: createDOMFactory('h4'), h5: createDOMFactory('h5'), h6: createDOMFactory('h6'), head: createDOMFactory('head'), header: createDOMFactory('header'), hgroup: createDOMFactory('hgroup'), hr: createDOMFactory('hr'), html: createDOMFactory('html'), i: createDOMFactory('i'), iframe: createDOMFactory('iframe'), img: createDOMFactory('img'), input: createDOMFactory('input'), ins: createDOMFactory('ins'), kbd: createDOMFactory('kbd'), keygen: createDOMFactory('keygen'), label: createDOMFactory('label'), legend: createDOMFactory('legend'), li: createDOMFactory('li'), link: createDOMFactory('link'), main: createDOMFactory('main'), map: createDOMFactory('map'), mark: createDOMFactory('mark'), menu: createDOMFactory('menu'), menuitem: createDOMFactory('menuitem'), meta: createDOMFactory('meta'), meter: createDOMFactory('meter'), nav: createDOMFactory('nav'), noscript: createDOMFactory('noscript'), object: createDOMFactory('object'), ol: createDOMFactory('ol'), optgroup: createDOMFactory('optgroup'), option: createDOMFactory('option'), output: createDOMFactory('output'), p: createDOMFactory('p'), param: createDOMFactory('param'), picture: createDOMFactory('picture'), pre: createDOMFactory('pre'), progress: createDOMFactory('progress'), q: createDOMFactory('q'), rp: createDOMFactory('rp'), rt: createDOMFactory('rt'), ruby: createDOMFactory('ruby'), s: createDOMFactory('s'), samp: createDOMFactory('samp'), script: createDOMFactory('script'), section: createDOMFactory('section'), select: createDOMFactory('select'), small: createDOMFactory('small'), source: createDOMFactory('source'), span: createDOMFactory('span'), strong: createDOMFactory('strong'), style: createDOMFactory('style'), sub: createDOMFactory('sub'), summary: createDOMFactory('summary'), sup: createDOMFactory('sup'), table: createDOMFactory('table'), tbody: createDOMFactory('tbody'), td: createDOMFactory('td'), textarea: createDOMFactory('textarea'), tfoot: createDOMFactory('tfoot'), th: createDOMFactory('th'), thead: createDOMFactory('thead'), time: createDOMFactory('time'), title: createDOMFactory('title'), tr: createDOMFactory('tr'), track: createDOMFactory('track'), u: createDOMFactory('u'), ul: createDOMFactory('ul'), 'var': createDOMFactory('var'), video: createDOMFactory('video'), wbr: createDOMFactory('wbr'), // SVG circle: createDOMFactory('circle'), clipPath: createDOMFactory('clipPath'), defs: createDOMFactory('defs'), ellipse: createDOMFactory('ellipse'), g: createDOMFactory('g'), image: createDOMFactory('image'), line: createDOMFactory('line'), linearGradient: createDOMFactory('linearGradient'), mask: createDOMFactory('mask'), path: createDOMFactory('path'), pattern: createDOMFactory('pattern'), polygon: createDOMFactory('polygon'), polyline: createDOMFactory('polyline'), radialGradient: createDOMFactory('radialGradient'), rect: createDOMFactory('rect'), stop: createDOMFactory('stop'), svg: createDOMFactory('svg'), text: createDOMFactory('text'), tspan: createDOMFactory('tspan') }; module.exports = ReactDOMFactories; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ 'use strict'; var ReactCurrentOwner = __webpack_require__(16); var ReactComponentTreeHook = __webpack_require__(32); var ReactElement = __webpack_require__(15); var checkReactTypeSpec = __webpack_require__(33); var canDefineProperty = __webpack_require__(19); var getIteratorFn = __webpack_require__(22); var warning = __webpack_require__(17); function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = ' Check the top-level render call using <' + parentName + '>.'; } } return info; } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var memoizer = ownerHasKeyUseWarning.uniqueKey || (ownerHasKeyUseWarning.uniqueKey = {}); var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (memoizer[currentComponentErrorInfo]) { return; } memoizer[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; } process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.%s', currentComponentErrorInfo, childOwner, ReactComponentTreeHook.getCurrentStackAddendum(element)) : void 0; } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); // Entry iterators provide implicit keys. if (iteratorFn) { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (ReactElement.isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { var componentClass = element.type; if (typeof componentClass !== 'function') { return; } var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkReactTypeSpec(componentClass.propTypes, element.props, 'prop', name, element, null); } if (typeof componentClass.getDefaultProps === 'function') { process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0; } } var ReactElementValidator = { createElement: function (type, props, children) { var validType = typeof type === 'string' || typeof type === 'function'; // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { if (typeof type !== 'function' && typeof type !== 'string') { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + 'it\'s defined in.'; } info += getDeclarationErrorAddendum(); process.env.NODE_ENV !== 'production' ? warning(false, 'React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', type == null ? type : typeof type, info) : void 0; } } var element = ReactElement.createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } validatePropTypes(element); return element; }, createFactory: function (type) { var validatedFactory = ReactElementValidator.createElement.bind(null, type); // Legacy hook TODO: Warn if this is accessed validatedFactory.type = type; if (process.env.NODE_ENV !== 'production') { if (canDefineProperty) { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { process.env.NODE_ENV !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : void 0; Object.defineProperty(this, 'type', { value: type }); return type; } }); } } return validatedFactory; }, cloneElement: function (element, props, children) { var newElement = ReactElement.cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } }; module.exports = ReactElementValidator; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(13); var ReactCurrentOwner = __webpack_require__(16); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); function isNative(fn) { // Based on isNative() from Lodash var funcToString = Function.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var reIsNative = RegExp('^' + funcToString // Take an example native function source for comparison .call(hasOwnProperty) // Strip regex characters so we can use it for regex .replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') // Remove hasOwnProperty from the template to make it generic .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'); try { var source = funcToString.call(fn); return reIsNative.test(source); } catch (err) { return false; } } var canUseCollections = // Array.from typeof Array.from === 'function' && // Map typeof Map === 'function' && isNative(Map) && // Map.prototype.keys Map.prototype != null && typeof Map.prototype.keys === 'function' && isNative(Map.prototype.keys) && // Set typeof Set === 'function' && isNative(Set) && // Set.prototype.keys Set.prototype != null && typeof Set.prototype.keys === 'function' && isNative(Set.prototype.keys); var setItem; var getItem; var removeItem; var getItemIDs; var addRoot; var removeRoot; var getRootIDs; if (canUseCollections) { var itemMap = new Map(); var rootIDSet = new Set(); setItem = function (id, item) { itemMap.set(id, item); }; getItem = function (id) { return itemMap.get(id); }; removeItem = function (id) { itemMap['delete'](id); }; getItemIDs = function () { return Array.from(itemMap.keys()); }; addRoot = function (id) { rootIDSet.add(id); }; removeRoot = function (id) { rootIDSet['delete'](id); }; getRootIDs = function () { return Array.from(rootIDSet.keys()); }; } else { var itemByKey = {}; var rootByKey = {}; // Use non-numeric keys to prevent V8 performance issues: // https://github.com/facebook/react/pull/7232 var getKeyFromID = function (id) { return '.' + id; }; var getIDFromKey = function (key) { return parseInt(key.substr(1), 10); }; setItem = function (id, item) { var key = getKeyFromID(id); itemByKey[key] = item; }; getItem = function (id) { var key = getKeyFromID(id); return itemByKey[key]; }; removeItem = function (id) { var key = getKeyFromID(id); delete itemByKey[key]; }; getItemIDs = function () { return Object.keys(itemByKey).map(getIDFromKey); }; addRoot = function (id) { var key = getKeyFromID(id); rootByKey[key] = true; }; removeRoot = function (id) { var key = getKeyFromID(id); delete rootByKey[key]; }; getRootIDs = function () { return Object.keys(rootByKey).map(getIDFromKey); }; } var unmountedIDs = []; function purgeDeep(id) { var item = getItem(id); if (item) { var childIDs = item.childIDs; removeItem(id); childIDs.forEach(purgeDeep); } } function describeComponentFrame(name, source, ownerName) { return '\n in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : ''); } function getDisplayName(element) { if (element == null) { return '#empty'; } else if (typeof element === 'string' || typeof element === 'number') { return '#text'; } else if (typeof element.type === 'string') { return element.type; } else { return element.type.displayName || element.type.name || 'Unknown'; } } function describeID(id) { var name = ReactComponentTreeHook.getDisplayName(id); var element = ReactComponentTreeHook.getElement(id); var ownerID = ReactComponentTreeHook.getOwnerID(id); var ownerName; if (ownerID) { ownerName = ReactComponentTreeHook.getDisplayName(ownerID); } process.env.NODE_ENV !== 'production' ? warning(element, 'ReactComponentTreeHook: Missing React element for debugID %s when ' + 'building stack', id) : void 0; return describeComponentFrame(name, element && element._source, ownerName); } var ReactComponentTreeHook = { onSetChildren: function (id, nextChildIDs) { var item = getItem(id); !item ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0; item.childIDs = nextChildIDs; for (var i = 0; i < nextChildIDs.length; i++) { var nextChildID = nextChildIDs[i]; var nextChild = getItem(nextChildID); !nextChild ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected hook events to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('140') : void 0; !(nextChild.childIDs != null || typeof nextChild.element !== 'object' || nextChild.element == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onSetChildren() to fire for a container child before its parent includes it in onSetChildren().') : _prodInvariant('141') : void 0; !nextChild.isMounted ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('71') : void 0; if (nextChild.parentID == null) { nextChild.parentID = id; // TODO: This shouldn't be necessary but mounting a new root during in // componentWillMount currently causes not-yet-mounted components to // be purged from our tree data so their parent id is missing. } !(nextChild.parentID === id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onBeforeMountComponent() parent and onSetChildren() to be consistent (%s has parents %s and %s).', nextChildID, nextChild.parentID, id) : _prodInvariant('142', nextChildID, nextChild.parentID, id) : void 0; } }, onBeforeMountComponent: function (id, element, parentID) { var item = { element: element, parentID: parentID, text: null, childIDs: [], isMounted: false, updateCount: 0 }; setItem(id, item); }, onBeforeUpdateComponent: function (id, element) { var item = getItem(id); if (!item || !item.isMounted) { // We may end up here as a result of setState() in componentWillUnmount(). // In this case, ignore the element. return; } item.element = element; }, onMountComponent: function (id) { var item = getItem(id); !item ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0; item.isMounted = true; var isRoot = item.parentID === 0; if (isRoot) { addRoot(id); } }, onUpdateComponent: function (id) { var item = getItem(id); if (!item || !item.isMounted) { // We may end up here as a result of setState() in componentWillUnmount(). // In this case, ignore the element. return; } item.updateCount++; }, onUnmountComponent: function (id) { var item = getItem(id); if (item) { // We need to check if it exists. // `item` might not exist if it is inside an error boundary, and a sibling // error boundary child threw while mounting. Then this instance never // got a chance to mount, but it still gets an unmounting event during // the error boundary cleanup. item.isMounted = false; var isRoot = item.parentID === 0; if (isRoot) { removeRoot(id); } } unmountedIDs.push(id); }, purgeUnmountedComponents: function () { if (ReactComponentTreeHook._preventPurging) { // Should only be used for testing. return; } for (var i = 0; i < unmountedIDs.length; i++) { var id = unmountedIDs[i]; purgeDeep(id); } unmountedIDs.length = 0; }, isMounted: function (id) { var item = getItem(id); return item ? item.isMounted : false; }, getCurrentStackAddendum: function (topElement) { var info = ''; if (topElement) { var name = getDisplayName(topElement); var owner = topElement._owner; info += describeComponentFrame(name, topElement._source, owner && owner.getName()); } var currentOwner = ReactCurrentOwner.current; var id = currentOwner && currentOwner._debugID; info += ReactComponentTreeHook.getStackAddendumByID(id); return info; }, getStackAddendumByID: function (id) { var info = ''; while (id) { info += describeID(id); id = ReactComponentTreeHook.getParentID(id); } return info; }, getChildIDs: function (id) { var item = getItem(id); return item ? item.childIDs : []; }, getDisplayName: function (id) { var element = ReactComponentTreeHook.getElement(id); if (!element) { return null; } return getDisplayName(element); }, getElement: function (id) { var item = getItem(id); return item ? item.element : null; }, getOwnerID: function (id) { var element = ReactComponentTreeHook.getElement(id); if (!element || !element._owner) { return null; } return element._owner._debugID; }, getParentID: function (id) { var item = getItem(id); return item ? item.parentID : null; }, getSource: function (id) { var item = getItem(id); var element = item ? item.element : null; var source = element != null ? element._source : null; return source; }, getText: function (id) { var element = ReactComponentTreeHook.getElement(id); if (typeof element === 'string') { return element; } else if (typeof element === 'number') { return '' + element; } else { return null; } }, getUpdateCount: function (id) { var item = getItem(id); return item ? item.updateCount : 0; }, getRootIDs: getRootIDs, getRegisteredIDs: getItemIDs }; module.exports = ReactComponentTreeHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(13); var ReactPropTypeLocationNames = __webpack_require__(29); var ReactPropTypesSecret = __webpack_require__(34); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = __webpack_require__(32); } var loggedTypeFailures = {}; /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?object} element The React element that is being type-checked * @param {?number} debugID The React component instance that is being type-checked * @private */ function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof typeSpecs[typeSpecName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0; error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var componentStackInfo = ''; if (process.env.NODE_ENV !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = __webpack_require__(32); } if (debugID !== null) { componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID); } else if (element !== null) { componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element); } } process.env.NODE_ENV !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0; } } } } module.exports = checkReactTypeSpec; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 34 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactElement = __webpack_require__(15); var ReactPropTypeLocationNames = __webpack_require__(29); var ReactPropTypesSecret = __webpack_require__(34); var emptyFunction = __webpack_require__(18); var getIteratorFn = __webpack_require__(22); var warning = __webpack_require__(17); /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (process.env.NODE_ENV !== 'production') { var manualPropTypeCallCache = {}; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (process.env.NODE_ENV !== 'production') { if (secret !== ReactPropTypesSecret && typeof console !== 'undefined') { var cacheKey = componentName + ':' + propName; if (!manualPropTypeCallCache[cacheKey]) { process.env.NODE_ENV !== 'production' ? warning(false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will not work in production with the next major version. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName) : void 0; manualPropTypeCallCache[cacheKey] = true; } } } if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + locationName + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + locationName + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var locationName = ReactPropTypeLocationNames[location]; // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturns(null)); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!ReactElement.isValidElement(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var locationName = ReactPropTypeLocationNames[location]; var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var locationName = ReactPropTypeLocationNames[location]; var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || ReactElement.isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } module.exports = ReactPropTypes; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 36 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; module.exports = '15.4.2'; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(13); var ReactElement = __webpack_require__(15); var invariant = __webpack_require__(14); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.only * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { !ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React.Children.only expected to receive a single React element child.') : _prodInvariant('143') : void 0; return children; } module.exports = onlyChild; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(39); /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ 'use strict'; var ReactDOMComponentTree = __webpack_require__(40); var ReactDefaultInjection = __webpack_require__(44); var ReactMount = __webpack_require__(172); var ReactReconciler = __webpack_require__(65); var ReactUpdates = __webpack_require__(62); var ReactVersion = __webpack_require__(177); var findDOMNode = __webpack_require__(178); var getHostComponentFromComposite = __webpack_require__(179); var renderSubtreeIntoContainer = __webpack_require__(180); var warning = __webpack_require__(17); ReactDefaultInjection.inject(); var ReactDOM = { findDOMNode: findDOMNode, render: ReactMount.render, unmountComponentAtNode: ReactMount.unmountComponentAtNode, version: ReactVersion, /* eslint-disable camelcase */ unstable_batchedUpdates: ReactUpdates.batchedUpdates, unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ ComponentTree: { getClosestInstanceFromNode: ReactDOMComponentTree.getClosestInstanceFromNode, getNodeFromInstance: function (inst) { // inst is an internal instance (but could be a composite) if (inst._renderedComponent) { inst = getHostComponentFromComposite(inst); } if (inst) { return ReactDOMComponentTree.getNodeFromInstance(inst); } else { return null; } } }, Mount: ReactMount, Reconciler: ReactReconciler }); } if (process.env.NODE_ENV !== 'production') { var ExecutionEnvironment = __webpack_require__(54); if (ExecutionEnvironment.canUseDOM && window.top === window.self) { // First check if devtools is not installed if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { // If we're in Chrome or Firefox, provide a download link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { // Firefox does not have the issue with devtools loaded over file:// var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 && navigator.userAgent.indexOf('Firefox') === -1; console.debug('Download the React DevTools ' + (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') + 'for a better development experience: ' + 'https://fb.me/react-devtools'); } } var testFunc = function testFn() {}; process.env.NODE_ENV !== 'production' ? warning((testFunc.name || testFunc.toString()).indexOf('testFn') !== -1, 'It looks like you\'re using a minified copy of the development build ' + 'of React. When deploying React apps to production, make sure to use ' + 'the production build which skips development warnings and is faster. ' + 'See https://fb.me/react-minification for more details.') : void 0; // If we're in IE8, check to see if we are in compatibility mode and provide // information on preventing compatibility mode var ieCompatibilityMode = document.documentMode && document.documentMode < 8; process.env.NODE_ENV !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : void 0; var expectedFeatures = [ // shims Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.trim]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { process.env.NODE_ENV !== 'production' ? warning(false, 'One or more ES5 shims expected by React are not available: ' + 'https://fb.me/react-warning-polyfills') : void 0; break; } } } } if (process.env.NODE_ENV !== 'production') { var ReactInstrumentation = __webpack_require__(68); var ReactDOMUnknownPropertyHook = __webpack_require__(181); var ReactDOMNullInputValuePropHook = __webpack_require__(182); var ReactDOMInvalidARIAHook = __webpack_require__(183); ReactInstrumentation.debugTool.addHook(ReactDOMUnknownPropertyHook); ReactInstrumentation.debugTool.addHook(ReactDOMNullInputValuePropHook); ReactInstrumentation.debugTool.addHook(ReactDOMInvalidARIAHook); } module.exports = ReactDOM; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var DOMProperty = __webpack_require__(42); var ReactDOMComponentFlags = __webpack_require__(43); var invariant = __webpack_require__(14); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var Flags = ReactDOMComponentFlags; var internalInstanceKey = '__reactInternalInstance$' + Math.random().toString(36).slice(2); /** * Check if a given node should be cached. */ function shouldPrecacheNode(node, nodeID) { return node.nodeType === 1 && node.getAttribute(ATTR_NAME) === String(nodeID) || node.nodeType === 8 && node.nodeValue === ' react-text: ' + nodeID + ' ' || node.nodeType === 8 && node.nodeValue === ' react-empty: ' + nodeID + ' '; } /** * Drill down (through composites and empty components) until we get a host or * host text component. * * This is pretty polymorphic but unavoidable with the current structure we have * for `_renderedChildren`. */ function getRenderedHostOrTextFromComponent(component) { var rendered; while (rendered = component._renderedComponent) { component = rendered; } return component; } /** * Populate `_hostNode` on the rendered host/text component with the given * DOM node. The passed `inst` can be a composite. */ function precacheNode(inst, node) { var hostInst = getRenderedHostOrTextFromComponent(inst); hostInst._hostNode = node; node[internalInstanceKey] = hostInst; } function uncacheNode(inst) { var node = inst._hostNode; if (node) { delete node[internalInstanceKey]; inst._hostNode = null; } } /** * Populate `_hostNode` on each child of `inst`, assuming that the children * match up with the DOM (element) children of `node`. * * We cache entire levels at once to avoid an n^2 problem where we access the * children of a node sequentially and have to walk from the start to our target * node every time. * * Since we update `_renderedChildren` and the actual DOM at (slightly) * different times, we could race here and see a newer `_renderedChildren` than * the DOM nodes we see. To avoid this, ReactMultiChild calls * `prepareToManageChildren` before we change `_renderedChildren`, at which * time the container's child nodes are always cached (until it unmounts). */ function precacheChildNodes(inst, node) { if (inst._flags & Flags.hasCachedChildNodes) { return; } var children = inst._renderedChildren; var childNode = node.firstChild; outer: for (var name in children) { if (!children.hasOwnProperty(name)) { continue; } var childInst = children[name]; var childID = getRenderedHostOrTextFromComponent(childInst)._domID; if (childID === 0) { // We're currently unmounting this child in ReactMultiChild; skip it. continue; } // We assume the child nodes are in the same order as the child instances. for (; childNode !== null; childNode = childNode.nextSibling) { if (shouldPrecacheNode(childNode, childID)) { precacheNode(childInst, childNode); continue outer; } } // We reached the end of the DOM children without finding an ID match. true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unable to find element with ID %s.', childID) : _prodInvariant('32', childID) : void 0; } inst._flags |= Flags.hasCachedChildNodes; } /** * Given a DOM node, return the closest ReactDOMComponent or * ReactDOMTextComponent instance ancestor. */ function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) { return node[internalInstanceKey]; } // Walk up the tree until we find an ancestor whose instance we have cached. var parents = []; while (!node[internalInstanceKey]) { parents.push(node); if (node.parentNode) { node = node.parentNode; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; } } var closest; var inst; for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) { closest = inst; if (parents.length) { precacheChildNodes(inst, node); } } return closest; } /** * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent * instance, or null if the node was not rendered by this React. */ function getInstanceFromNode(node) { var inst = getClosestInstanceFromNode(node); if (inst != null && inst._hostNode === node) { return inst; } else { return null; } } /** * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding * DOM node. */ function getNodeFromInstance(inst) { // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. !(inst._hostNode !== undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; if (inst._hostNode) { return inst._hostNode; } // Walk up the tree until we find an ancestor whose DOM node we have cached. var parents = []; while (!inst._hostNode) { parents.push(inst); !inst._hostParent ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React DOM tree root should always have a node reference.') : _prodInvariant('34') : void 0; inst = inst._hostParent; } // Now parents contains each ancestor that does *not* have a cached native // node, and `inst` is the deepest ancestor that does. for (; parents.length; inst = parents.pop()) { precacheChildNodes(inst, inst._hostNode); } return inst._hostNode; } var ReactDOMComponentTree = { getClosestInstanceFromNode: getClosestInstanceFromNode, getInstanceFromNode: getInstanceFromNode, getNodeFromInstance: getNodeFromInstance, precacheChildNodes: precacheChildNodes, precacheNode: precacheNode, uncacheNode: uncacheNode }; module.exports = ReactDOMComponentTree; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 41 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * WARNING: DO NOT manually require this module. * This is a replacement for `invariant(...)` used by the error code system * and will _only_ be required by the corresponding babel pass. * It always throws. */ function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; } module.exports = reactProdInvariant; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_PROPERTY: 0x1, HAS_BOOLEAN_VALUE: 0x4, HAS_NUMERIC_VALUE: 0x8, HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8, HAS_OVERLOADED_BOOLEAN_VALUE: 0x20, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMAttributeNamespaces: object mapping React attribute name to the DOM * attribute namespace URL. (Attribute names not specified use no namespace.) * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function (domPropertyConfig) { var Injection = DOMPropertyInjection; var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute); } for (var propName in Properties) { !!DOMProperty.properties.hasOwnProperty(propName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property \'%s\' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.', propName) : _prodInvariant('48', propName) : void 0; var lowerCased = propName.toLowerCase(); var propConfig = Properties[propName]; var propertyInfo = { attributeName: lowerCased, attributeNamespace: null, propertyName: propName, mutationMethod: null, mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) }; !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s', propName) : _prodInvariant('50', propName) : void 0; if (process.env.NODE_ENV !== 'production') { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; if (process.env.NODE_ENV !== 'production') { DOMProperty.getPossibleStandardName[attributeName] = propName; } } if (DOMAttributeNamespaces.hasOwnProperty(propName)) { propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; } if (DOMPropertyNames.hasOwnProperty(propName)) { propertyInfo.propertyName = DOMPropertyNames[propName]; } if (DOMMutationMethods.hasOwnProperty(propName)) { propertyInfo.mutationMethod = DOMMutationMethods[propName]; } DOMProperty.properties[propName] = propertyInfo; } } }; /* eslint-disable max-len */ var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; /* eslint-enable max-len */ /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', ROOT_ATTRIBUTE_NAME: 'data-reactroot', ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR, ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040', /** * Map from property "standard name" to an object with info about how to set * the property in the DOM. Each object contains: * * attributeName: * Used when rendering markup or with `*Attribute()`. * attributeNamespace * propertyName: * Used on DOM node instances. (This includes properties that mutate due to * external factors.) * mutationMethod: * If non-null, used instead of the property or `setAttribute()` after * initial render. * mustUseProperty: * Whether the property must be accessed and mutated as an object property. * hasBooleanValue: * Whether the property should be removed when set to a falsey value. * hasNumericValue: * Whether the property must be numeric or parse as a numeric and should be * removed when set to a falsey value. * hasPositiveNumericValue: * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * hasOverloadedBooleanValue: * Whether the property can be used as a flag as well as with a value. * Removed when strictly equal to false; present without a value when * strictly equal to true; present with a value otherwise. */ properties: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. Available only in __DEV__. * * autofocus is predefined, because adding it to the property whitelist * causes unintended side effects. * * @type {Object} */ getPossibleStandardName: process.env.NODE_ENV !== 'production' ? { autofocus: 'autoFocus' } : null, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function (attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 43 */ /***/ function(module, exports) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMComponentFlags = { hasCachedChildNodes: 1 << 0 }; module.exports = ReactDOMComponentFlags; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ARIADOMPropertyConfig = __webpack_require__(45); var BeforeInputEventPlugin = __webpack_require__(46); var ChangeEventPlugin = __webpack_require__(61); var DefaultEventPluginOrder = __webpack_require__(78); var EnterLeaveEventPlugin = __webpack_require__(79); var HTMLDOMPropertyConfig = __webpack_require__(84); var ReactComponentBrowserEnvironment = __webpack_require__(85); var ReactDOMComponent = __webpack_require__(98); var ReactDOMComponentTree = __webpack_require__(40); var ReactDOMEmptyComponent = __webpack_require__(143); var ReactDOMTreeTraversal = __webpack_require__(144); var ReactDOMTextComponent = __webpack_require__(145); var ReactDefaultBatchingStrategy = __webpack_require__(146); var ReactEventListener = __webpack_require__(147); var ReactInjection = __webpack_require__(150); var ReactReconcileTransaction = __webpack_require__(151); var SVGDOMPropertyConfig = __webpack_require__(159); var SelectEventPlugin = __webpack_require__(160); var SimpleEventPlugin = __webpack_require__(161); var alreadyInjected = false; function inject() { if (alreadyInjected) { // TODO: This is currently true because these injections are shared between // the client and the server package. They should be built independently // and not share any injection state. Then this problem will be solved. return; } alreadyInjected = true; ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginUtils.injectComponentTree(ReactDOMComponentTree); ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.HostComponent.injectGenericComponentClass(ReactDOMComponent); ReactInjection.HostComponent.injectTextComponentClass(ReactDOMTextComponent); ReactInjection.DOMProperty.injectDOMPropertyConfig(ARIADOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponentFactory(function (instantiate) { return new ReactDOMEmptyComponent(instantiate); }); ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction); ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); } module.exports = { inject: inject }; /***/ }, /* 45 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ARIADOMPropertyConfig = { Properties: { // Global States and Properties 'aria-current': 0, // state 'aria-details': 0, 'aria-disabled': 0, // state 'aria-hidden': 0, // state 'aria-invalid': 0, // state 'aria-keyshortcuts': 0, 'aria-label': 0, 'aria-roledescription': 0, // Widget Attributes 'aria-autocomplete': 0, 'aria-checked': 0, 'aria-expanded': 0, 'aria-haspopup': 0, 'aria-level': 0, 'aria-modal': 0, 'aria-multiline': 0, 'aria-multiselectable': 0, 'aria-orientation': 0, 'aria-placeholder': 0, 'aria-pressed': 0, 'aria-readonly': 0, 'aria-required': 0, 'aria-selected': 0, 'aria-sort': 0, 'aria-valuemax': 0, 'aria-valuemin': 0, 'aria-valuenow': 0, 'aria-valuetext': 0, // Live Region Attributes 'aria-atomic': 0, 'aria-busy': 0, 'aria-live': 0, 'aria-relevant': 0, // Drag-and-Drop Attributes 'aria-dropeffect': 0, 'aria-grabbed': 0, // Relationship Attributes 'aria-activedescendant': 0, 'aria-colcount': 0, 'aria-colindex': 0, 'aria-colspan': 0, 'aria-controls': 0, 'aria-describedby': 0, 'aria-errormessage': 0, 'aria-flowto': 0, 'aria-labelledby': 0, 'aria-owns': 0, 'aria-posinset': 0, 'aria-rowcount': 0, 'aria-rowindex': 0, 'aria-rowspan': 0, 'aria-setsize': 0 }, DOMAttributeNames: {}, DOMPropertyNames: {} }; module.exports = ARIADOMPropertyConfig; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPropagators = __webpack_require__(47); var ExecutionEnvironment = __webpack_require__(54); var FallbackCompositionState = __webpack_require__(55); var SyntheticCompositionEvent = __webpack_require__(58); var SyntheticInputEvent = __webpack_require__(60); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window; var documentMode = null; if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto(); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: 'onBeforeInput', captured: 'onBeforeInputCapture' }, dependencies: ['topCompositionEnd', 'topKeyPress', 'topTextInput', 'topPaste'] }, compositionEnd: { phasedRegistrationNames: { bubbled: 'onCompositionEnd', captured: 'onCompositionEndCapture' }, dependencies: ['topBlur', 'topCompositionEnd', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] }, compositionStart: { phasedRegistrationNames: { bubbled: 'onCompositionStart', captured: 'onCompositionStartCapture' }, dependencies: ['topBlur', 'topCompositionStart', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] }, compositionUpdate: { phasedRegistrationNames: { bubbled: 'onCompositionUpdate', captured: 'onCompositionUpdateCapture' }, dependencies: ['topBlur', 'topCompositionUpdate', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] } }; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey); } /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case 'topCompositionStart': return eventTypes.compositionStart; case 'topCompositionEnd': return eventTypes.compositionEnd; case 'topCompositionUpdate': return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionStart(topLevelType, nativeEvent) { return topLevelType === 'topKeyDown' && nativeEvent.keyCode === START_KEYCODE; } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case 'topKeyUp': // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case 'topKeyDown': // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case 'topKeyPress': case 'topMouseDown': case 'topBlur': // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } // Track the current IME composition fallback object, if any. var currentComposition = null; /** * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackCompositionStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (!eventType) { return null; } if (useFallbackCompositionData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = FallbackCompositionState.getPooled(nativeEventTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case 'topCompositionEnd': return getDataFromCustomEvent(nativeEvent); case 'topKeyPress': /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case 'topTextInput': // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. // If composition event is available, we extract a string only at // compositionevent, otherwise extract it at fallback events. if (currentComposition) { if (topLevelType === 'topCompositionEnd' || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) { var chars = currentComposition.getData(); FallbackCompositionState.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case 'topPaste': // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case 'topKeyPress': /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { return String.fromCharCode(nativeEvent.which); } return null; case 'topCompositionEnd': return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget); event.data = chars; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)]; } }; module.exports = BeforeInputEventPlugin; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPluginHub = __webpack_require__(48); var EventPluginUtils = __webpack_require__(50); var accumulateInto = __webpack_require__(52); var forEachAccumulated = __webpack_require__(53); var warning = __webpack_require__(17); var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(inst, phase, event) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(inst, 'Dispatching inst must not be null') : void 0; } var listener = listenerAtPhase(inst, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; var parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null; EventPluginUtils.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(inst, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, from, to) { EventPluginUtils.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var EventPluginRegistry = __webpack_require__(49); var EventPluginUtils = __webpack_require__(50); var ReactErrorUtils = __webpack_require__(51); var accumulateInto = __webpack_require__(52); var forEachAccumulated = __webpack_require__(53); var invariant = __webpack_require__(14); /** * Internal store for event listeners */ var listenerBank = {}; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @param {boolean} simulated If the event is simulated (changes exn behavior) * @private */ var executeDispatchesAndRelease = function (event, simulated) { if (event) { EventPluginUtils.executeDispatchesInOrder(event, simulated); if (!event.isPersistent()) { event.constructor.release(event); } } }; var executeDispatchesAndReleaseSimulated = function (e) { return executeDispatchesAndRelease(e, true); }; var executeDispatchesAndReleaseTopLevel = function (e) { return executeDispatchesAndRelease(e, false); }; var getDictionaryKey = function (inst) { // Prevents V8 performance issue: // https://github.com/facebook/react/pull/7232 return '.' + inst._rootNodeID; }; function isInteractive(tag) { return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea'; } function shouldPreventMouseEvent(name, type, props) { switch (name) { case 'onClick': case 'onClickCapture': case 'onDoubleClick': case 'onDoubleClickCapture': case 'onMouseDown': case 'onMouseDownCapture': case 'onMouseMove': case 'onMouseMoveCapture': case 'onMouseUp': case 'onMouseUpCapture': return !!(props.disabled && isInteractive(type)); default: return false; } } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, /** * Stores `listener` at `listenerBank[registrationName][key]`. Is idempotent. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {function} listener The callback to store. */ putListener: function (inst, registrationName, listener) { !(typeof listener === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : _prodInvariant('94', registrationName, typeof listener) : void 0; var key = getDictionaryKey(inst); var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[key] = listener; var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.didPutListener) { PluginModule.didPutListener(inst, registrationName, listener); } }, /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function (inst, registrationName) { // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not // live here; needs to be moved to a better place soon var bankForRegistrationName = listenerBank[registrationName]; if (shouldPreventMouseEvent(registrationName, inst._currentElement.type, inst._currentElement.props)) { return null; } var key = getDictionaryKey(inst); return bankForRegistrationName && bankForRegistrationName[key]; }, /** * Deletes a listener from the registration bank. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function (inst, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? if (bankForRegistrationName) { var key = getDictionaryKey(inst); delete bankForRegistrationName[key]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {object} inst The instance, which is the source of events. */ deleteAllListeners: function (inst) { var key = getDictionaryKey(inst); for (var registrationName in listenerBank) { if (!listenerBank.hasOwnProperty(registrationName)) { continue; } if (!listenerBank[registrationName][key]) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } delete listenerBank[registrationName][key]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function (events) { if (events) { eventQueue = accumulateInto(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function (simulated) { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; if (simulated) { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); } else { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); } !!eventQueue ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : _prodInvariant('95') : void 0; // This would be a good time to rethrow if any of the event handlers threw. ReactErrorUtils.rethrowCaughtError(); }, /** * These are needed for tests only. Do not use! */ __purge: function () { listenerBank = {}; }, __getListenerBank: function () { return listenerBank; } }; module.exports = EventPluginHub; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); /** * Injectable ordering of event plugins. */ var eventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!eventPluginOrder) { // Wait until an `eventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var pluginModule = namesToPlugins[pluginName]; var pluginIndex = eventPluginOrder.indexOf(pluginName); !(pluginIndex > -1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : _prodInvariant('96', pluginName) : void 0; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !pluginModule.extractEvents ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : _prodInvariant('97', pluginName) : void 0; EventPluginRegistry.plugins[pluginIndex] = pluginModule; var publishedEvents = pluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : _prodInvariant('98', eventName, pluginName) : void 0; } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : _prodInvariant('99', eventName) : void 0; EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName(phasedRegistrationName, pluginModule, eventName); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, pluginModule, eventName) { !!EventPluginRegistry.registrationNameModules[registrationName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : _prodInvariant('100', registrationName) : void 0; EventPluginRegistry.registrationNameModules[registrationName] = pluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; if (process.env.NODE_ENV !== 'production') { var lowerCasedName = registrationName.toLowerCase(); EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName; if (registrationName === 'onDoubleClick') { EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName; } } } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in __DEV__. * @type {Object} */ possibleRegistrationNames: process.env.NODE_ENV !== 'production' ? {} : null, // Trust the developer to only use possibleRegistrationNames in __DEV__ /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function (injectedEventPluginOrder) { !!eventPluginOrder ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : _prodInvariant('101') : void 0; // Clone the ordering so it cannot be dynamically mutated. eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function (injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var pluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) { !!namesToPlugins[pluginName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : _prodInvariant('102', pluginName) : void 0; namesToPlugins[pluginName] = pluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function (event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; } if (dispatchConfig.phasedRegistrationNames !== undefined) { // pulling phasedRegistrationNames out of dispatchConfig helps Flow see // that it is not undefined. var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; for (var phase in phasedRegistrationNames) { if (!phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var pluginModule = EventPluginRegistry.registrationNameModules[phasedRegistrationNames[phase]]; if (pluginModule) { return pluginModule; } } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function () { eventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } if (process.env.NODE_ENV !== 'production') { var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames; for (var lowerCasedName in possibleRegistrationNames) { if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) { delete possibleRegistrationNames[lowerCasedName]; } } } } }; module.exports = EventPluginRegistry; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var ReactErrorUtils = __webpack_require__(51); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); /** * Injected dependencies: */ /** * - `ComponentTree`: [required] Module that can convert between React instances * and actual node references. */ var ComponentTree; var TreeTraversal; var injection = { injectComponentTree: function (Injected) { ComponentTree = Injected; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0; } }, injectTreeTraversal: function (Injected) { TreeTraversal = Injected; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, 'EventPluginUtils.injection.injectTreeTraversal(...): Injected ' + 'module is missing isAncestor or getLowestCommonAncestor.') : void 0; } } }; function isEndish(topLevelType) { return topLevelType === 'topMouseUp' || topLevelType === 'topTouchEnd' || topLevelType === 'topTouchCancel'; } function isMoveish(topLevelType) { return topLevelType === 'topMouseMove' || topLevelType === 'topTouchMove'; } function isStartish(topLevelType) { return topLevelType === 'topMouseDown' || topLevelType === 'topTouchStart'; } var validateEventDispatches; if (process.env.NODE_ENV !== 'production') { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; process.env.NODE_ENV !== 'production' ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : void 0; }; } /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {boolean} simulated If the event is simulated (changes exn behavior) * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ function executeDispatch(event, simulated, listener, inst) { var type = event.type || 'unknown-event'; event.currentTarget = EventPluginUtils.getNodeFromInstance(inst); if (simulated) { ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event); } else { ReactErrorUtils.invokeGuardedCallback(type, listener, event); } event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, simulated, dispatchListeners, dispatchInstances); } event._dispatchListeners = null; event._dispatchInstances = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchInstances)) { return dispatchInstances; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; !!Array.isArray(dispatchListener) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : _prodInvariant('103') : void 0; event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; var res = dispatchListener ? dispatchListener(event) : null; event.currentTarget = null; event._dispatchListeners = null; event._dispatchInstances = null; return res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, getInstanceFromNode: function (node) { return ComponentTree.getInstanceFromNode(node); }, getNodeFromInstance: function (node) { return ComponentTree.getNodeFromInstance(node); }, isAncestor: function (a, b) { return TreeTraversal.isAncestor(a, b); }, getLowestCommonAncestor: function (a, b) { return TreeTraversal.getLowestCommonAncestor(a, b); }, getParentInstance: function (inst) { return TreeTraversal.getParentInstance(inst); }, traverseTwoPhase: function (target, fn, arg) { return TreeTraversal.traverseTwoPhase(target, fn, arg); }, traverseEnterLeave: function (from, to, fn, argFrom, argTo) { return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo); }, injection: injection }; module.exports = EventPluginUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var caughtError = null; /** * Call a function while guarding against errors that happens within it. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} a First argument * @param {*} b Second argument */ function invokeGuardedCallback(name, func, a) { try { func(a); } catch (x) { if (caughtError === null) { caughtError = x; } } } var ReactErrorUtils = { invokeGuardedCallback: invokeGuardedCallback, /** * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event * handler are sure to be rethrown by rethrowCaughtError. */ invokeGuardedCallbackWithCatch: invokeGuardedCallback, /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ rethrowCaughtError: function () { if (caughtError) { var error = caughtError; caughtError = null; throw error; } } }; if (process.env.NODE_ENV !== 'production') { /** * To help development we can get better devtools integration by simulating a * real browser event. */ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); ReactErrorUtils.invokeGuardedCallback = function (name, func, a) { var boundFunc = func.bind(null, a); var evtType = 'react-' + name; fakeNode.addEventListener(evtType, boundFunc, false); var evt = document.createEvent('Event'); // $FlowFixMe https://github.com/facebook/flow/issues/2336 evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); fakeNode.removeEventListener(evtType, boundFunc, false); }; } } module.exports = ReactErrorUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); /** * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { !(next != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : _prodInvariant('30') : void 0; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). if (Array.isArray(current)) { if (Array.isArray(next)) { current.push.apply(current, next); return current; } current.push(next); return current; } if (Array.isArray(next)) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 53 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ function forEachAccumulated(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } } module.exports = forEachAccumulated; /***/ }, /* 54 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var PooledClass = __webpack_require__(56); var getTextContentAccessor = __webpack_require__(57); /** * This helper class stores information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this._root = root; this._startText = this.getText(); this._fallbackText = null; } _assign(FallbackCompositionState.prototype, { destructor: function () { this._root = null; this._startText = null; this._fallbackText = null; }, /** * Get current text of input. * * @return {string} */ getText: function () { if ('value' in this._root) { return this._root.value; } return this._root[getTextContentAccessor()]; }, /** * Determine the differing substring between the initially stored * text content and the current content. * * @return {string} */ getData: function () { if (this._fallbackText) { return this._fallbackText; } var start; var startValue = this._startText; var startLength = startValue.length; var end; var endValue = this.getText(); var endLength = endValue.length; for (start = 0; start < startLength; start++) { if (startValue[start] !== endValue[start]) { break; } } var minEnd = startLength - start; for (end = 1; end <= minEnd; end++) { if (startValue[startLength - end] !== endValue[endLength - end]) { break; } } var sliceTail = end > 1 ? 1 - end : undefined; this._fallbackText = endValue.slice(start, sliceTail); return this._fallbackText; } }); PooledClass.addPoolingTo(FallbackCompositionState); module.exports = FallbackCompositionState; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances. * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { // Casting as any so that flow ignores the actual implementation and trusts // it to match the type we declared var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler }; module.exports = PooledClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(54); var contentKey = null; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(59); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); module.exports = SyntheticCompositionEvent; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var PooledClass = __webpack_require__(56); var emptyFunction = __webpack_require__(18); var warning = __webpack_require__(17); var didWarnForAddedNewProperty = false; var isProxySupported = typeof Proxy === 'function'; var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances']; /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {*} targetInst Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { if (process.env.NODE_ENV !== 'production') { // these have a getter/setter for warnings delete this.nativeEvent; delete this.preventDefault; delete this.stopPropagation; } this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } if (process.env.NODE_ENV !== 'production') { delete this[propName]; // this has a getter/setter for warnings } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; return this; } _assign(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (!event) { return; } if (event.preventDefault) { event.preventDefault(); } else if (typeof event.returnValue !== 'unknown') { // eslint-disable-line valid-typeof event.returnValue = false; } this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else if (typeof event.cancelBubble !== 'unknown') { // eslint-disable-line valid-typeof // The ChangeEventPlugin registers a "propertychange" event for // IE. This event does not support bubbling or cancelling, and // any references to cancelBubble throw "Member not found". A // typeof check of "unknown" circumvents this issue (and is also // IE specific). event.cancelBubble = true; } this.isPropagationStopped = emptyFunction.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function () { var Interface = this.constructor.Interface; for (var propName in Interface) { if (process.env.NODE_ENV !== 'production') { Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); } else { this[propName] = null; } } for (var i = 0; i < shouldBeReleasedProperties.length; i++) { this[shouldBeReleasedProperties[i]] = null; } if (process.env.NODE_ENV !== 'production') { Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction)); Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction)); } } }); SyntheticEvent.Interface = EventInterface; if (process.env.NODE_ENV !== 'production') { if (isProxySupported) { /*eslint-disable no-func-assign */ SyntheticEvent = new Proxy(SyntheticEvent, { construct: function (target, args) { return this.apply(target, Object.create(target.prototype), args); }, apply: function (constructor, that, args) { return new Proxy(constructor.apply(that, args), { set: function (target, prop, value) { if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) { process.env.NODE_ENV !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re adding a new property in the synthetic event object. ' + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0; didWarnForAddedNewProperty = true; } target[prop] = value; return true; } }); } }); /*eslint-enable no-func-assign */ } } /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function (Class, Interface) { var Super = this; var E = function () {}; E.prototype = Super.prototype; var prototype = new E(); _assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = _assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler); module.exports = SyntheticEvent; /** * Helper to nullify syntheticEvent instance properties when destructing * * @param {object} SyntheticEvent * @param {String} propName * @return {object} defineProperty object */ function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; process.env.NODE_ENV !== 'production' ? warning(warningCondition, 'This synthetic event is reused for performance reasons. If you\'re seeing this, ' + 'you\'re %s `%s` on a released/nullified synthetic event. %s. ' + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0; } } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(59); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ var InputEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface); module.exports = SyntheticInputEvent; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPluginHub = __webpack_require__(48); var EventPropagators = __webpack_require__(47); var ExecutionEnvironment = __webpack_require__(54); var ReactDOMComponentTree = __webpack_require__(40); var ReactUpdates = __webpack_require__(62); var SyntheticEvent = __webpack_require__(59); var getEventTarget = __webpack_require__(75); var isEventSupported = __webpack_require__(76); var isTextInputElement = __webpack_require__(77); var eventTypes = { change: { phasedRegistrationNames: { bubbled: 'onChange', captured: 'onChangeCapture' }, dependencies: ['topBlur', 'topChange', 'topClick', 'topFocus', 'topInput', 'topKeyDown', 'topKeyUp', 'topSelectionChange'] } }; /** * For IE shims */ var activeElement = null; var activeElementInst = null; var activeElementValue = null; var activeElementValueProp = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && (!document.documentMode || document.documentMode > 8); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled(eventTypes.change, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); EventPropagators.accumulateTwoPhaseDispatches(event); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(false); } function startWatchingForChangeEventIE8(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementInst = null; } function getTargetInstForChangeEvent(topLevelType, targetInst) { if (topLevelType === 'topChange') { return targetInst; } } function handleEventsForChangeEventIE8(topLevelType, target, targetInst) { if (topLevelType === 'topFocus') { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(target, targetInst); } else if (topLevelType === 'topBlur') { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events. // IE10+ fire input events to often, such when a placeholder // changes or when an input with a placeholder is focused. isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 11); } /** * (For IE <=11) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function () { return activeElementValueProp.get.call(this); }, set: function (val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For IE <=11) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value'); // Not guarded in a canDefineProperty check: IE8 supports defineProperty only // on DOM elements Object.defineProperty(activeElement, 'value', newValueProp); if (activeElement.attachEvent) { activeElement.attachEvent('onpropertychange', handlePropertyChange); } else { activeElement.addEventListener('propertychange', handlePropertyChange, false); } } /** * (For IE <=11) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; if (activeElement.detachEvent) { activeElement.detachEvent('onpropertychange', handlePropertyChange); } else { activeElement.removeEventListener('propertychange', handlePropertyChange, false); } activeElement = null; activeElementInst = null; activeElementValue = null; activeElementValueProp = null; } /** * (For IE <=11) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetInstForInputEvent(topLevelType, targetInst) { if (topLevelType === 'topInput') { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return targetInst; } } function handleEventsForInputEventIE(topLevelType, target, targetInst) { if (topLevelType === 'topFocus') { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9-11, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(target, targetInst); } else if (topLevelType === 'topBlur') { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetInstForInputEventIE(topLevelType, targetInst) { if (topLevelType === 'topSelectionChange' || topLevelType === 'topKeyUp' || topLevelType === 'topKeyDown') { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementInst; } } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetInstForClickEvent(topLevelType, targetInst) { if (topLevelType === 'topClick') { return targetInst; } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; var getTargetInstFunc, handleEventFunc; if (shouldUseChangeEvent(targetNode)) { if (doesChangeEventBubble) { getTargetInstFunc = getTargetInstForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(targetNode)) { if (isInputEventSupported) { getTargetInstFunc = getTargetInstForInputEvent; } else { getTargetInstFunc = getTargetInstForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(targetNode)) { getTargetInstFunc = getTargetInstForClickEvent; } if (getTargetInstFunc) { var inst = getTargetInstFunc(topLevelType, targetInst); if (inst) { var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, nativeEventTarget); event.type = 'change'; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc(topLevelType, targetNode, targetInst); } } }; module.exports = ChangeEventPlugin; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41), _assign = __webpack_require__(10); var CallbackQueue = __webpack_require__(63); var PooledClass = __webpack_require__(56); var ReactFeatureFlags = __webpack_require__(64); var ReactReconciler = __webpack_require__(65); var Transaction = __webpack_require__(74); var invariant = __webpack_require__(14); var dirtyComponents = []; var updateBatchNumber = 0; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching strategy') : _prodInvariant('123') : void 0; } var NESTED_UPDATES = { initialize: function () { this.dirtyComponentsLength = dirtyComponents.length; }, close: function () { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function () { this.callbackQueue.reset(); }, close: function () { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */true); } _assign(ReactUpdatesFlushTransaction.prototype, Transaction, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, destructor: function () { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function (method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(); return batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; !(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to match dirty-components array length (%s).', len, dirtyComponents.length) : _prodInvariant('124', len, dirtyComponents.length) : void 0; // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); // Any updates enqueued while reconciling must be performed after this entire // batch. Otherwise, if dirtyComponents is [A, B] where A has children B and // C, B could update twice in a single batch if C's render enqueues an update // to B (since B would have already updated, we should skip it, and the only // way we can know to do so is by checking the batch counter). updateBatchNumber++; for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var namedComponent = component; // Duck type TopLevelWrapper. This is probably always true. if (component._currentElement.type.isReactTopLevelWrapper) { namedComponent = component._renderedComponent; } markerName = 'React update: ' + namedComponent.getName(); console.time(markerName); } ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber); if (markerName) { console.timeEnd(markerName); } if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance()); } } } } var flushBatchedUpdates = function () { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } }; /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); if (component._updateBatchNumber == null) { component._updateBatchNumber = updateBatchNumber + 1; } } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { !batchingStrategy.isBatchingUpdates ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context whereupdates are not being batched.') : _prodInvariant('125') : void 0; asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function (ReconcileTransaction) { !ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : _prodInvariant('126') : void 0; ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function (_batchingStrategy) { !_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : _prodInvariant('127') : void 0; !(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : _prodInvariant('128') : void 0; !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : _prodInvariant('129') : void 0; batchingStrategy = _batchingStrategy; } }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, asap: asap }; module.exports = ReactUpdates; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var PooledClass = __webpack_require__(56); var invariant = __webpack_require__(14); /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ var CallbackQueue = function () { function CallbackQueue(arg) { _classCallCheck(this, CallbackQueue); this._callbacks = null; this._contexts = null; this._arg = arg; } /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ CallbackQueue.prototype.enqueue = function enqueue(callback, context) { this._callbacks = this._callbacks || []; this._callbacks.push(callback); this._contexts = this._contexts || []; this._contexts.push(context); }; /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ CallbackQueue.prototype.notifyAll = function notifyAll() { var callbacks = this._callbacks; var contexts = this._contexts; var arg = this._arg; if (callbacks && contexts) { !(callbacks.length === contexts.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : _prodInvariant('24') : void 0; this._callbacks = null; this._contexts = null; for (var i = 0; i < callbacks.length; i++) { callbacks[i].call(contexts[i], arg); } callbacks.length = 0; contexts.length = 0; } }; CallbackQueue.prototype.checkpoint = function checkpoint() { return this._callbacks ? this._callbacks.length : 0; }; CallbackQueue.prototype.rollback = function rollback(len) { if (this._callbacks && this._contexts) { this._callbacks.length = len; this._contexts.length = len; } }; /** * Resets the internal queue. * * @internal */ CallbackQueue.prototype.reset = function reset() { this._callbacks = null; this._contexts = null; }; /** * `PooledClass` looks for this. */ CallbackQueue.prototype.destructor = function destructor() { this.reset(); }; return CallbackQueue; }(); module.exports = PooledClass.addPoolingTo(CallbackQueue); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 64 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactFeatureFlags = { // When true, call console.time() before and .timeEnd() after each top-level // render (both initial renders and updates). Useful when looking at prod-mode // timeline profiles in Chrome, for example. logTopLevelRenders: false }; module.exports = ReactFeatureFlags; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactRef = __webpack_require__(66); var ReactInstrumentation = __webpack_require__(68); var warning = __webpack_require__(17); /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef.attachRefs(this, this._currentElement); } var ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} the containing host component instance * @param {?object} info about the host container * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (internalInstance, transaction, hostParent, hostContainerInfo, context, parentDebugID // 0 in production and for roots ) { if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeMountComponent(internalInstance._debugID, internalInstance._currentElement, parentDebugID); } } var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context, parentDebugID); if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID); } } return markup; }, /** * Returns a value that can be passed to * ReactComponentEnvironment.replaceNodeWithMarkup. */ getHostNode: function (internalInstance) { return internalInstance.getHostNode(); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (internalInstance, safely) { if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUnmountComponent(internalInstance._debugID); } } ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(safely); if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID); } } }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function (internalInstance, nextElement, transaction, context) { var prevElement = internalInstance._currentElement; if (nextElement === prevElement && context === internalInstance._context) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for an element created outside a composite to be // deeply mutated and reused. // TODO: Bailing out early is just a perf optimization right? // TODO: Removing the return statement should affect correctness? return; } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement); } } var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement); if (refsChanged) { ReactRef.detachRefs(internalInstance, prevElement); } internalInstance.receiveComponent(nextElement, transaction, context); if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (internalInstance, transaction, updateBatchNumber) { if (internalInstance._updateBatchNumber !== updateBatchNumber) { // The component's enqueued batch number should always be the current // batch or the following one. process.env.NODE_ENV !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0; return; } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement); } } internalInstance.performUpdateIfNecessary(transaction); if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } } }; module.exports = ReactReconciler; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactOwner = __webpack_require__(67); var ReactRef = {}; function attachRef(ref, component, owner) { if (typeof ref === 'function') { ref(component.getPublicInstance()); } else { // Legacy ref ReactOwner.addComponentAsRefTo(component, ref, owner); } } function detachRef(ref, component, owner) { if (typeof ref === 'function') { ref(null); } else { // Legacy ref ReactOwner.removeComponentAsRefFrom(component, ref, owner); } } ReactRef.attachRefs = function (instance, element) { if (element === null || typeof element !== 'object') { return; } var ref = element.ref; if (ref != null) { attachRef(ref, instance, element._owner); } }; ReactRef.shouldUpdateRefs = function (prevElement, nextElement) { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. var prevRef = null; var prevOwner = null; if (prevElement !== null && typeof prevElement === 'object') { prevRef = prevElement.ref; prevOwner = prevElement._owner; } var nextRef = null; var nextOwner = null; if (nextElement !== null && typeof nextElement === 'object') { nextRef = nextElement.ref; nextOwner = nextElement._owner; } return prevRef !== nextRef || // If owner changes but we have an unchanged function ref, don't update refs typeof nextRef === 'string' && nextOwner !== prevOwner; }; ReactRef.detachRefs = function (instance, element) { if (element === null || typeof element !== 'object') { return; } var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; module.exports = ReactRef; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ function isValidOwner(object) { return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function'); } /** * ReactOwners are capable of storing references to owned components. * * All components are capable of //being// referenced by owner components, but * only ReactOwner components are capable of //referencing// owned components. * The named reference is known as a "ref". * * Refs are available when mounted and updated during reconciliation. * * var MyComponent = React.createClass({ * render: function() { * return ( * <div onClick={this.handleClick}> * <CustomComponent ref="custom" /> * </div> * ); * }, * handleClick: function() { * this.refs.custom.handleClick(); * }, * componentDidMount: function() { * this.refs.custom.initialize(); * } * }); * * Refs should rarely be used. When refs are used, they should only be done to * control data that is not handled by React's data flow. * * @class ReactOwner */ var ReactOwner = { /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function (component, ref, owner) { !isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('119') : void 0; owner.attachRef(ref, component); }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function (component, ref, owner) { !isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might be removing a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('120') : void 0; var ownerPublicInstance = owner.getPublicInstance(); // Check that `component`'s owner is still alive and that `component` is still the current ref // because we do not want to detach the ref if another component stole it. if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } }; module.exports = ReactOwner; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; // Trust the developer to only use ReactInstrumentation with a __DEV__ check var debugTool = null; if (process.env.NODE_ENV !== 'production') { var ReactDebugTool = __webpack_require__(69); debugTool = ReactDebugTool; } module.exports = { debugTool: debugTool }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactInvalidSetStateWarningHook = __webpack_require__(70); var ReactHostOperationHistoryHook = __webpack_require__(71); var ReactComponentTreeHook = __webpack_require__(32); var ExecutionEnvironment = __webpack_require__(54); var performanceNow = __webpack_require__(72); var warning = __webpack_require__(17); var hooks = []; var didHookThrowForEvent = {}; function callHook(event, fn, context, arg1, arg2, arg3, arg4, arg5) { try { fn.call(context, arg1, arg2, arg3, arg4, arg5); } catch (e) { process.env.NODE_ENV !== 'production' ? warning(didHookThrowForEvent[event], 'Exception thrown by hook while handling %s: %s', event, e + '\n' + e.stack) : void 0; didHookThrowForEvent[event] = true; } } function emitEvent(event, arg1, arg2, arg3, arg4, arg5) { for (var i = 0; i < hooks.length; i++) { var hook = hooks[i]; var fn = hook[event]; if (fn) { callHook(event, fn, hook, arg1, arg2, arg3, arg4, arg5); } } } var isProfiling = false; var flushHistory = []; var lifeCycleTimerStack = []; var currentFlushNesting = 0; var currentFlushMeasurements = []; var currentFlushStartTime = 0; var currentTimerDebugID = null; var currentTimerStartTime = 0; var currentTimerNestedFlushDuration = 0; var currentTimerType = null; var lifeCycleTimerHasWarned = false; function clearHistory() { ReactComponentTreeHook.purgeUnmountedComponents(); ReactHostOperationHistoryHook.clearHistory(); } function getTreeSnapshot(registeredIDs) { return registeredIDs.reduce(function (tree, id) { var ownerID = ReactComponentTreeHook.getOwnerID(id); var parentID = ReactComponentTreeHook.getParentID(id); tree[id] = { displayName: ReactComponentTreeHook.getDisplayName(id), text: ReactComponentTreeHook.getText(id), updateCount: ReactComponentTreeHook.getUpdateCount(id), childIDs: ReactComponentTreeHook.getChildIDs(id), // Text nodes don't have owners but this is close enough. ownerID: ownerID || parentID && ReactComponentTreeHook.getOwnerID(parentID) || 0, parentID: parentID }; return tree; }, {}); } function resetMeasurements() { var previousStartTime = currentFlushStartTime; var previousMeasurements = currentFlushMeasurements; var previousOperations = ReactHostOperationHistoryHook.getHistory(); if (currentFlushNesting === 0) { currentFlushStartTime = 0; currentFlushMeasurements = []; clearHistory(); return; } if (previousMeasurements.length || previousOperations.length) { var registeredIDs = ReactComponentTreeHook.getRegisteredIDs(); flushHistory.push({ duration: performanceNow() - previousStartTime, measurements: previousMeasurements || [], operations: previousOperations || [], treeSnapshot: getTreeSnapshot(registeredIDs) }); } clearHistory(); currentFlushStartTime = performanceNow(); currentFlushMeasurements = []; } function checkDebugID(debugID) { var allowRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (allowRoot && debugID === 0) { return; } if (!debugID) { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDebugTool: debugID may not be empty.') : void 0; } } function beginLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType && !lifeCycleTimerHasWarned) { process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'Did not expect %s timer to start while %s timer is still in ' + 'progress for %s instance.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; lifeCycleTimerHasWarned = true; } currentTimerStartTime = performanceNow(); currentTimerNestedFlushDuration = 0; currentTimerDebugID = debugID; currentTimerType = timerType; } function endLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) { process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'We did not expect %s timer to stop while %s timer is still in ' + 'progress for %s instance. Please report this as a bug in React.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; lifeCycleTimerHasWarned = true; } if (isProfiling) { currentFlushMeasurements.push({ timerType: timerType, instanceID: debugID, duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration }); } currentTimerStartTime = 0; currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; } function pauseCurrentLifeCycleTimer() { var currentTimer = { startTime: currentTimerStartTime, nestedFlushStartTime: performanceNow(), debugID: currentTimerDebugID, timerType: currentTimerType }; lifeCycleTimerStack.push(currentTimer); currentTimerStartTime = 0; currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; } function resumeCurrentLifeCycleTimer() { var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop(), startTime = _lifeCycleTimerStack$.startTime, nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime, debugID = _lifeCycleTimerStack$.debugID, timerType = _lifeCycleTimerStack$.timerType; var nestedFlushDuration = performanceNow() - nestedFlushStartTime; currentTimerStartTime = startTime; currentTimerNestedFlushDuration += nestedFlushDuration; currentTimerDebugID = debugID; currentTimerType = timerType; } var lastMarkTimeStamp = 0; var canUsePerformanceMeasure = // $FlowFixMe https://github.com/facebook/flow/issues/2345 typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; function shouldMark(debugID) { if (!isProfiling || !canUsePerformanceMeasure) { return false; } var element = ReactComponentTreeHook.getElement(debugID); if (element == null || typeof element !== 'object') { return false; } var isHostElement = typeof element.type === 'string'; if (isHostElement) { return false; } return true; } function markBegin(debugID, markType) { if (!shouldMark(debugID)) { return; } var markName = debugID + '::' + markType; lastMarkTimeStamp = performanceNow(); performance.mark(markName); } function markEnd(debugID, markType) { if (!shouldMark(debugID)) { return; } var markName = debugID + '::' + markType; var displayName = ReactComponentTreeHook.getDisplayName(debugID) || 'Unknown'; // Chrome has an issue of dropping markers recorded too fast: // https://bugs.chromium.org/p/chromium/issues/detail?id=640652 // To work around this, we will not report very small measurements. // I determined the magic number by tweaking it back and forth. // 0.05ms was enough to prevent the issue, but I set it to 0.1ms to be safe. // When the bug is fixed, we can `measure()` unconditionally if we want to. var timeStamp = performanceNow(); if (timeStamp - lastMarkTimeStamp > 0.1) { var measurementName = displayName + ' [' + markType + ']'; performance.measure(measurementName, markName); } performance.clearMarks(markName); performance.clearMeasures(measurementName); } var ReactDebugTool = { addHook: function (hook) { hooks.push(hook); }, removeHook: function (hook) { for (var i = 0; i < hooks.length; i++) { if (hooks[i] === hook) { hooks.splice(i, 1); i--; } } }, isProfiling: function () { return isProfiling; }, beginProfiling: function () { if (isProfiling) { return; } isProfiling = true; flushHistory.length = 0; resetMeasurements(); ReactDebugTool.addHook(ReactHostOperationHistoryHook); }, endProfiling: function () { if (!isProfiling) { return; } isProfiling = false; resetMeasurements(); ReactDebugTool.removeHook(ReactHostOperationHistoryHook); }, getFlushHistory: function () { return flushHistory; }, onBeginFlush: function () { currentFlushNesting++; resetMeasurements(); pauseCurrentLifeCycleTimer(); emitEvent('onBeginFlush'); }, onEndFlush: function () { resetMeasurements(); currentFlushNesting--; resumeCurrentLifeCycleTimer(); emitEvent('onEndFlush'); }, onBeginLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); emitEvent('onBeginLifeCycleTimer', debugID, timerType); markBegin(debugID, timerType); beginLifeCycleTimer(debugID, timerType); }, onEndLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); endLifeCycleTimer(debugID, timerType); markEnd(debugID, timerType); emitEvent('onEndLifeCycleTimer', debugID, timerType); }, onBeginProcessingChildContext: function () { emitEvent('onBeginProcessingChildContext'); }, onEndProcessingChildContext: function () { emitEvent('onEndProcessingChildContext'); }, onHostOperation: function (operation) { checkDebugID(operation.instanceID); emitEvent('onHostOperation', operation); }, onSetState: function () { emitEvent('onSetState'); }, onSetChildren: function (debugID, childDebugIDs) { checkDebugID(debugID); childDebugIDs.forEach(checkDebugID); emitEvent('onSetChildren', debugID, childDebugIDs); }, onBeforeMountComponent: function (debugID, element, parentDebugID) { checkDebugID(debugID); checkDebugID(parentDebugID, true); emitEvent('onBeforeMountComponent', debugID, element, parentDebugID); markBegin(debugID, 'mount'); }, onMountComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'mount'); emitEvent('onMountComponent', debugID); }, onBeforeUpdateComponent: function (debugID, element) { checkDebugID(debugID); emitEvent('onBeforeUpdateComponent', debugID, element); markBegin(debugID, 'update'); }, onUpdateComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'update'); emitEvent('onUpdateComponent', debugID); }, onBeforeUnmountComponent: function (debugID) { checkDebugID(debugID); emitEvent('onBeforeUnmountComponent', debugID); markBegin(debugID, 'unmount'); }, onUnmountComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'unmount'); emitEvent('onUnmountComponent', debugID); }, onTestEvent: function () { emitEvent('onTestEvent'); } }; // TODO remove these when RN/www gets updated ReactDebugTool.addDevtool = ReactDebugTool.addHook; ReactDebugTool.removeDevtool = ReactDebugTool.removeHook; ReactDebugTool.addHook(ReactInvalidSetStateWarningHook); ReactDebugTool.addHook(ReactComponentTreeHook); var url = ExecutionEnvironment.canUseDOM && window.location.href || ''; if (/[?&]react_perf\b/.test(url)) { ReactDebugTool.beginProfiling(); } module.exports = ReactDebugTool; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var warning = __webpack_require__(17); if (process.env.NODE_ENV !== 'production') { var processingChildContext = false; var warnInvalidSetState = function () { process.env.NODE_ENV !== 'production' ? warning(!processingChildContext, 'setState(...): Cannot call setState() inside getChildContext()') : void 0; }; } var ReactInvalidSetStateWarningHook = { onBeginProcessingChildContext: function () { processingChildContext = true; }, onEndProcessingChildContext: function () { processingChildContext = false; }, onSetState: function () { warnInvalidSetState(); } }; module.exports = ReactInvalidSetStateWarningHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 71 */ /***/ function(module, exports) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var history = []; var ReactHostOperationHistoryHook = { onHostOperation: function (operation) { history.push(operation); }, clearHistory: function () { if (ReactHostOperationHistoryHook._preventClearing) { // Should only be used for tests. return; } history = []; }, getHistory: function () { return history; } }; module.exports = ReactHostOperationHistoryHook; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var performance = __webpack_require__(73); var performanceNow; /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ if (performance.now) { performanceNow = function performanceNow() { return performance.now(); }; } else { performanceNow = function performanceNow() { return Date.now(); }; } module.exports = performanceNow; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var ExecutionEnvironment = __webpack_require__(54); var performance; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.msPerformance || window.webkitPerformance; } module.exports = performance || {}; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); var OBSERVED_ERROR = {}; /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM updates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var TransactionImpl = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function () { this.transactionWrappers = this.getTransactionWrappers(); if (this.wrapperInitData) { this.wrapperInitData.length = 0; } else { this.wrapperInitData = []; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function () { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. The optional arguments helps prevent the need * to bind in many cases. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} a Argument to pass to the method. * @param {Object?=} b Argument to pass to the method. * @param {Object?=} c Argument to pass to the method. * @param {Object?=} d Argument to pass to the method. * @param {Object?=} e Argument to pass to the method. * @param {Object?=} f Argument to pass to the method. * * @return {*} Return value from `method`. */ perform: function (method, scope, a, b, c, d, e, f) { !!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.') : _prodInvariant('27') : void 0; var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) {} } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function (startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) {} } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function (startIndex) { !this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : _prodInvariant('28') : void 0; var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== OBSERVED_ERROR && wrapper.close) { wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) {} } } } this.wrapperInitData.length = 0; } }; module.exports = TransactionImpl; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 75 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963 if (target.correspondingUseElement) { target = target.correspondingUseElement; } // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; } module.exports = getEventTarget; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(54); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = eventName in document; if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; /***/ }, /* 77 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { 'color': true, 'date': true, 'datetime': true, 'datetime-local': true, 'email': true, 'month': true, 'number': true, 'password': true, 'range': true, 'search': true, 'tel': true, 'text': true, 'time': true, 'url': true, 'week': true }; function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); if (nodeName === 'input') { return !!supportedInputTypes[elem.type]; } if (nodeName === 'textarea') { return true; } return false; } module.exports = isTextInputElement; /***/ }, /* 78 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Module that is injectable into `EventPluginHub`, that specifies a * deterministic ordering of `EventPlugin`s. A convenient way to reason about * plugins, without having to package every one of them. This is better than * having plugins be ordered in the same order that they are injected because * that ordering would be influenced by the packaging order. * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that * preventing default on events is convenient in `SimpleEventPlugin` handlers. */ var DefaultEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'TapEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin']; module.exports = DefaultEventPluginOrder; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPropagators = __webpack_require__(47); var ReactDOMComponentTree = __webpack_require__(40); var SyntheticMouseEvent = __webpack_require__(80); var eventTypes = { mouseEnter: { registrationName: 'onMouseEnter', dependencies: ['topMouseOut', 'topMouseOver'] }, mouseLeave: { registrationName: 'onMouseLeave', dependencies: ['topMouseOut', 'topMouseOver'] } }; var EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (topLevelType === 'topMouseOver' && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== 'topMouseOut' && topLevelType !== 'topMouseOver') { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; if (topLevelType === 'topMouseOut') { from = targetInst; var related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromNode = from == null ? win : ReactDOMComponentTree.getNodeFromInstance(from); var toNode = to == null ? win : ReactDOMComponentTree.getNodeFromInstance(to); var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = fromNode; leave.relatedTarget = toNode; var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = toNode; enter.relatedTarget = fromNode; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; } }; module.exports = EnterLeaveEventPlugin; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticUIEvent = __webpack_require__(81); var ViewportMetrics = __webpack_require__(82); var getEventModifierState = __webpack_require__(83); /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, getModifierState: getEventModifierState, button: function (event) { // Webkit, Firefox, IE9+ // which: 1 2 3 // button: 0 1 2 (standard) var button = event.button; if ('which' in event) { return button; } // IE<9 // which: undefined // button: 0 0 0 // button: 1 4 2 (onmouseup) return button === 2 ? 2 : button === 4 ? 1 : 0; }, buttons: null, relatedTarget: function (event) { return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); }, // "Proprietary" Interface. pageX: function (event) { return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; }, pageY: function (event) { return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(59); var getEventTarget = __webpack_require__(75); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function (event) { if (event.view) { return event.view; } var target = getEventTarget(event); if (target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function (event) { return event.detail || 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; /***/ }, /* 82 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function (scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; /***/ }, /* 83 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { 'Alt': 'altKey', 'Control': 'ctrlKey', 'Meta': 'metaKey', 'Shift': 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } module.exports = getEventModifierState; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(42); var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$')), Properties: { /** * Standard Properties */ accept: 0, acceptCharset: 0, accessKey: 0, action: 0, allowFullScreen: HAS_BOOLEAN_VALUE, allowTransparency: 0, alt: 0, // specifies target context for links with `preload` type as: 0, async: HAS_BOOLEAN_VALUE, autoComplete: 0, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: HAS_BOOLEAN_VALUE, cellPadding: 0, cellSpacing: 0, charSet: 0, challenge: 0, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, cite: 0, classID: 0, className: 0, cols: HAS_POSITIVE_NUMERIC_VALUE, colSpan: 0, content: 0, contentEditable: 0, contextMenu: 0, controls: HAS_BOOLEAN_VALUE, coords: 0, crossOrigin: 0, data: 0, // For `<object />` acts as `src`. dateTime: 0, 'default': HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: 0, disabled: HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: 0, encType: 0, form: 0, formAction: 0, formEncType: 0, formMethod: 0, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: 0, frameBorder: 0, headers: 0, height: 0, hidden: HAS_BOOLEAN_VALUE, high: 0, href: 0, hrefLang: 0, htmlFor: 0, httpEquiv: 0, icon: 0, id: 0, inputMode: 0, integrity: 0, is: 0, keyParams: 0, keyType: 0, kind: 0, label: 0, lang: 0, list: 0, loop: HAS_BOOLEAN_VALUE, low: 0, manifest: 0, marginHeight: 0, marginWidth: 0, max: 0, maxLength: 0, media: 0, mediaGroup: 0, method: 0, min: 0, minLength: 0, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: 0, nonce: 0, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: 0, pattern: 0, placeholder: 0, playsInline: HAS_BOOLEAN_VALUE, poster: 0, preload: 0, profile: 0, radioGroup: 0, readOnly: HAS_BOOLEAN_VALUE, referrerPolicy: 0, rel: 0, required: HAS_BOOLEAN_VALUE, reversed: HAS_BOOLEAN_VALUE, role: 0, rows: HAS_POSITIVE_NUMERIC_VALUE, rowSpan: HAS_NUMERIC_VALUE, sandbox: 0, scope: 0, scoped: HAS_BOOLEAN_VALUE, scrolling: 0, seamless: HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: 0, size: HAS_POSITIVE_NUMERIC_VALUE, sizes: 0, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: 0, src: 0, srcDoc: 0, srcLang: 0, srcSet: 0, start: HAS_NUMERIC_VALUE, step: 0, style: 0, summary: 0, tabIndex: 0, target: 0, title: 0, // Setting .type throws on non-<input> tags type: 0, useMap: 0, value: 0, width: 0, wmode: 0, wrap: 0, /** * RDFa Properties */ about: 0, datatype: 0, inlist: 0, prefix: 0, // property is also supported for OpenGraph in meta tags. property: 0, resource: 0, 'typeof': 0, vocab: 0, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: 0, autoCorrect: 0, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: 0, // color is for Safari mask-icon link color: 0, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: 0, itemScope: HAS_BOOLEAN_VALUE, itemType: 0, // itemID and itemRef are for Microdata support as well but // only specified in the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: 0, itemRef: 0, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: 0, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: 0, // IE-only attribute that controls focus behavior unselectable: 0 }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: {} }; module.exports = HTMLDOMPropertyConfig; /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMChildrenOperations = __webpack_require__(86); var ReactDOMIDOperations = __webpack_require__(97); /** * Abstracts away all functionality of the reconciler that requires knowledge of * the browser context. TODO: These callers should be refactored to avoid the * need for this injection. */ var ReactComponentBrowserEnvironment = { processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup }; module.exports = ReactComponentBrowserEnvironment; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMLazyTree = __webpack_require__(87); var Danger = __webpack_require__(93); var ReactDOMComponentTree = __webpack_require__(40); var ReactInstrumentation = __webpack_require__(68); var createMicrosoftUnsafeLocalFunction = __webpack_require__(90); var setInnerHTML = __webpack_require__(89); var setTextContent = __webpack_require__(91); function getNodeAfter(parentNode, node) { // Special case for text components, which return [open, close] comments // from getHostNode. if (Array.isArray(node)) { node = node[1]; } return node ? node.nextSibling : parentNode.firstChild; } /** * Inserts `childNode` as a child of `parentNode` at the `index`. * * @param {DOMElement} parentNode Parent node in which to insert. * @param {DOMElement} childNode Child node to insert. * @param {number} index Index at which to insert the child. * @internal */ var insertChildAt = createMicrosoftUnsafeLocalFunction(function (parentNode, childNode, referenceNode) { // We rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. (Using `undefined` is not allowed by all browsers so // we are careful to use `null`.) parentNode.insertBefore(childNode, referenceNode); }); function insertLazyTreeChildAt(parentNode, childTree, referenceNode) { DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode); } function moveChild(parentNode, childNode, referenceNode) { if (Array.isArray(childNode)) { moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode); } else { insertChildAt(parentNode, childNode, referenceNode); } } function removeChild(parentNode, childNode) { if (Array.isArray(childNode)) { var closingComment = childNode[1]; childNode = childNode[0]; removeDelimitedText(parentNode, childNode, closingComment); parentNode.removeChild(closingComment); } parentNode.removeChild(childNode); } function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) { var node = openingComment; while (true) { var nextNode = node.nextSibling; insertChildAt(parentNode, node, referenceNode); if (node === closingComment) { break; } node = nextNode; } } function removeDelimitedText(parentNode, startNode, closingComment) { while (true) { var node = startNode.nextSibling; if (node === closingComment) { // The closing comment is removed by ReactMultiChild. break; } else { parentNode.removeChild(node); } } } function replaceDelimitedText(openingComment, closingComment, stringText) { var parentNode = openingComment.parentNode; var nodeAfterComment = openingComment.nextSibling; if (nodeAfterComment === closingComment) { // There are no text nodes between the opening and closing comments; insert // a new one if stringText isn't empty. if (stringText) { insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment); } } else { if (stringText) { // Set the text content of the first node after the opening comment, and // remove all following nodes up until the closing comment. setTextContent(nodeAfterComment, stringText); removeDelimitedText(parentNode, nodeAfterComment, closingComment); } else { removeDelimitedText(parentNode, openingComment, closingComment); } } if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID, type: 'replace text', payload: stringText }); } } var dangerouslyReplaceNodeWithMarkup = Danger.dangerouslyReplaceNodeWithMarkup; if (process.env.NODE_ENV !== 'production') { dangerouslyReplaceNodeWithMarkup = function (oldChild, markup, prevInstance) { Danger.dangerouslyReplaceNodeWithMarkup(oldChild, markup); if (prevInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: prevInstance._debugID, type: 'replace with', payload: markup.toString() }); } else { var nextInstance = ReactDOMComponentTree.getInstanceFromNode(markup.node); if (nextInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: nextInstance._debugID, type: 'mount', payload: markup.toString() }); } } }; } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup, replaceDelimitedText: replaceDelimitedText, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @internal */ processUpdates: function (parentNode, updates) { if (process.env.NODE_ENV !== 'production') { var parentNodeDebugID = ReactDOMComponentTree.getInstanceFromNode(parentNode)._debugID; } for (var k = 0; k < updates.length; k++) { var update = updates[k]; switch (update.type) { case 'INSERT_MARKUP': insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode)); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'insert child', payload: { toIndex: update.toIndex, content: update.content.toString() } }); } break; case 'MOVE_EXISTING': moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode)); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'move child', payload: { fromIndex: update.fromIndex, toIndex: update.toIndex } }); } break; case 'SET_MARKUP': setInnerHTML(parentNode, update.content); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'replace children', payload: update.content.toString() }); } break; case 'TEXT_CONTENT': setTextContent(parentNode, update.content); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'replace text', payload: update.content.toString() }); } break; case 'REMOVE_NODE': removeChild(parentNode, update.fromNode); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'remove child', payload: { fromIndex: update.fromIndex } }); } break; } } } }; module.exports = DOMChildrenOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMNamespaces = __webpack_require__(88); var setInnerHTML = __webpack_require__(89); var createMicrosoftUnsafeLocalFunction = __webpack_require__(90); var setTextContent = __webpack_require__(91); var ELEMENT_NODE_TYPE = 1; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; /** * In IE (8-11) and Edge, appending nodes with no children is dramatically * faster than appending a full subtree, so we essentially queue up the * .appendChild calls here and apply them so each node is added to its parent * before any children are added. * * In other browsers, doing so is slower or neutral compared to the other order * (in Firefox, twice as slow) so we only do this inversion in IE. * * See https://github.com/spicyj/innerhtml-vs-createelement-vs-clonenode. */ var enableLazy = typeof document !== 'undefined' && typeof document.documentMode === 'number' || typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && /\bEdge\/\d/.test(navigator.userAgent); function insertTreeChildren(tree) { if (!enableLazy) { return; } var node = tree.node; var children = tree.children; if (children.length) { for (var i = 0; i < children.length; i++) { insertTreeBefore(node, children[i], null); } } else if (tree.html != null) { setInnerHTML(node, tree.html); } else if (tree.text != null) { setTextContent(node, tree.text); } } var insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (parentNode, tree, referenceNode) { // DocumentFragments aren't actually part of the DOM after insertion so // appending children won't update the DOM. We need to ensure the fragment // is properly populated first, breaking out of our lazy approach for just // this level. Also, some <object> plugins (like Flash Player) will read // <param> nodes immediately upon insertion into the DOM, so <object> // must also be populated prior to insertion into the DOM. if (tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE || tree.node.nodeType === ELEMENT_NODE_TYPE && tree.node.nodeName.toLowerCase() === 'object' && (tree.node.namespaceURI == null || tree.node.namespaceURI === DOMNamespaces.html)) { insertTreeChildren(tree); parentNode.insertBefore(tree.node, referenceNode); } else { parentNode.insertBefore(tree.node, referenceNode); insertTreeChildren(tree); } }); function replaceChildWithTree(oldNode, newTree) { oldNode.parentNode.replaceChild(newTree.node, oldNode); insertTreeChildren(newTree); } function queueChild(parentTree, childTree) { if (enableLazy) { parentTree.children.push(childTree); } else { parentTree.node.appendChild(childTree.node); } } function queueHTML(tree, html) { if (enableLazy) { tree.html = html; } else { setInnerHTML(tree.node, html); } } function queueText(tree, text) { if (enableLazy) { tree.text = text; } else { setTextContent(tree.node, text); } } function toString() { return this.node.nodeName; } function DOMLazyTree(node) { return { node: node, children: [], html: null, text: null, toString: toString }; } DOMLazyTree.insertTreeBefore = insertTreeBefore; DOMLazyTree.replaceChildWithTree = replaceChildWithTree; DOMLazyTree.queueChild = queueChild; DOMLazyTree.queueHTML = queueHTML; DOMLazyTree.queueText = queueText; module.exports = DOMLazyTree; /***/ }, /* 88 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMNamespaces = { html: 'http://www.w3.org/1999/xhtml', mathml: 'http://www.w3.org/1998/Math/MathML', svg: 'http://www.w3.org/2000/svg' }; module.exports = DOMNamespaces; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(54); var DOMNamespaces = __webpack_require__(88); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; var createMicrosoftUnsafeLocalFunction = __webpack_require__(90); // SVG temp container for IE lacking innerHTML var reusableSVGContainer; /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) { // IE does not have innerHTML for SVG nodes, so instead we inject the // new markup in a temp node and then move the child nodes across into // the target node if (node.namespaceURI === DOMNamespaces.svg && !('innerHTML' in node)) { reusableSVGContainer = reusableSVGContainer || document.createElement('div'); reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>'; var svgNode = reusableSVGContainer.firstChild; while (svgNode.firstChild) { node.appendChild(svgNode.firstChild); } } else { node.innerHTML = html; } }); if (ExecutionEnvironment.canUseDOM) { // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement('div'); testElement.innerHTML = ' '; if (testElement.innerHTML === '') { setInnerHTML = function (node, html) { // Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. // TODO: What to do on a detached node? if (node.parentNode) { node.parentNode.replaceChild(node, node); } // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. // UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode // in hopes that this is preserved even if "\uFEFF" is transformed to // the actual Unicode character (by Babel, for example). // https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216 node.innerHTML = String.fromCharCode(0xFEFF) + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } testElement = null; } module.exports = setInnerHTML; /***/ }, /* 90 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /* globals MSApp */ 'use strict'; /** * Create a function which has 'unsafe' privileges (required by windows8 apps) */ var createMicrosoftUnsafeLocalFunction = function (func) { if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { return function (arg0, arg1, arg2, arg3) { MSApp.execUnsafeLocalFunction(function () { return func(arg0, arg1, arg2, arg3); }); }; } else { return func; } }; module.exports = createMicrosoftUnsafeLocalFunction; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(54); var escapeTextContentForBrowser = __webpack_require__(92); var setInnerHTML = __webpack_require__(89); /** * Set the textContent property of a node, ensuring that whitespace is preserved * even in IE8. innerText is a poor substitute for textContent and, among many * issues, inserts <br> instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function (node, text) { if (text) { var firstChild = node.firstChild; if (firstChild && firstChild === node.lastChild && firstChild.nodeType === 3) { firstChild.nodeValue = text; return; } } node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function (node, text) { if (node.nodeType === 3) { node.nodeValue = text; return; } setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent; /***/ }, /* 92 */ /***/ function(module, exports) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * Based on the escape-html library, which is used under the MIT License below: * * Copyright (c) 2012-2013 TJ Holowaychuk * Copyright (c) 2015 Andreas Lubbe * Copyright (c) 2015 Tiancheng "Timothy" Gu * * 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. * */ 'use strict'; // code copied and modified from escape-html /** * Module variables. * @private */ var matchHtmlRegExp = /["'&<>]/; /** * Escape special characters in the given string of html. * * @param {string} string The string to escape for inserting into HTML * @return {string} * @public */ function escapeHtml(string) { var str = '' + string; var match = matchHtmlRegExp.exec(str); if (!match) { return str; } var escape; var html = ''; var index = 0; var lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '&quot;'; break; case 38: // & escape = '&amp;'; break; case 39: // ' escape = '&#x27;'; // modified from escape-html; used to be '&#39' break; case 60: // < escape = '&lt;'; break; case 62: // > escape = '&gt;'; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escape; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; } // end code copied and modified from escape-html /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { if (typeof text === 'boolean' || typeof text === 'number') { // this shortcircuit helps perf for types that we know will never have // special characters, especially given that this function is used often // for numeric dom ids. return '' + text; } return escapeHtml(text); } module.exports = escapeTextContentForBrowser; /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var DOMLazyTree = __webpack_require__(87); var ExecutionEnvironment = __webpack_require__(54); var createNodesFromMarkup = __webpack_require__(94); var emptyFunction = __webpack_require__(18); var invariant = __webpack_require__(14); var Danger = { /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) { !ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('56') : void 0; !markup ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : _prodInvariant('57') : void 0; !(oldChild.nodeName !== 'HTML') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See ReactDOMServer.renderToString().') : _prodInvariant('58') : void 0; if (typeof markup === 'string') { var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } else { DOMLazyTree.replaceChildWithTree(oldChild, markup); } } }; module.exports = Danger; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /*eslint-disable fb-www/unsafe-html*/ var ExecutionEnvironment = __webpack_require__(54); var createArrayFromMixed = __webpack_require__(95); var getMarkupWrap = __webpack_require__(96); var invariant = __webpack_require__(14); /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Pattern used by `getNodeName`. */ var nodeNamePattern = /^\s*<(\w+)/; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; !!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : void 0; var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { !handleScript ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : void 0; createArrayFromMixed(scripts).forEach(handleScript); } var nodes = Array.from(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var invariant = __webpack_require__(14); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFromMixed. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browsers builtin objects can report typeof 'function' (e.g. NodeList // in old versions of Safari). !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : void 0; !(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : void 0; !(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : void 0; !(typeof obj.callee !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant(false) : void 0; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return ( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFromMixed; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /*eslint-disable fb-www/unsafe-html */ var ExecutionEnvironment = __webpack_require__(54); var invariant = __webpack_require__(14); /** * Dummy container used to detect which wraps are necessary. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Some browsers cannot use `innerHTML` to render certain elements standalone, * so we wrap them, render the wrapped nodes, then extract the desired node. * * In IE8, certain elements cannot render alone, so wrap all elements ('*'). */ var shouldWrap = {}; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>']; var markupWrap = { '*': [1, '?<div>', '</div>'], 'area': [1, '<map>', '</map>'], 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], 'legend': [1, '<fieldset>', '</fieldset>'], 'param': [1, '<object>', '</object>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'optgroup': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap }; // Initialize the SVG elements since we know they'll always need to be wrapped // consistently. If they are created inside a <div> they will be initialized in // the wrong namespace (and will not display). var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan']; svgElements.forEach(function (nodeName) { markupWrap[nodeName] = svgWrap; shouldWrap[nodeName] = true; }); /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { !!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : void 0; if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } module.exports = getMarkupWrap; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMChildrenOperations = __webpack_require__(86); var ReactDOMComponentTree = __webpack_require__(40); /** * Operations used to process updates to DOM nodes. */ var ReactDOMIDOperations = { /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @internal */ dangerouslyProcessChildrenUpdates: function (parentInst, updates) { var node = ReactDOMComponentTree.getNodeFromInstance(parentInst); DOMChildrenOperations.processUpdates(node, updates); } }; module.exports = ReactDOMIDOperations; /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /* global hasOwnProperty:true */ 'use strict'; var _prodInvariant = __webpack_require__(41), _assign = __webpack_require__(10); var AutoFocusUtils = __webpack_require__(99); var CSSPropertyOperations = __webpack_require__(101); var DOMLazyTree = __webpack_require__(87); var DOMNamespaces = __webpack_require__(88); var DOMProperty = __webpack_require__(42); var DOMPropertyOperations = __webpack_require__(109); var EventPluginHub = __webpack_require__(48); var EventPluginRegistry = __webpack_require__(49); var ReactBrowserEventEmitter = __webpack_require__(111); var ReactDOMComponentFlags = __webpack_require__(43); var ReactDOMComponentTree = __webpack_require__(40); var ReactDOMInput = __webpack_require__(114); var ReactDOMOption = __webpack_require__(117); var ReactDOMSelect = __webpack_require__(118); var ReactDOMTextarea = __webpack_require__(119); var ReactInstrumentation = __webpack_require__(68); var ReactMultiChild = __webpack_require__(120); var ReactServerRenderingTransaction = __webpack_require__(139); var emptyFunction = __webpack_require__(18); var escapeTextContentForBrowser = __webpack_require__(92); var invariant = __webpack_require__(14); var isEventSupported = __webpack_require__(76); var shallowEqual = __webpack_require__(129); var validateDOMNesting = __webpack_require__(142); var warning = __webpack_require__(17); var Flags = ReactDOMComponentFlags; var deleteListener = EventPluginHub.deleteListener; var getNode = ReactDOMComponentTree.getNodeFromInstance; var listenTo = ReactBrowserEventEmitter.listenTo; var registrationNameModules = EventPluginRegistry.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = { 'string': true, 'number': true }; var STYLE = 'style'; var HTML = '__html'; var RESERVED_PROPS = { children: null, dangerouslySetInnerHTML: null, suppressContentEditableWarning: null }; // Node type for document fragments (Node.DOCUMENT_FRAGMENT_NODE). var DOC_FRAGMENT_TYPE = 11; function getDeclarationErrorAddendum(internalInstance) { if (internalInstance) { var owner = internalInstance._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' This DOM node was rendered by `' + name + '`.'; } } } return ''; } function friendlyStringify(obj) { if (typeof obj === 'object') { if (Array.isArray(obj)) { return '[' + obj.map(friendlyStringify).join(', ') + ']'; } else { var pairs = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key); pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key])); } } return '{' + pairs.join(', ') + '}'; } } else if (typeof obj === 'string') { return JSON.stringify(obj); } else if (typeof obj === 'function') { return '[function object]'; } // Differs from JSON.stringify in that undefined because undefined and that // inf and nan don't become null return String(obj); } var styleMutationWarning = {}; function checkAndWarnForMutatedStyle(style1, style2, component) { if (style1 == null || style2 == null) { return; } if (shallowEqual(style1, style2)) { return; } var componentName = component._tag; var owner = component._currentElement._owner; var ownerName; if (owner) { ownerName = owner.getName(); } var hash = ownerName + '|' + componentName; if (styleMutationWarning.hasOwnProperty(hash)) { return; } styleMutationWarning[hash] = true; process.env.NODE_ENV !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : void 0; } /** * @param {object} component * @param {?object} props */ function assertValidProps(component, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (voidElementTags[component._tag]) { !(props.children == null && props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : _prodInvariant('137', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : void 0; } if (props.dangerouslySetInnerHTML != null) { !(props.children == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : _prodInvariant('60') : void 0; !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.') : _prodInvariant('61') : void 0; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : void 0; process.env.NODE_ENV !== 'production' ? warning(props.suppressContentEditableWarning || !props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : void 0; process.env.NODE_ENV !== 'production' ? warning(props.onFocusIn == null && props.onFocusOut == null, 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.') : void 0; } !(props.style == null || typeof props.style === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + \'em\'}} when using JSX.%s', getDeclarationErrorAddendum(component)) : _prodInvariant('62', getDeclarationErrorAddendum(component)) : void 0; } function enqueuePutListener(inst, registrationName, listener, transaction) { if (transaction instanceof ReactServerRenderingTransaction) { return; } if (process.env.NODE_ENV !== 'production') { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. process.env.NODE_ENV !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : void 0; } var containerInfo = inst._hostContainerInfo; var isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOC_FRAGMENT_TYPE; var doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument; listenTo(registrationName, doc); transaction.getReactMountReady().enqueue(putListener, { inst: inst, registrationName: registrationName, listener: listener }); } function putListener() { var listenerToPut = this; EventPluginHub.putListener(listenerToPut.inst, listenerToPut.registrationName, listenerToPut.listener); } function inputPostMount() { var inst = this; ReactDOMInput.postMountWrapper(inst); } function textareaPostMount() { var inst = this; ReactDOMTextarea.postMountWrapper(inst); } function optionPostMount() { var inst = this; ReactDOMOption.postMountWrapper(inst); } var setAndValidateContentChildDev = emptyFunction; if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev = function (content) { var hasExistingContent = this._contentDebugID != null; var debugID = this._debugID; // This ID represents the inlined child that has no backing instance: var contentDebugID = -debugID; if (content == null) { if (hasExistingContent) { ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID); } this._contentDebugID = null; return; } validateDOMNesting(null, String(content), this, this._ancestorInfo); this._contentDebugID = contentDebugID; if (hasExistingContent) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(contentDebugID, content); ReactInstrumentation.debugTool.onUpdateComponent(contentDebugID); } else { ReactInstrumentation.debugTool.onBeforeMountComponent(contentDebugID, content, debugID); ReactInstrumentation.debugTool.onMountComponent(contentDebugID); ReactInstrumentation.debugTool.onSetChildren(debugID, [contentDebugID]); } }; } // There are so many media events, it makes sense to just // maintain a list rather than create a `trapBubbledEvent` for each var mediaEvents = { topAbort: 'abort', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topSeeked: 'seeked', topSeeking: 'seeking', topStalled: 'stalled', topSuspend: 'suspend', topTimeUpdate: 'timeupdate', topVolumeChange: 'volumechange', topWaiting: 'waiting' }; function trapBubbledEventsLocal() { var inst = this; // If a component renders to null or if another component fatals and causes // the state of the tree to be corrupted, `node` here can be null. !inst._rootNodeID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Must be mounted to trap events') : _prodInvariant('63') : void 0; var node = getNode(inst); !node ? process.env.NODE_ENV !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : _prodInvariant('64') : void 0; switch (inst._tag) { case 'iframe': case 'object': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', node)]; break; case 'video': case 'audio': inst._wrapperState.listeners = []; // Create listener for each media event for (var event in mediaEvents) { if (mediaEvents.hasOwnProperty(event)) { inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(event, mediaEvents[event], node)); } } break; case 'source': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topError', 'error', node)]; break; case 'img': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topError', 'error', node), ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', node)]; break; case 'form': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topReset', 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent('topSubmit', 'submit', node)]; break; case 'input': case 'select': case 'textarea': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topInvalid', 'invalid', node)]; break; } } function postUpdateSelectWrapper() { ReactDOMSelect.postUpdateWrapper(this); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special-case tags. var omittedCloseTags = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true }; var newlineEatingTags = { 'listing': true, 'pre': true, 'textarea': true }; // For HTML, certain tags cannot have children. This has the same purpose as // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = _assign({ 'menuitem': true }, omittedCloseTags); // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty = {}.hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty.call(validatedTagCache, tag)) { !VALID_TAG_REGEX.test(tag) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : _prodInvariant('65', tag) : void 0; validatedTagCache[tag] = true; } } function isCustomComponent(tagName, props) { return tagName.indexOf('-') >= 0 || props.is != null; } var globalIdCounter = 1; /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactMultiChild */ function ReactDOMComponent(element) { var tag = element.type; validateDangerousTag(tag); this._currentElement = element; this._tag = tag.toLowerCase(); this._namespaceURI = null; this._renderedChildren = null; this._previousStyle = null; this._previousStyleCopy = null; this._hostNode = null; this._hostParent = null; this._rootNodeID = 0; this._domID = 0; this._hostContainerInfo = null; this._wrapperState = null; this._topLevelWrapper = null; this._flags = 0; if (process.env.NODE_ENV !== 'production') { this._ancestorInfo = null; setAndValidateContentChildDev.call(this, null); } } ReactDOMComponent.displayName = 'ReactDOMComponent'; ReactDOMComponent.Mixin = { /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?ReactDOMComponent} the parent component instance * @param {?object} info about the host container * @param {object} context * @return {string} The computed markup. */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { this._rootNodeID = globalIdCounter++; this._domID = hostContainerInfo._idCounter++; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var props = this._currentElement.props; switch (this._tag) { case 'audio': case 'form': case 'iframe': case 'img': case 'link': case 'object': case 'source': case 'video': this._wrapperState = { listeners: null }; transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'input': ReactDOMInput.mountWrapper(this, props, hostParent); props = ReactDOMInput.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'option': ReactDOMOption.mountWrapper(this, props, hostParent); props = ReactDOMOption.getHostProps(this, props); break; case 'select': ReactDOMSelect.mountWrapper(this, props, hostParent); props = ReactDOMSelect.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'textarea': ReactDOMTextarea.mountWrapper(this, props, hostParent); props = ReactDOMTextarea.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; } assertValidProps(this, props); // We create tags in the namespace of their parent container, except HTML // tags get no namespace. var namespaceURI; var parentTag; if (hostParent != null) { namespaceURI = hostParent._namespaceURI; parentTag = hostParent._tag; } else if (hostContainerInfo._tag) { namespaceURI = hostContainerInfo._namespaceURI; parentTag = hostContainerInfo._tag; } if (namespaceURI == null || namespaceURI === DOMNamespaces.svg && parentTag === 'foreignobject') { namespaceURI = DOMNamespaces.html; } if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'svg') { namespaceURI = DOMNamespaces.svg; } else if (this._tag === 'math') { namespaceURI = DOMNamespaces.mathml; } } this._namespaceURI = namespaceURI; if (process.env.NODE_ENV !== 'production') { var parentInfo; if (hostParent != null) { parentInfo = hostParent._ancestorInfo; } else if (hostContainerInfo._tag) { parentInfo = hostContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting(this._tag, null, this, parentInfo); } this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this); } var mountImage; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var el; if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'script') { // Create the script via .innerHTML so its "parser-inserted" flag is // set to true and it does not execute var div = ownerDocument.createElement('div'); var type = this._currentElement.type; div.innerHTML = '<' + type + '></' + type + '>'; el = div.removeChild(div.firstChild); } else if (props.is) { el = ownerDocument.createElement(this._currentElement.type, props.is); } else { // Separate else branch instead of using `props.is || undefined` above becuase of a Firefox bug. // See discussion in https://github.com/facebook/react/pull/6896 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240 el = ownerDocument.createElement(this._currentElement.type); } } else { el = ownerDocument.createElementNS(namespaceURI, this._currentElement.type); } ReactDOMComponentTree.precacheNode(this, el); this._flags |= Flags.hasCachedChildNodes; if (!this._hostParent) { DOMPropertyOperations.setAttributeForRoot(el); } this._updateDOMProperties(null, props, transaction); var lazyTree = DOMLazyTree(el); this._createInitialChildren(transaction, props, context, lazyTree); mountImage = lazyTree; } else { var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props); var tagContent = this._createContentMarkup(transaction, props, context); if (!tagContent && omittedCloseTags[this._tag]) { mountImage = tagOpen + '/>'; } else { mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>'; } } switch (this._tag) { case 'input': transaction.getReactMountReady().enqueue(inputPostMount, this); if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'textarea': transaction.getReactMountReady().enqueue(textareaPostMount, this); if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'select': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'button': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'option': transaction.getReactMountReady().enqueue(optionPostMount, this); break; } return mountImage; }, /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function (transaction, props) { var ret = '<' + this._currentElement.type; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { if (propValue) { enqueuePutListener(this, propKey, propValue, transaction); } } else { if (propKey === STYLE) { if (propValue) { if (process.env.NODE_ENV !== 'production') { // See `_updateDOMProperties`. style block this._previousStyle = propValue; } propValue = this._previousStyleCopy = _assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this); } var markup = null; if (this._tag != null && isCustomComponent(this._tag, props)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); } } else { markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret; } if (!this._hostParent) { ret += ' ' + DOMPropertyOperations.createMarkupForRoot(); } ret += ' ' + DOMPropertyOperations.createMarkupForID(this._domID); return ret; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function (transaction, props, context) { var ret = ''; // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { ret = innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node ret = escapeTextContentForBrowser(contentToUse); if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, contentToUse); } } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); ret = mountImages.join(''); } } if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> return '\n' + ret; } else { return ret; } }, _createInitialChildren: function (transaction, props, context, lazyTree) { // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { DOMLazyTree.queueHTML(lazyTree, innerHTML.__html); } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; // TODO: Validate that text is allowed as a child of this node if (contentToUse != null) { // Avoid setting textContent when the text is empty. In IE11 setting // textContent on a text area will cause the placeholder to not // show within the textarea until it has been focused and blurred again. // https://github.com/facebook/react/issues/6731#issuecomment-254874553 if (contentToUse !== '') { if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, contentToUse); } DOMLazyTree.queueText(lazyTree, contentToUse); } } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); for (var i = 0; i < mountImages.length; i++) { DOMLazyTree.queueChild(lazyTree, mountImages[i]); } } } }, /** * Receives a next element and updates the component. * * @internal * @param {ReactElement} nextElement * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context */ receiveComponent: function (nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function (transaction, prevElement, nextElement, context) { var lastProps = prevElement.props; var nextProps = this._currentElement.props; switch (this._tag) { case 'input': lastProps = ReactDOMInput.getHostProps(this, lastProps); nextProps = ReactDOMInput.getHostProps(this, nextProps); break; case 'option': lastProps = ReactDOMOption.getHostProps(this, lastProps); nextProps = ReactDOMOption.getHostProps(this, nextProps); break; case 'select': lastProps = ReactDOMSelect.getHostProps(this, lastProps); nextProps = ReactDOMSelect.getHostProps(this, nextProps); break; case 'textarea': lastProps = ReactDOMTextarea.getHostProps(this, lastProps); nextProps = ReactDOMTextarea.getHostProps(this, nextProps); break; } assertValidProps(this, nextProps); this._updateDOMProperties(lastProps, nextProps, transaction); this._updateDOMChildren(lastProps, nextProps, transaction, context); switch (this._tag) { case 'input': // Update the wrapper around inputs *after* updating props. This has to // happen after `_updateDOMProperties`. Otherwise HTML5 input validations // raise warnings and prevent the new value from being assigned. ReactDOMInput.updateWrapper(this); break; case 'textarea': ReactDOMTextarea.updateWrapper(this); break; case 'select': // <select> value update needs to occur after <option> children // reconciliation transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); break; } }, /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {object} nextProps * @param {?DOMElement} node */ _updateDOMProperties: function (lastProps, nextProps, transaction) { var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) { continue; } if (propKey === STYLE) { var lastStyle = this._previousStyleCopy; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } this._previousStyleCopy = null; } else if (registrationNameModules.hasOwnProperty(propKey)) { if (lastProps[propKey]) { // Only call deleteListener if there was a listener previously or // else willDeleteListener gets called when there wasn't actually a // listener (e.g., onClick={null}) deleteListener(this, propKey); } } else if (isCustomComponent(this._tag, lastProps)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations.deleteValueForAttribute(getNode(this), propKey); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps != null ? lastProps[propKey] : undefined; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) { continue; } if (propKey === STYLE) { if (nextProp) { if (process.env.NODE_ENV !== 'production') { checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this); this._previousStyle = nextProp; } nextProp = this._previousStyleCopy = _assign({}, nextProp); } else { this._previousStyleCopy = null; } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules.hasOwnProperty(propKey)) { if (nextProp) { enqueuePutListener(this, propKey, nextProp, transaction); } else if (lastProp) { deleteListener(this, propKey); } } else if (isCustomComponent(this._tag, nextProps)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations.setValueForAttribute(getNode(this), propKey, nextProp); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { var node = getNode(this); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertently setting to a string. This // brings us in line with the same behavior we have on initial render. if (nextProp != null) { DOMPropertyOperations.setValueForProperty(node, propKey, nextProp); } else { DOMPropertyOperations.deleteValueForProperty(node, propKey); } } } if (styleUpdates) { CSSPropertyOperations.setValueForStyles(getNode(this), styleUpdates, this); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {object} context */ _updateDOMChildren: function (lastProps, nextProps, transaction, context) { var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction, context); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, nextContent); } } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { this.updateMarkup('' + nextHtml); } if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } else if (nextChildren != null) { if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, null); } this.updateChildren(nextChildren, transaction, context); } }, getHostNode: function () { return getNode(this); }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function (safely) { switch (this._tag) { case 'audio': case 'form': case 'iframe': case 'img': case 'link': case 'object': case 'source': case 'video': var listeners = this._wrapperState.listeners; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].remove(); } } break; case 'html': case 'head': case 'body': /** * Components like <html> <head> and <body> can't be removed or added * easily in a cross-browser way, however it's valuable to be able to * take advantage of React's reconciliation for styling and <title> * management. So we just document it and throw in dangerous cases. */ true ? process.env.NODE_ENV !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.', this._tag) : _prodInvariant('66', this._tag) : void 0; break; } this.unmountChildren(safely); ReactDOMComponentTree.uncacheNode(this); EventPluginHub.deleteAllListeners(this); this._rootNodeID = 0; this._domID = 0; this._wrapperState = null; if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, null); } }, getPublicInstance: function () { return getNode(this); } }; _assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin); module.exports = ReactDOMComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMComponentTree = __webpack_require__(40); var focusNode = __webpack_require__(100); var AutoFocusUtils = { focusDOMComponent: function () { focusNode(ReactDOMComponentTree.getNodeFromInstance(this)); } }; module.exports = AutoFocusUtils; /***/ }, /* 100 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch (e) {} } module.exports = focusNode; /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var CSSProperty = __webpack_require__(102); var ExecutionEnvironment = __webpack_require__(54); var ReactInstrumentation = __webpack_require__(68); var camelizeStyleName = __webpack_require__(103); var dangerousStyleValue = __webpack_require__(105); var hyphenateStyleName = __webpack_require__(106); var memoizeStringOnly = __webpack_require__(108); var warning = __webpack_require__(17); var processStyleName = memoizeStringOnly(function (styleName) { return hyphenateStyleName(styleName); }); var hasShorthandPropertyBug = false; var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { var tempStyle = document.createElement('div').style; try { // IE8 throws "Invalid argument." if resetting shorthand style properties. tempStyle.font = ''; } catch (e) { hasShorthandPropertyBug = true; } // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if (process.env.NODE_ENV !== 'production') { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnedForNaNValue = false; var warnHyphenatedStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?%s', name, camelizeStyleName(name), checkRenderMessage(owner)) : void 0; }; var warnBadVendoredStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?%s', name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)) : void 0; }; var warnStyleValueWithSemicolon = function (name, value, owner) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon.%s ' + 'Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, '')) : void 0; }; var warnStyleValueIsNaN = function (name, value, owner) { if (warnedForNaNValue) { return; } warnedForNaNValue = true; process.env.NODE_ENV !== 'production' ? warning(false, '`NaN` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)) : void 0; }; var checkRenderMessage = function (owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; }; /** * @param {string} name * @param {*} value * @param {ReactDOMComponent} component */ var warnValidStyle = function (name, value, component) { var owner; if (component) { owner = component._currentElement._owner; } if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name, owner); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name, owner); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value, owner); } if (typeof value === 'number' && isNaN(value)) { warnStyleValueIsNaN(name, value, owner); } }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @param {ReactDOMComponent} component * @return {?string} */ createMarkupForStyles: function (styles, component) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (process.env.NODE_ENV !== 'production') { warnValidStyle(styleName, styleValue, component); } if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue, component) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles * @param {ReactDOMComponent} component */ setValueForStyles: function (node, styles, component) { if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: component._debugID, type: 'update styles', payload: styles }); } var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if (process.env.NODE_ENV !== 'production') { warnValidStyle(styleName, styles[styleName], component); } var styleValue = dangerousStyleValue(styleName, styles[styleName], component); if (styleName === 'float' || styleName === 'cssFloat') { styleName = styleFloatAccessor; } if (styleValue) { style[styleName] = styleValue; } else { var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; module.exports = CSSPropertyOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 102 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridRow: true, gridColumn: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundAttachment: true, backgroundColor: true, backgroundImage: true, backgroundPositionX: true, backgroundPositionY: true, backgroundRepeat: true }, backgroundPosition: { backgroundPositionX: true, backgroundPositionY: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true }, outline: { outlineWidth: true, outlineStyle: true, outlineColor: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var camelize = __webpack_require__(104); var msPattern = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); } module.exports = camelizeStyleName; /***/ }, /* 104 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } module.exports = camelize; /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var CSSProperty = __webpack_require__(102); var warning = __webpack_require__(17); var isUnitlessNumber = CSSProperty.isUnitlessNumber; var styleWarnings = {}; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @param {ReactDOMComponent} component * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, component) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value; // cast to string } if (typeof value === 'string') { if (process.env.NODE_ENV !== 'production') { // Allow '0' to pass through without warning. 0 is already special and // doesn't require units, so we don't need to warn about it. if (component && value !== '0') { var owner = component._currentElement._owner; var ownerName = owner ? owner.getName() : null; if (ownerName && !styleWarnings[ownerName]) { styleWarnings[ownerName] = {}; } var warned = false; if (ownerName) { var warnings = styleWarnings[ownerName]; warned = warnings[name]; if (!warned) { warnings[name] = true; } } if (!warned) { process.env.NODE_ENV !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value) : void 0; } } } value = value.trim(); } return value + 'px'; } module.exports = dangerousStyleValue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var hyphenate = __webpack_require__(107); var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } module.exports = hyphenateStyleName; /***/ }, /* 107 */ /***/ function(module, exports) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; /***/ }, /* 108 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * * @typechecks static-only */ 'use strict'; /** * Memoizes the return value of a function that accepts one string argument. */ function memoizeStringOnly(callback) { var cache = {}; return function (string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; } module.exports = memoizeStringOnly; /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(42); var ReactDOMComponentTree = __webpack_require__(40); var ReactInstrumentation = __webpack_require__(68); var quoteAttributeValueForBrowser = __webpack_require__(110); var warning = __webpack_require__(17); var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$'); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { return true; } if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : void 0; return false; } function shouldIgnoreValue(propertyInfo, value) { return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function (id) { return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id); }, setAttributeForID: function (node, id) { node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id); }, createMarkupForRoot: function () { return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""'; }, setAttributeForRoot: function (node) { node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, ''); }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function (name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { if (shouldIgnoreValue(propertyInfo, value)) { return ''; } var attributeName = propertyInfo.attributeName; if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { return attributeName + '=""'; } return attributeName + '=' + quoteAttributeValueForBrowser(value); } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); } return null; }, /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ createMarkupForCustomAttribute: function (name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function (node, name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(propertyInfo, value)) { this.deleteValueForProperty(node, name); return; } else if (propertyInfo.mustUseProperty) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propertyInfo.propertyName] = value; } else { var attributeName = propertyInfo.attributeName; var namespace = propertyInfo.attributeNamespace; // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. if (namespace) { node.setAttributeNS(namespace, attributeName, '' + value); } else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { node.setAttribute(attributeName, ''); } else { node.setAttribute(attributeName, '' + value); } } } else if (DOMProperty.isCustomAttribute(name)) { DOMPropertyOperations.setValueForAttribute(node, name, value); return; } if (process.env.NODE_ENV !== 'production') { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'update attribute', payload: payload }); } }, setValueForAttribute: function (node, name, value) { if (!isAttributeNameSafe(name)) { return; } if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } if (process.env.NODE_ENV !== 'production') { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'update attribute', payload: payload }); } }, /** * Deletes an attributes from a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForAttribute: function (node, name) { node.removeAttribute(name); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'remove attribute', payload: name }); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function (node, name) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, undefined); } else if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; if (propertyInfo.hasBooleanValue) { node[propName] = false; } else { node[propName] = ''; } } else { node.removeAttribute(propertyInfo.attributeName); } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'remove attribute', payload: name }); } } }; module.exports = DOMPropertyOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var escapeTextContentForBrowser = __webpack_require__(92); /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser(value) + '"'; } module.exports = quoteAttributeValueForBrowser; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var EventPluginRegistry = __webpack_require__(49); var ReactEventEmitterMixin = __webpack_require__(112); var ViewportMetrics = __webpack_require__(82); var getVendorPrefixedEventName = __webpack_require__(113); var isEventSupported = __webpack_require__(76); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var hasEventPageXY; var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topAbort: 'abort', topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend', topAnimationIteration: getVendorPrefixedEventName('animationiteration') || 'animationiteration', topAnimationStart: getVendorPrefixedEventName('animationstart') || 'animationstart', topBlur: 'blur', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topScroll: 'scroll', topSeeked: 'seeked', topSeeking: 'seeking', topSelectionChange: 'selectionchange', topStalled: 'stalled', topSuspend: 'suspend', topTextInput: 'textInput', topTimeUpdate: 'timeupdate', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topTransitionEnd: getVendorPrefixedEventName('transitionend') || 'transitionend', topVolumeChange: 'volumechange', topWaiting: 'waiting', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * EventPluginHub.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = _assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function (ReactEventListener) { ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function (enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function () { return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function (registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName]; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { if (dependency === 'topWheel') { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'wheel', mountAt); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'mousewheel', mountAt); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'DOMMouseScroll', mountAt); } } else if (dependency === 'topScroll') { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topScroll', 'scroll', mountAt); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topScroll', 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE); } } else if (dependency === 'topFocus' || dependency === 'topBlur') { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topFocus', 'focus', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topBlur', 'blur', mountAt); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topFocus', 'focusin', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topBlur', 'focusout', mountAt); } // to make sure blur and focus event listeners are only attached once isListening.topBlur = true; isListening.topFocus = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt); } isListening[dependency] = true; } } }, trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); }, trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); }, /** * Protect against document.createEvent() returning null * Some popup blocker extensions appear to do this: * https://github.com/facebook/react/issues/6887 */ supportsEventPageXY: function () { if (!document.createEvent) { return false; } var ev = document.createEvent('MouseEvent'); return ev != null && 'pageX' in ev; }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * ViewportMetrics is only used by SyntheticMouse/TouchEvent and only when * pageX/pageY isn't supported (legacy browsers). * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function () { if (hasEventPageXY === undefined) { hasEventPageXY = ReactBrowserEventEmitter.supportsEventPageXY(); } if (!hasEventPageXY && !isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } } }); module.exports = ReactBrowserEventEmitter; /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPluginHub = __webpack_require__(48); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(false); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. */ handleTopLevel: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events = EventPluginHub.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(54); /** * Generate a mapping of standard vendor prefixes using the defined style property and event name. * * @param {string} styleProp * @param {string} eventName * @returns {object} */ function makePrefixMap(styleProp, eventName) { var prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; prefixes['ms' + styleProp] = 'MS' + eventName; prefixes['O' + styleProp] = 'o' + eventName.toLowerCase(); return prefixes; } /** * A list of event names to a configurable list of vendor prefixes. */ var vendorPrefixes = { animationend: makePrefixMap('Animation', 'AnimationEnd'), animationiteration: makePrefixMap('Animation', 'AnimationIteration'), animationstart: makePrefixMap('Animation', 'AnimationStart'), transitionend: makePrefixMap('Transition', 'TransitionEnd') }; /** * Event names that have already been detected and prefixed (if applicable). */ var prefixedEventNames = {}; /** * Element to check for prefixes on. */ var style = {}; /** * Bootstrap if a DOM exists. */ if (ExecutionEnvironment.canUseDOM) { style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are usable, and if not remove them from the map. if (!('AnimationEvent' in window)) { delete vendorPrefixes.animationend.animation; delete vendorPrefixes.animationiteration.animation; delete vendorPrefixes.animationstart.animation; } // Same as above if (!('TransitionEvent' in window)) { delete vendorPrefixes.transitionend.transition; } } /** * Attempts to determine the correct vendor prefixed event name. * * @param {string} eventName * @returns {string} */ function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return prefixedEventNames[eventName] = prefixMap[styleProp]; } } return ''; } module.exports = getVendorPrefixedEventName; /***/ }, /* 114 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41), _assign = __webpack_require__(10); var DOMPropertyOperations = __webpack_require__(109); var LinkedValueUtils = __webpack_require__(115); var ReactDOMComponentTree = __webpack_require__(40); var ReactUpdates = __webpack_require__(62); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); var didWarnValueLink = false; var didWarnCheckedLink = false; var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; var didWarnUncontrolledToControlled = false; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMInput.updateWrapper(this); } } function isControlled(props) { var usesChecked = props.type === 'checkbox' || props.type === 'radio'; return usesChecked ? props.checked != null : props.value != null; } /** * Implements an <input> host component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = { getHostProps: function (inst, props) { var value = LinkedValueUtils.getValue(props); var checked = LinkedValueUtils.getChecked(props); var hostProps = _assign({ // Make sure we set .type before any other properties (setting .value // before .type means .value is lost in IE11 and below) type: undefined, // Make sure we set .step before .value (setting .value before .step // means .value is rounded on mount, based upon step precision) step: undefined, // Make sure we set .min & .max before .value (to ensure proper order // in corner cases such as min or max deriving from value, e.g. Issue #7170) min: undefined, max: undefined }, props, { defaultChecked: undefined, defaultValue: undefined, value: value != null ? value : inst._wrapperState.initialValue, checked: checked != null ? checked : inst._wrapperState.initialChecked, onChange: inst._wrapperState.onChange }); return hostProps; }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner); var owner = inst._currentElement._owner; if (props.valueLink !== undefined && !didWarnValueLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } if (props.checkedLink !== undefined && !didWarnCheckedLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`checkedLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnCheckedLink = true; } if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { process.env.NODE_ENV !== 'production' ? warning(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnCheckedDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { process.env.NODE_ENV !== 'production' ? warning(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnValueDefaultValue = true; } } var defaultValue = props.defaultValue; inst._wrapperState = { initialChecked: props.checked != null ? props.checked : props.defaultChecked, initialValue: props.value != null ? props.value : defaultValue, listeners: null, onChange: _handleChange.bind(inst) }; if (process.env.NODE_ENV !== 'production') { inst._wrapperState.controlled = isControlled(props); } }, updateWrapper: function (inst) { var props = inst._currentElement.props; if (process.env.NODE_ENV !== 'production') { var controlled = isControlled(props); var owner = inst._currentElement._owner; if (!inst._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { process.env.NODE_ENV !== 'production' ? warning(false, '%s is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnUncontrolledToControlled = true; } if (inst._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { process.env.NODE_ENV !== 'production' ? warning(false, '%s is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnControlledToUncontrolled = true; } } // TODO: Shouldn't this be getChecked(props)? var checked = props.checked; if (checked != null) { DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'checked', checked || false); } var node = ReactDOMComponentTree.getNodeFromInstance(inst); var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. var newValue = '' + value; // To avoid side effects (such as losing text selection), only set value if changed if (newValue !== node.value) { node.value = newValue; } } else { if (props.value == null && props.defaultValue != null) { // In Chrome, assigning defaultValue to certain input types triggers input validation. // For number inputs, the display value loses trailing decimal points. For email inputs, // Chrome raises "The specified value <x> is not a valid email address". // // Here we check to see if the defaultValue has actually changed, avoiding these problems // when the user is inputting text // // https://github.com/facebook/react/issues/7253 if (node.defaultValue !== '' + props.defaultValue) { node.defaultValue = '' + props.defaultValue; } } if (props.checked == null && props.defaultChecked != null) { node.defaultChecked = !!props.defaultChecked; } } }, postMountWrapper: function (inst) { var props = inst._currentElement.props; // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. var node = ReactDOMComponentTree.getNodeFromInstance(inst); // Detach value from defaultValue. We won't do anything if we're working on // submit or reset inputs as those values & defaultValues are linked. They // are not resetable nodes so this operation doesn't matter and actually // removes browser-default values (eg "Submit Query") when no value is // provided. switch (props.type) { case 'submit': case 'reset': break; case 'color': case 'date': case 'datetime': case 'datetime-local': case 'month': case 'time': case 'week': // This fixes the no-show issue on iOS Safari and Android Chrome: // https://github.com/facebook/react/issues/7233 node.value = ''; node.value = node.defaultValue; break; default: node.value = node.value; break; } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug // this is needed to work around a chrome bug where setting defaultChecked // will sometimes influence the value of checked (even after detachment). // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 // We need to temporarily unset name to avoid disrupting radio button groups. var name = node.name; if (name !== '') { node.name = ''; } node.defaultChecked = !node.defaultChecked; node.defaultChecked = !node.defaultChecked; if (name !== '') { node.name = name; } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); // Here we use asap to wait until all updates have propagated, which // is important when using controlled components within layers: // https://github.com/facebook/react/issues/1698 ReactUpdates.asap(forceUpdateIfMounted, this); var name = props.name; if (props.type === 'radio' && name != null) { var rootNode = ReactDOMComponentTree.getNodeFromInstance(this); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form, let's just use the global // `querySelectorAll` to ensure we don't miss anything. var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React radio buttons with non-React ones. var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode); !otherInstance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : _prodInvariant('90') : void 0; // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. ReactUpdates.asap(forceUpdateIfMounted, otherInstance); } } return returnValue; } module.exports = ReactDOMInput; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var React = __webpack_require__(8); var ReactPropTypesSecret = __webpack_require__(116); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(inputProps) { !(inputProps.checkedLink == null || inputProps.valueLink == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use checkedLink, you probably don\'t want to use valueLink and vice versa.') : _prodInvariant('87') : void 0; } function _assertValueLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.value == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want to use value or onChange, you probably don\'t want to use valueLink.') : _prodInvariant('88') : void 0; } function _assertCheckedLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.checked == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. If you want to use checked or onChange, you probably don\'t want to use checkedLink') : _prodInvariant('89') : void 0; } var propTypes = { value: function (props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, checked: function (props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, onChange: React.PropTypes.func }; var loggedTypeFailures = {}; function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { checkPropTypes: function (tagName, props, owner) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, tagName, 'prop', null, ReactPropTypesSecret); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(owner); process.env.NODE_ENV !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : void 0; } } }, /** * @param {object} inputProps Props for form component * @return {*} current value of the input either from value prop or link. */ getValue: function (inputProps) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.value; } return inputProps.value; }, /** * @param {object} inputProps Props for form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function (inputProps) { if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.value; } return inputProps.checked; }, /** * @param {object} inputProps Props for form component * @param {SyntheticEvent} event change event to handle */ executeOnChange: function (inputProps, event) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.requestChange(event.target.value); } else if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.requestChange(event.target.checked); } else if (inputProps.onChange) { return inputProps.onChange.call(undefined, event); } } }; module.exports = LinkedValueUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 116 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var React = __webpack_require__(8); var ReactDOMComponentTree = __webpack_require__(40); var ReactDOMSelect = __webpack_require__(118); var warning = __webpack_require__(17); var didWarnInvalidOptionChildren = false; function flattenChildren(children) { var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. React.Children.forEach(children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else if (!didWarnInvalidOptionChildren) { didWarnInvalidOptionChildren = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : void 0; } }); return content; } /** * Implements an <option> host component that warns when `selected` is set. */ var ReactDOMOption = { mountWrapper: function (inst, props, hostParent) { // TODO (yungsters): Remove support for `selected` in <option>. if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : void 0; } // Look up whether this option is 'selected' var selectValue = null; if (hostParent != null) { var selectParent = hostParent; if (selectParent._tag === 'optgroup') { selectParent = selectParent._hostParent; } if (selectParent != null && selectParent._tag === 'select') { selectValue = ReactDOMSelect.getSelectValueContext(selectParent); } } // If the value is null (e.g., no specified value or after initial mount) // or missing (e.g., for <datalist>), we don't change props.selected var selected = null; if (selectValue != null) { var value; if (props.value != null) { value = props.value + ''; } else { value = flattenChildren(props.children); } selected = false; if (Array.isArray(selectValue)) { // multiple for (var i = 0; i < selectValue.length; i++) { if ('' + selectValue[i] === value) { selected = true; break; } } } else { selected = '' + selectValue === value; } } inst._wrapperState = { selected: selected }; }, postMountWrapper: function (inst) { // value="" should make a value attribute (#6219) var props = inst._currentElement.props; if (props.value != null) { var node = ReactDOMComponentTree.getNodeFromInstance(inst); node.setAttribute('value', props.value); } }, getHostProps: function (inst, props) { var hostProps = _assign({ selected: undefined, children: undefined }, props); // Read state only from initial mount because <select> updates value // manually; we need the initial state only for server rendering if (inst._wrapperState.selected != null) { hostProps.selected = inst._wrapperState.selected; } var content = flattenChildren(props.children); if (content) { hostProps.children = content; } return hostProps; } }; module.exports = ReactDOMOption; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var LinkedValueUtils = __webpack_require__(115); var ReactDOMComponentTree = __webpack_require__(40); var ReactUpdates = __webpack_require__(62); var warning = __webpack_require__(17); var didWarnValueLink = false; var didWarnValueDefaultValue = false; function updateOptionsIfPendingUpdateAndMounted() { if (this._rootNodeID && this._wrapperState.pendingUpdate) { this._wrapperState.pendingUpdate = false; var props = this._currentElement.props; var value = LinkedValueUtils.getValue(props); if (value != null) { updateOptions(this, Boolean(props.multiple), value); } } } function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } var valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. * @private */ function checkSelectPropTypes(inst, props) { var owner = inst._currentElement._owner; LinkedValueUtils.checkPropTypes('select', props, owner); if (props.valueLink !== undefined && !didWarnValueLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `select` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } var isArray = Array.isArray(props[propName]); if (props.multiple && !isArray) { process.env.NODE_ENV !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } else if (!props.multiple && isArray) { process.env.NODE_ENV !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } } } /** * @param {ReactDOMComponent} inst * @param {boolean} multiple * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(inst, multiple, propValue) { var selectedValue, i; var options = ReactDOMComponentTree.getNodeFromInstance(inst).options; if (multiple) { selectedValue = {}; for (i = 0; i < propValue.length; i++) { selectedValue['' + propValue[i]] = true; } for (i = 0; i < options.length; i++) { var selected = selectedValue.hasOwnProperty(options[i].value); if (options[i].selected !== selected) { options[i].selected = selected; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. selectedValue = '' + propValue; for (i = 0; i < options.length; i++) { if (options[i].value === selectedValue) { options[i].selected = true; return; } } if (options.length) { options[0].selected = true; } } } /** * Implements a <select> host component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = { getHostProps: function (inst, props) { return _assign({}, props, { onChange: inst._wrapperState.onChange, value: undefined }); }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { checkSelectPropTypes(inst, props); } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { pendingUpdate: false, initialValue: value != null ? value : props.defaultValue, listeners: null, onChange: _handleChange.bind(inst), wasMultiple: Boolean(props.multiple) }; if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { process.env.NODE_ENV !== 'production' ? warning(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValueDefaultValue = true; } }, getSelectValueContext: function (inst) { // ReactDOMOption looks at this initial value so the initial generated // markup has correct `selected` attributes return inst._wrapperState.initialValue; }, postUpdateWrapper: function (inst) { var props = inst._currentElement.props; // After the initial mount, we control selected-ness manually so don't pass // this value down inst._wrapperState.initialValue = undefined; var wasMultiple = inst._wrapperState.wasMultiple; inst._wrapperState.wasMultiple = Boolean(props.multiple); var value = LinkedValueUtils.getValue(props); if (value != null) { inst._wrapperState.pendingUpdate = false; updateOptions(inst, Boolean(props.multiple), value); } else if (wasMultiple !== Boolean(props.multiple)) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (props.defaultValue != null) { updateOptions(inst, Boolean(props.multiple), props.defaultValue); } else { // Revert the select back to its default unselected state. updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : ''); } } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); if (this._rootNodeID) { this._wrapperState.pendingUpdate = true; } ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); return returnValue; } module.exports = ReactDOMSelect; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41), _assign = __webpack_require__(10); var LinkedValueUtils = __webpack_require__(115); var ReactDOMComponentTree = __webpack_require__(40); var ReactUpdates = __webpack_require__(62); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); var didWarnValueLink = false; var didWarnValDefaultVal = false; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMTextarea.updateWrapper(this); } } /** * Implements a <textarea> host component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = { getHostProps: function (inst, props) { !(props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : _prodInvariant('91') : void 0; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. We could add a check in setTextContent // to only set the value if/when the value differs from the node value (which would // completely solve this IE9 bug), but Sebastian+Ben seemed to like this solution. // The value can be a boolean or object so that's why it's forced to be a string. var hostProps = _assign({}, props, { value: undefined, defaultValue: undefined, children: '' + inst._wrapperState.initialValue, onChange: inst._wrapperState.onChange }); return hostProps; }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner); if (props.valueLink !== undefined && !didWarnValueLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `textarea` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) { process.env.NODE_ENV !== 'production' ? warning(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValDefaultVal = true; } } var value = LinkedValueUtils.getValue(props); var initialValue = value; // Only bother fetching default value if we're going to use it if (value == null) { var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = props.children; if (children != null) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : void 0; } !(defaultValue == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : _prodInvariant('92') : void 0; if (Array.isArray(children)) { !(children.length <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : _prodInvariant('93') : void 0; children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } initialValue = defaultValue; } inst._wrapperState = { initialValue: '' + initialValue, listeners: null, onChange: _handleChange.bind(inst) }; }, updateWrapper: function (inst) { var props = inst._currentElement.props; var node = ReactDOMComponentTree.getNodeFromInstance(inst); var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. var newValue = '' + value; // To avoid side effects (such as losing text selection), only set value if changed if (newValue !== node.value) { node.value = newValue; } if (props.defaultValue == null) { node.defaultValue = newValue; } } if (props.defaultValue != null) { node.defaultValue = props.defaultValue; } }, postMountWrapper: function (inst) { // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. var node = ReactDOMComponentTree.getNodeFromInstance(inst); var textContent = node.textContent; // Only set node.value if textContent is equal to the expected // initial value. In IE10/IE11 there is a bug where the placeholder attribute // will populate textContent as well. // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/ if (textContent === inst._wrapperState.initialValue) { node.value = textContent; } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); ReactUpdates.asap(forceUpdateIfMounted, this); return returnValue; } module.exports = ReactDOMTextarea; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var ReactComponentEnvironment = __webpack_require__(121); var ReactInstanceMap = __webpack_require__(122); var ReactInstrumentation = __webpack_require__(68); var ReactCurrentOwner = __webpack_require__(16); var ReactReconciler = __webpack_require__(65); var ReactChildReconciler = __webpack_require__(123); var emptyFunction = __webpack_require__(18); var flattenChildren = __webpack_require__(138); var invariant = __webpack_require__(14); /** * Make an update for markup to be rendered and inserted at a supplied index. * * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function makeInsertMarkup(markup, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: 'INSERT_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for moving an existing element to another index. * * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function makeMove(child, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: 'MOVE_EXISTING', content: null, fromIndex: child._mountIndex, fromNode: ReactReconciler.getHostNode(child), toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for removing an element at an index. * * @param {number} fromIndex Index of the element to remove. * @private */ function makeRemove(child, node) { // NOTE: Null values reduce hidden classes. return { type: 'REMOVE_NODE', content: null, fromIndex: child._mountIndex, fromNode: node, toIndex: null, afterNode: null }; } /** * Make an update for setting the markup of a node. * * @param {string} markup Markup that renders into an element. * @private */ function makeSetMarkup(markup) { // NOTE: Null values reduce hidden classes. return { type: 'SET_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Make an update for setting the text content. * * @param {string} textContent Text content to set. * @private */ function makeTextContent(textContent) { // NOTE: Null values reduce hidden classes. return { type: 'TEXT_CONTENT', content: textContent, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Push an update, if any, onto the queue. Creates a new queue if none is * passed and always returns the queue. Mutative. */ function enqueue(queue, update) { if (update) { queue = queue || []; queue.push(update); } return queue; } /** * Processes any enqueued updates. * * @private */ function processQueue(inst, updateQueue) { ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue); } var setChildrenForInstrumentation = emptyFunction; if (process.env.NODE_ENV !== 'production') { var getDebugID = function (inst) { if (!inst._debugID) { // Check for ART-like instances. TODO: This is silly/gross. var internal; if (internal = ReactInstanceMap.get(inst)) { inst = internal; } } return inst._debugID; }; setChildrenForInstrumentation = function (children) { var debugID = getDebugID(this); // TODO: React Native empty components are also multichild. // This means they still get into this method but don't have _debugID. if (debugID !== 0) { ReactInstrumentation.debugTool.onSetChildren(debugID, children ? Object.keys(children).map(function (key) { return children[key]._debugID; }) : []); } }; } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { _reconcilerInstantiateChildren: function (nestedChildren, transaction, context) { if (process.env.NODE_ENV !== 'production') { var selfDebugID = getDebugID(this); if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context, selfDebugID); } finally { ReactCurrentOwner.current = null; } } } return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); }, _reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context) { var nextChildren; var selfDebugID = 0; if (process.env.NODE_ENV !== 'production') { selfDebugID = getDebugID(this); if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID); } finally { ReactCurrentOwner.current = null; } ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID); return nextChildren; } } nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID); ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID); return nextChildren; }, /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function (nestedChildren, transaction, context) { var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); this._renderedChildren = children; var mountImages = []; var index = 0; for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; var selfDebugID = 0; if (process.env.NODE_ENV !== 'production') { selfDebugID = getDebugID(this); } var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._hostContainerInfo, context, selfDebugID); child._mountIndex = index++; mountImages.push(mountImage); } } if (process.env.NODE_ENV !== 'production') { setChildrenForInstrumentation.call(this, children); } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function (nextContent) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } // Set new text content. var updates = [makeTextContent(nextContent)]; processQueue(this, updates); }, /** * Replaces any rendered children with a markup string. * * @param {string} nextMarkup String of markup. * @internal */ updateMarkup: function (nextMarkup) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } var updates = [makeSetMarkup(nextMarkup)]; processQueue(this, updates); }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function (nextNestedChildrenElements, transaction, context) { // Hook used by React ART this._updateChildren(nextNestedChildrenElements, transaction, context); }, /** * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function (nextNestedChildrenElements, transaction, context) { var prevChildren = this._renderedChildren; var removedNodes = {}; var mountImages = []; var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context); if (!nextChildren && !prevChildren) { return; } var updates = null; var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var nextIndex = 0; var lastIndex = 0; // `nextMountIndex` will increment for each newly mounted child. var nextMountIndex = 0; var lastPlacedNode = null; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (prevChild === nextChild) { updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); // The `removedNodes` loop below will actually remove the child. } // The child must be instantiated before it's mounted. updates = enqueue(updates, this._mountChildAtIndex(nextChild, mountImages[nextMountIndex], lastPlacedNode, nextIndex, transaction, context)); nextMountIndex++; } nextIndex++; lastPlacedNode = ReactReconciler.getHostNode(nextChild); } // Remove children that are no longer present. for (name in removedNodes) { if (removedNodes.hasOwnProperty(name)) { updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name])); } } if (updates) { processQueue(this, updates); } this._renderedChildren = nextChildren; if (process.env.NODE_ENV !== 'production') { setChildrenForInstrumentation.call(this, nextChildren); } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. It does not actually perform any * backend operations. * * @internal */ unmountChildren: function (safely) { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren, safely); this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function (child, afterNode, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { return makeMove(child, afterNode, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function (child, afterNode, mountImage) { return makeInsertMarkup(mountImage, afterNode, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function (child, node) { return makeRemove(child, node); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildAtIndex: function (child, mountImage, afterNode, index, transaction, context) { child._mountIndex = index; return this.createChild(child, afterNode, mountImage); }, /** * Unmounts a rendered child. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @private */ _unmountChild: function (child, node) { var update = this.removeChild(child, node); child._mountIndex = null; return update; } } }; module.exports = ReactMultiChild; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); var injected = false; var ReactComponentEnvironment = { /** * Optionally injectable hook for swapping out mount images in the middle of * the tree. */ replaceNodeWithMarkup: null, /** * Optionally injectable hook for processing a queue of child updates. Will * later move into MultiChildComponents. */ processChildrenUpdates: null, injection: { injectEnvironment: function (environment) { !!injected ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : _prodInvariant('104') : void 0; ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; module.exports = ReactComponentEnvironment; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 122 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. */ // TODO: Replace this with ES6: var ReactInstanceMap = new Map(); var ReactInstanceMap = { /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ remove: function (key) { key._reactInternalInstance = undefined; }, get: function (key) { return key._reactInternalInstance; }, has: function (key) { return key._reactInternalInstance !== undefined; }, set: function (key, value) { key._reactInternalInstance = value; } }; module.exports = ReactInstanceMap; /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactReconciler = __webpack_require__(65); var instantiateReactComponent = __webpack_require__(124); var KeyEscapeUtils = __webpack_require__(134); var shouldUpdateReactComponent = __webpack_require__(130); var traverseAllChildren = __webpack_require__(135); var warning = __webpack_require__(17); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = __webpack_require__(32); } function instantiateChild(childInstances, child, name, selfDebugID) { // We found a component instance. var keyUnique = childInstances[name] === undefined; if (process.env.NODE_ENV !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = __webpack_require__(32); } if (!keyUnique) { process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0; } } if (child != null && keyUnique) { childInstances[name] = instantiateReactComponent(child, true); } } /** * ReactChildReconciler provides helpers for initializing or updating a set of * children. Its output is suitable for passing it onto ReactMultiChild which * does diffed reordering and insertion. */ var ReactChildReconciler = { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildNodes Nested child maps. * @return {?object} A set of child instances. * @internal */ instantiateChildren: function (nestedChildNodes, transaction, context, selfDebugID // 0 in production and for roots ) { if (nestedChildNodes == null) { return null; } var childInstances = {}; if (process.env.NODE_ENV !== 'production') { traverseAllChildren(nestedChildNodes, function (childInsts, child, name) { return instantiateChild(childInsts, child, name, selfDebugID); }, childInstances); } else { traverseAllChildren(nestedChildNodes, instantiateChild, childInstances); } return childInstances; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextChildren Flat child element maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function (prevChildren, nextChildren, mountImages, removedNodes, transaction, hostParent, hostContainerInfo, context, selfDebugID // 0 in production and for roots ) { // We currently don't have a way to track moves here but if we use iterators // instead of for..in we can zip the iterators and check if an item has // moved. // TODO: If nothing has changed, return the prevChildren object so that we // can quickly bailout if nothing has changed. if (!nextChildren && !prevChildren) { return; } var name; var prevChild; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) { ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context); nextChildren[name] = prevChild; } else { if (prevChild) { removedNodes[name] = ReactReconciler.getHostNode(prevChild); ReactReconciler.unmountComponent(prevChild, false); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent(nextElement, true); nextChildren[name] = nextChildInstance; // Creating mount image now ensures refs are resolved in right order // (see https://github.com/facebook/react/pull/7101 for explanation). var nextChildMountImage = ReactReconciler.mountComponent(nextChildInstance, transaction, hostParent, hostContainerInfo, context, selfDebugID); mountImages.push(nextChildMountImage); } } // Unmount children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { prevChild = prevChildren[name]; removedNodes[name] = ReactReconciler.getHostNode(prevChild); ReactReconciler.unmountComponent(prevChild, false); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function (renderedChildren, safely) { for (var name in renderedChildren) { if (renderedChildren.hasOwnProperty(name)) { var renderedChild = renderedChildren[name]; ReactReconciler.unmountComponent(renderedChild, safely); } } } }; module.exports = ReactChildReconciler; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41), _assign = __webpack_require__(10); var ReactCompositeComponent = __webpack_require__(125); var ReactEmptyComponent = __webpack_require__(131); var ReactHostComponent = __webpack_require__(132); var getNextDebugID = __webpack_require__(133); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function (element) { this.construct(element); }; _assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent, { _instantiateReactComponent: instantiateReactComponent }); function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; } /** * Given a ReactNode, create an instance that will actually be mounted. * * @param {ReactNode} node * @param {boolean} shouldHaveDebugID * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(node, shouldHaveDebugID) { var instance; if (node === null || node === false) { instance = ReactEmptyComponent.create(instantiateReactComponent); } else if (typeof node === 'object') { var element = node; var type = element.type; if (typeof type !== 'function' && typeof type !== 'string') { var info = ''; if (process.env.NODE_ENV !== 'production') { if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + 'it\'s defined in.'; } } info += getDeclarationErrorAddendum(element._owner); true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', type == null ? type : typeof type, info) : _prodInvariant('130', type == null ? type : typeof type, info) : void 0; } // Special case string values if (typeof element.type === 'string') { instance = ReactHostComponent.createInternalComponent(element); } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // representations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); // We renamed this. Allow the old name for compat. :( if (!instance.getHostNode) { instance.getHostNode = instance.getNativeNode; } } else { instance = new ReactCompositeComponentWrapper(element); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactHostComponent.createInstanceForText(node); } else { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : _prodInvariant('131', typeof node) : void 0; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.getHostNode === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : void 0; } // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; if (process.env.NODE_ENV !== 'production') { instance._debugID = shouldHaveDebugID ? getNextDebugID() : 0; } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if (process.env.NODE_ENV !== 'production') { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; } module.exports = instantiateReactComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41), _assign = __webpack_require__(10); var React = __webpack_require__(8); var ReactComponentEnvironment = __webpack_require__(121); var ReactCurrentOwner = __webpack_require__(16); var ReactErrorUtils = __webpack_require__(51); var ReactInstanceMap = __webpack_require__(122); var ReactInstrumentation = __webpack_require__(68); var ReactNodeTypes = __webpack_require__(126); var ReactReconciler = __webpack_require__(65); if (process.env.NODE_ENV !== 'production') { var checkReactTypeSpec = __webpack_require__(127); } var emptyObject = __webpack_require__(26); var invariant = __webpack_require__(14); var shallowEqual = __webpack_require__(129); var shouldUpdateReactComponent = __webpack_require__(130); var warning = __webpack_require__(17); var CompositeTypes = { ImpureClass: 0, PureClass: 1, StatelessFunctional: 2 }; function StatelessComponent(Component) {} StatelessComponent.prototype.render = function () { var Component = ReactInstanceMap.get(this)._currentElement.type; var element = Component(this.props, this.context, this.updater); warnIfInvalidElement(Component, element); return element; }; function warnIfInvalidElement(Component, element) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(element === null || element === false || React.isValidElement(element), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!Component.childContextTypes, '%s(...): childContextTypes cannot be defined on a functional component.', Component.displayName || Component.name || 'Component') : void 0; } } function shouldConstruct(Component) { return !!(Component.prototype && Component.prototype.isReactComponent); } function isPureComponent(Component) { return !!(Component.prototype && Component.prototype.isPureReactComponent); } // Separated into a function to contain deoptimizations caused by try/finally. function measureLifeCyclePerf(fn, debugID, timerType) { if (debugID === 0) { // Top-level wrappers (see ReactMount) and empty components (see // ReactDOMEmptyComponent) are invisible to hooks and devtools. // Both are implementation details that should go away in the future. return fn(); } ReactInstrumentation.debugTool.onBeginLifeCycleTimer(debugID, timerType); try { return fn(); } finally { ReactInstrumentation.debugTool.onEndLifeCycleTimer(debugID, timerType); } } /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponent = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function (element) { this._currentElement = element; this._rootNodeID = 0; this._compositeType = null; this._instance = null; this._hostParent = null; this._hostContainerInfo = null; // See ReactUpdateQueue this._updateBatchNumber = null; this._pendingElement = null; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._renderedNodeType = null; this._renderedComponent = null; this._context = null; this._mountOrder = 0; this._topLevelWrapper = null; // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null; // ComponentWillUnmount shall only be called once this._calledComponentWillUnmount = false; if (process.env.NODE_ENV !== 'production') { this._warnedAboutRefsInRender = false; } }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} hostParent * @param {?object} hostContainerInfo * @param {?object} context * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { var _this = this; this._context = context; this._mountOrder = nextMountID++; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var publicProps = this._currentElement.props; var publicContext = this._processContext(context); var Component = this._currentElement.type; var updateQueue = transaction.getUpdateQueue(); // Initialize the public class var doConstruct = shouldConstruct(Component); var inst = this._constructComponent(doConstruct, publicProps, publicContext, updateQueue); var renderedElement; // Support functional components if (!doConstruct && (inst == null || inst.render == null)) { renderedElement = inst; warnIfInvalidElement(Component, renderedElement); !(inst === null || inst === false || React.isValidElement(inst)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : _prodInvariant('105', Component.displayName || Component.name || 'Component') : void 0; inst = new StatelessComponent(Component); this._compositeType = CompositeTypes.StatelessFunctional; } else { if (isPureComponent(Component)) { this._compositeType = CompositeTypes.PureClass; } else { this._compositeType = CompositeTypes.ImpureClass; } } if (process.env.NODE_ENV !== 'production') { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging if (inst.render == null) { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', Component.displayName || Component.name || 'Component') : void 0; } var propsMutated = inst.props !== publicProps; var componentName = Component.displayName || Component.name || 'Component'; process.env.NODE_ENV !== 'production' ? warning(inst.props === undefined || !propsMutated, '%s(...): When calling super() in `%s`, make sure to pass ' + 'up the same props that your component\'s constructor was passed.', componentName, componentName) : void 0; } // These should be set up in the constructor, but as a convenience for // simpler class abstractions, we set them up after the fact. inst.props = publicProps; inst.context = publicContext; inst.refs = emptyObject; inst.updater = updateQueue; this._instance = inst; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); if (process.env.NODE_ENV !== 'production') { // Since plain JS classes are defined without any special initialization // logic, we can not catch common errors early. Therefore, we have to // catch them here, at initialization time, instead. process.env.NODE_ENV !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved || inst.state, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : void 0; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : void 0; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : void 0; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : void 0; } var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : _prodInvariant('106', this.getName() || 'ReactCompositeComponent') : void 0; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; var markup; if (inst.unstable_handleError) { markup = this.performInitialMountWithErrorHandling(renderedElement, hostParent, hostContainerInfo, transaction, context); } else { markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } if (inst.componentDidMount) { if (process.env.NODE_ENV !== 'production') { transaction.getReactMountReady().enqueue(function () { measureLifeCyclePerf(function () { return inst.componentDidMount(); }, _this._debugID, 'componentDidMount'); }); } else { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } } return markup; }, _constructComponent: function (doConstruct, publicProps, publicContext, updateQueue) { if (process.env.NODE_ENV !== 'production') { ReactCurrentOwner.current = this; try { return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); } finally { ReactCurrentOwner.current = null; } } else { return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); } }, _constructComponentWithoutOwner: function (doConstruct, publicProps, publicContext, updateQueue) { var Component = this._currentElement.type; if (doConstruct) { if (process.env.NODE_ENV !== 'production') { return measureLifeCyclePerf(function () { return new Component(publicProps, publicContext, updateQueue); }, this._debugID, 'ctor'); } else { return new Component(publicProps, publicContext, updateQueue); } } // This can still be an instance in case of factory components // but we'll count this as time spent rendering as the more common case. if (process.env.NODE_ENV !== 'production') { return measureLifeCyclePerf(function () { return Component(publicProps, publicContext, updateQueue); }, this._debugID, 'render'); } else { return Component(publicProps, publicContext, updateQueue); } }, performInitialMountWithErrorHandling: function (renderedElement, hostParent, hostContainerInfo, transaction, context) { var markup; var checkpoint = transaction.checkpoint(); try { markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } catch (e) { // Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint transaction.rollback(checkpoint); this._instance.unstable_handleError(e); if (this._pendingStateQueue) { this._instance.state = this._processPendingState(this._instance.props, this._instance.context); } checkpoint = transaction.checkpoint(); this._renderedComponent.unmountComponent(true); transaction.rollback(checkpoint); // Try again - we've informed the component about the error, so they can render an error message this time. // If this throws again, the error will bubble up (and can be caught by a higher error boundary). markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } return markup; }, performInitialMount: function (renderedElement, hostParent, hostContainerInfo, transaction, context) { var inst = this._instance; var debugID = 0; if (process.env.NODE_ENV !== 'production') { debugID = this._debugID; } if (inst.componentWillMount) { if (process.env.NODE_ENV !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillMount(); }, debugID, 'componentWillMount'); } else { inst.componentWillMount(); } // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingStateQueue` without triggering a re-render. if (this._pendingStateQueue) { inst.state = this._processPendingState(inst.props, inst.context); } } // If not a stateless component, we now render if (renderedElement === undefined) { renderedElement = this._renderValidatedComponent(); } var nodeType = ReactNodeTypes.getType(renderedElement); this._renderedNodeType = nodeType; var child = this._instantiateReactComponent(renderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */ ); this._renderedComponent = child; var markup = ReactReconciler.mountComponent(child, transaction, hostParent, hostContainerInfo, this._processChildContext(context), debugID); if (process.env.NODE_ENV !== 'production') { if (debugID !== 0) { var childDebugIDs = child._debugID !== 0 ? [child._debugID] : []; ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs); } } return markup; }, getHostNode: function () { return ReactReconciler.getHostNode(this._renderedComponent); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (safely) { if (!this._renderedComponent) { return; } var inst = this._instance; if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) { inst._calledComponentWillUnmount = true; if (safely) { var name = this.getName() + '.componentWillUnmount()'; ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst)); } else { if (process.env.NODE_ENV !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillUnmount(); }, this._debugID, 'componentWillUnmount'); } else { inst.componentWillUnmount(); } } } if (this._renderedComponent) { ReactReconciler.unmountComponent(this._renderedComponent, safely); this._renderedNodeType = null; this._renderedComponent = null; this._instance = null; } // Reset pending fields // Even if this component is scheduled for another update in ReactUpdates, // it would still be ignored because these fields are reset. this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._pendingCallbacks = null; this._pendingElement = null; // These fields do not really need to be reset since this object is no // longer accessible. this._context = null; this._rootNodeID = 0; this._topLevelWrapper = null; // Delete the reference from the instance to this internal representation // which allow the internals to be properly cleaned up even if the user // leaks a reference to the public instance. ReactInstanceMap.remove(inst); // Some existing components rely on inst.props even after they've been // destroyed (in event handlers). // TODO: inst.props = null; // TODO: inst.state = null; // TODO: inst.context = null; }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function (context) { var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject; } var maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function (context) { var maskedContext = this._maskContext(context); if (process.env.NODE_ENV !== 'production') { var Component = this._currentElement.type; if (Component.contextTypes) { this._checkContextTypes(Component.contextTypes, maskedContext, 'context'); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function (currentContext) { var Component = this._currentElement.type; var inst = this._instance; var childContext; if (inst.getChildContext) { if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onBeginProcessingChildContext(); try { childContext = inst.getChildContext(); } finally { ReactInstrumentation.debugTool.onEndProcessingChildContext(); } } else { childContext = inst.getChildContext(); } } if (childContext) { !(typeof Component.childContextTypes === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().', this.getName() || 'ReactCompositeComponent') : _prodInvariant('107', this.getName() || 'ReactCompositeComponent') : void 0; if (process.env.NODE_ENV !== 'production') { this._checkContextTypes(Component.childContextTypes, childContext, 'childContext'); } for (var name in childContext) { !(name in Component.childContextTypes) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : _prodInvariant('108', this.getName() || 'ReactCompositeComponent', name) : void 0; } return _assign({}, currentContext, childContext); } return currentContext; }, /** * Assert that the context types are valid * * @param {object} typeSpecs Map of context field to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkContextTypes: function (typeSpecs, values, location) { if (process.env.NODE_ENV !== 'production') { checkReactTypeSpec(typeSpecs, values, location, this.getName(), null, this._debugID); } }, receiveComponent: function (nextElement, transaction, nextContext) { var prevElement = this._currentElement; var prevContext = this._context; this._pendingElement = null; this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context); } else if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } else { this._updateBatchNumber = null; } }, /** * Perform an update to a mounted component. The componentWillReceiveProps and * shouldComponentUpdate methods are called, then (assuming the update isn't * skipped) the remaining update lifecycle methods are called and the DOM * representation is updated. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevParentElement * @param {ReactElement} nextParentElement * @internal * @overridable */ updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { var inst = this._instance; !(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Attempted to update component `%s` that has already been unmounted (or failed to mount).', this.getName() || 'ReactCompositeComponent') : _prodInvariant('136', this.getName() || 'ReactCompositeComponent') : void 0; var willReceive = false; var nextContext; // Determine if the context has changed or not if (this._context === nextUnmaskedContext) { nextContext = inst.context; } else { nextContext = this._processContext(nextUnmaskedContext); willReceive = true; } var prevProps = prevParentElement.props; var nextProps = nextParentElement.props; // Not a simple state update but a props update if (prevParentElement !== nextParentElement) { willReceive = true; } // An update here will schedule an update but immediately set // _pendingStateQueue which will ensure that any state updates gets // immediately reconciled instead of waiting for the next batch. if (willReceive && inst.componentWillReceiveProps) { if (process.env.NODE_ENV !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillReceiveProps(nextProps, nextContext); }, this._debugID, 'componentWillReceiveProps'); } else { inst.componentWillReceiveProps(nextProps, nextContext); } } var nextState = this._processPendingState(nextProps, nextContext); var shouldUpdate = true; if (!this._pendingForceUpdate) { if (inst.shouldComponentUpdate) { if (process.env.NODE_ENV !== 'production') { shouldUpdate = measureLifeCyclePerf(function () { return inst.shouldComponentUpdate(nextProps, nextState, nextContext); }, this._debugID, 'shouldComponentUpdate'); } else { shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext); } } else { if (this._compositeType === CompositeTypes.PureClass) { shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState); } } } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(shouldUpdate !== undefined, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : void 0; } this._updateBatchNumber = null; if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext); } else { // If it's determined that a component should not update, we still want // to set props and state but we shortcut the rest of the update. this._currentElement = nextParentElement; this._context = nextUnmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; } }, _processPendingState: function (props, context) { var inst = this._instance; var queue = this._pendingStateQueue; var replace = this._pendingReplaceState; this._pendingReplaceState = false; this._pendingStateQueue = null; if (!queue) { return inst.state; } if (replace && queue.length === 1) { return queue[0]; } var nextState = _assign({}, replace ? queue[0] : inst.state); for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; _assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial); } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { var _this2 = this; var inst = this._instance; var hasComponentDidUpdate = Boolean(inst.componentDidUpdate); var prevProps; var prevState; var prevContext; if (hasComponentDidUpdate) { prevProps = inst.props; prevState = inst.state; prevContext = inst.context; } if (inst.componentWillUpdate) { if (process.env.NODE_ENV !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillUpdate(nextProps, nextState, nextContext); }, this._debugID, 'componentWillUpdate'); } else { inst.componentWillUpdate(nextProps, nextState, nextContext); } } this._currentElement = nextElement; this._context = unmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; this._updateRenderedComponent(transaction, unmaskedContext); if (hasComponentDidUpdate) { if (process.env.NODE_ENV !== 'production') { transaction.getReactMountReady().enqueue(function () { measureLifeCyclePerf(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), _this2._debugID, 'componentDidUpdate'); }); } else { transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst); } } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function (transaction, context) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; var nextRenderedElement = this._renderValidatedComponent(); var debugID = 0; if (process.env.NODE_ENV !== 'production') { debugID = this._debugID; } if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); } else { var oldHostNode = ReactReconciler.getHostNode(prevComponentInstance); ReactReconciler.unmountComponent(prevComponentInstance, false); var nodeType = ReactNodeTypes.getType(nextRenderedElement); this._renderedNodeType = nodeType; var child = this._instantiateReactComponent(nextRenderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */ ); this._renderedComponent = child; var nextMarkup = ReactReconciler.mountComponent(child, transaction, this._hostParent, this._hostContainerInfo, this._processChildContext(context), debugID); if (process.env.NODE_ENV !== 'production') { if (debugID !== 0) { var childDebugIDs = child._debugID !== 0 ? [child._debugID] : []; ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs); } } this._replaceNodeWithMarkup(oldHostNode, nextMarkup, prevComponentInstance); } }, /** * Overridden in shallow rendering. * * @protected */ _replaceNodeWithMarkup: function (oldHostNode, nextMarkup, prevInstance) { ReactComponentEnvironment.replaceNodeWithMarkup(oldHostNode, nextMarkup, prevInstance); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function () { var inst = this._instance; var renderedElement; if (process.env.NODE_ENV !== 'production') { renderedElement = measureLifeCyclePerf(function () { return inst.render(); }, this._debugID, 'render'); } else { renderedElement = inst.render(); } if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (renderedElement === undefined && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedElement = null; } } return renderedElement; }, /** * @private */ _renderValidatedComponent: function () { var renderedElement; if (process.env.NODE_ENV !== 'production' || this._compositeType !== CompositeTypes.StatelessFunctional) { ReactCurrentOwner.current = this; try { renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactCurrentOwner.current = null; } } else { renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); } !( // TODO: An `isValidNode` function would probably be more appropriate renderedElement === null || renderedElement === false || React.isValidElement(renderedElement)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : _prodInvariant('109', this.getName() || 'ReactCompositeComponent') : void 0; return renderedElement; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function (ref, component) { var inst = this.getPublicInstance(); !(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : _prodInvariant('110') : void 0; var publicComponentInstance = component.getPublicInstance(); if (process.env.NODE_ENV !== 'production') { var componentName = component && component.getName ? component.getName() : 'a component'; process.env.NODE_ENV !== 'production' ? warning(publicComponentInstance != null || component._compositeType !== CompositeTypes.StatelessFunctional, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : void 0; } var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; refs[ref] = publicComponentInstance; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function (ref) { var refs = this.getPublicInstance().refs; delete refs[ref]; }, /** * Get a text description of the component that can be used to identify it * in error messages. * @return {string} The name or null. * @internal */ getName: function () { var type = this._currentElement.type; var constructor = this._instance && this._instance.constructor; return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; }, /** * Get the publicly accessible representation of this component - i.e. what * is exposed by refs and returned by render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function () { var inst = this._instance; if (this._compositeType === CompositeTypes.StatelessFunctional) { return null; } return inst; }, // Stub _instantiateReactComponent: null }; module.exports = ReactCompositeComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var React = __webpack_require__(8); var invariant = __webpack_require__(14); var ReactNodeTypes = { HOST: 0, COMPOSITE: 1, EMPTY: 2, getType: function (node) { if (node === null || node === false) { return ReactNodeTypes.EMPTY; } else if (React.isValidElement(node)) { if (typeof node.type === 'function') { return ReactNodeTypes.COMPOSITE; } else { return ReactNodeTypes.HOST; } } true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unexpected node: %s', node) : _prodInvariant('26', node) : void 0; } }; module.exports = ReactNodeTypes; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var ReactPropTypeLocationNames = __webpack_require__(128); var ReactPropTypesSecret = __webpack_require__(116); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = __webpack_require__(32); } var loggedTypeFailures = {}; /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?object} element The React element that is being type-checked * @param {?number} debugID The React component instance that is being type-checked * @private */ function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof typeSpecs[typeSpecName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0; error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var componentStackInfo = ''; if (process.env.NODE_ENV !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = __webpack_require__(32); } if (debugID !== null) { componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID); } else if (element !== null) { componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element); } } process.env.NODE_ENV !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0; } } } } module.exports = checkReactTypeSpec; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypeLocationNames = {}; if (process.env.NODE_ENV !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 129 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * */ /*eslint-disable no-self-compare */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 // Added the nonzero y check to make Flow happy, but it is redundant return x !== 0 || y !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (is(objA, objB)) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } module.exports = shallowEqual; /***/ }, /* 130 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; if (prevEmpty || nextEmpty) { return prevEmpty === nextEmpty; } var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return nextType === 'string' || nextType === 'number'; } else { return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; } } module.exports = shouldUpdateReactComponent; /***/ }, /* 131 */ /***/ function(module, exports) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyComponentFactory; var ReactEmptyComponentInjection = { injectEmptyComponentFactory: function (factory) { emptyComponentFactory = factory; } }; var ReactEmptyComponent = { create: function (instantiate) { return emptyComponentFactory(instantiate); } }; ReactEmptyComponent.injection = ReactEmptyComponentInjection; module.exports = ReactEmptyComponent; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); var genericComponentClass = null; var textComponentClass = null; var ReactHostComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function (componentClass) { genericComponentClass = componentClass; }, // This accepts a text component class that takes the text string to be // rendered as props. injectTextComponentClass: function (componentClass) { textComponentClass = componentClass; } }; /** * Get a host internal component class for a specific tag. * * @param {ReactElement} element The element to create. * @return {function} The internal class constructor function. */ function createInternalComponent(element) { !genericComponentClass ? process.env.NODE_ENV !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : _prodInvariant('111', element.type) : void 0; return new genericComponentClass(element); } /** * @param {ReactText} text * @return {ReactComponent} */ function createInstanceForText(text) { return new textComponentClass(text); } /** * @param {ReactComponent} component * @return {boolean} */ function isTextComponent(component) { return component instanceof textComponentClass; } var ReactHostComponent = { createInternalComponent: createInternalComponent, createInstanceForText: createInstanceForText, isTextComponent: isTextComponent, injection: ReactHostComponentInjection }; module.exports = ReactHostComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 133 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var nextDebugID = 1; function getNextDebugID() { return nextDebugID++; } module.exports = getNextDebugID; /***/ }, /* 134 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; module.exports = KeyEscapeUtils; /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var ReactCurrentOwner = __webpack_require__(16); var REACT_ELEMENT_TYPE = __webpack_require__(136); var getIteratorFn = __webpack_require__(137); var invariant = __webpack_require__(14); var KeyEscapeUtils = __webpack_require__(134); var warning = __webpack_require__(17); var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * This is inlined from ReactElement since this file is shared between * isomorphic and renderers. We could extract this to a * */ /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || // The following is inlined from ReactElement. This means we can optimize // some checks. React Fiber also inlines this logic for similar purposes. type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if (process.env.NODE_ENV !== 'production') { var mapsAsChildrenAddendum = ''; if (ReactCurrentOwner.current) { var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName(); if (mapsAsChildrenOwnerName) { mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.'; } } process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if (process.env.NODE_ENV !== 'production') { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 136 */ /***/ function(module, exports) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; module.exports = REACT_ELEMENT_TYPE; /***/ }, /* 137 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var KeyEscapeUtils = __webpack_require__(134); var traverseAllChildren = __webpack_require__(135); var warning = __webpack_require__(17); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = __webpack_require__(32); } /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. * @param {number=} selfDebugID Optional debugID of the current internal instance. */ function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) { // We found a component instance. if (traverseContext && typeof traverseContext === 'object') { var result = traverseContext; var keyUnique = result[name] === undefined; if (process.env.NODE_ENV !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = __webpack_require__(32); } if (!keyUnique) { process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0; } } if (keyUnique && child != null) { result[name] = child; } } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children, selfDebugID) { if (children == null) { return children; } var result = {}; if (process.env.NODE_ENV !== 'production') { traverseAllChildren(children, function (traverseContext, child, name) { return flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID); }, result); } else { traverseAllChildren(children, flattenSingleChildIntoContext, result); } return result; } module.exports = flattenChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var PooledClass = __webpack_require__(56); var Transaction = __webpack_require__(74); var ReactInstrumentation = __webpack_require__(68); var ReactServerUpdateQueue = __webpack_require__(140); /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = []; if (process.env.NODE_ENV !== 'production') { TRANSACTION_WRAPPERS.push({ initialize: ReactInstrumentation.debugTool.onBeginFlush, close: ReactInstrumentation.debugTool.onEndFlush }); } var noopCallbackQueue = { enqueue: function () {} }; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.useCreateElement = false; this.updateQueue = new ReactServerUpdateQueue(this); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap procedures. */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return noopCallbackQueue; }, /** * @return {object} The queue to collect React async events. */ getUpdateQueue: function () { return this.updateQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () {}, checkpoint: function () {}, rollback: function () {} }; _assign(ReactServerRenderingTransaction.prototype, Transaction, Mixin); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ReactUpdateQueue = __webpack_require__(141); var warning = __webpack_require__(17); function warnNoop(publicInstance, callerName) { if (process.env.NODE_ENV !== 'production') { var constructor = publicInstance.constructor; process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0; } } /** * This is the update queue used for server rendering. * It delegates to ReactUpdateQueue while server rendering is in progress and * switches to ReactNoopUpdateQueue after the transaction has completed. * @class ReactServerUpdateQueue * @param {Transaction} transaction */ var ReactServerUpdateQueue = function () { function ReactServerUpdateQueue(transaction) { _classCallCheck(this, ReactServerUpdateQueue); this.transaction = transaction; } /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ ReactServerUpdateQueue.prototype.isMounted = function isMounted(publicInstance) { return false; }; /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ ReactServerUpdateQueue.prototype.enqueueCallback = function enqueueCallback(publicInstance, callback, callerName) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueCallback(publicInstance, callback, callerName); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ ReactServerUpdateQueue.prototype.enqueueForceUpdate = function enqueueForceUpdate(publicInstance) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueForceUpdate(publicInstance); } else { warnNoop(publicInstance, 'forceUpdate'); } }; /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object|function} completeState Next state. * @internal */ ReactServerUpdateQueue.prototype.enqueueReplaceState = function enqueueReplaceState(publicInstance, completeState) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueReplaceState(publicInstance, completeState); } else { warnNoop(publicInstance, 'replaceState'); } }; /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object|function} partialState Next partial state to be merged with state. * @internal */ ReactServerUpdateQueue.prototype.enqueueSetState = function enqueueSetState(publicInstance, partialState) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueSetState(publicInstance, partialState); } else { warnNoop(publicInstance, 'setState'); } }; return ReactServerUpdateQueue; }(); module.exports = ReactServerUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var ReactCurrentOwner = __webpack_require__(16); var ReactInstanceMap = __webpack_require__(122); var ReactInstrumentation = __webpack_require__(68); var ReactUpdates = __webpack_require__(62); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); function enqueueUpdate(internalInstance) { ReactUpdates.enqueueUpdate(internalInstance); } function formatUnexpectedArgument(arg) { var type = typeof arg; if (type !== 'object') { return type; } var displayName = arg.constructor && arg.constructor.name || type; var keys = Object.keys(arg); if (keys.length > 0 && keys.length < 20) { return displayName + ' (keys: ' + keys.join(', ') + ')'; } return displayName; } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { var internalInstance = ReactInstanceMap.get(publicInstance); if (!internalInstance) { if (process.env.NODE_ENV !== 'production') { var ctor = publicInstance.constructor; // Only warn when we have a callerName. Otherwise we should be silent. // We're probably calling from enqueueCallback. We don't want to warn // there because we already warned for the corresponding lifecycle method. process.env.NODE_ENV !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, ctor && (ctor.displayName || ctor.name) || 'ReactClass') : void 0; } return null; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition (such as ' + 'within `render` or another component\'s constructor). Render methods ' + 'should be a pure function of props and state; constructor ' + 'side-effects are an anti-pattern, but can be moved to ' + '`componentWillMount`.', callerName) : void 0; } return internalInstance; } /** * ReactUpdateQueue allows for state updates to be scheduled into a later * reconciliation step. */ var ReactUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } var internalInstance = ReactInstanceMap.get(publicInstance); if (internalInstance) { // During componentWillMount and render this will still be null but after // that will always render to something. At least for now. So we can use // this hack. return !!internalInstance._renderedComponent; } else { return false; } }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @param {string} callerName Name of the calling function in the public API. * @internal */ enqueueCallback: function (publicInstance, callback, callerName) { ReactUpdateQueue.validateCallback(callback, callerName); var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); // Previously we would throw an error if we didn't have an internal // instance. Since we want to make it a no-op instead, we mirror the same // behavior we have in other enqueue* methods. // We also need to ignore callbacks in componentWillMount. See // enqueueUpdates. if (!internalInstance) { return null; } if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. Alternatively, we can disallow // componentWillMount during server-side rendering. enqueueUpdate(internalInstance); }, enqueueCallbackInternal: function (internalInstance, callback) { if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } enqueueUpdate(internalInstance); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate'); if (!internalInstance) { return; } internalInstance._pendingForceUpdate = true; enqueueUpdate(internalInstance); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; enqueueUpdate(internalInstance); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onSetState(); process.env.NODE_ENV !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : void 0; } var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState'); if (!internalInstance) { return; } var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState); enqueueUpdate(internalInstance); }, enqueueElementInternal: function (internalInstance, nextElement, nextContext) { internalInstance._pendingElement = nextElement; // TODO: introduce _pendingContext instead of setting it directly. internalInstance._context = nextContext; enqueueUpdate(internalInstance); }, validateCallback: function (callback, callerName) { !(!callback || typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.', callerName, formatUnexpectedArgument(callback)) : _prodInvariant('122', callerName, formatUnexpectedArgument(callback)) : void 0; } }; module.exports = ReactUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 142 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var emptyFunction = __webpack_require__(18); var warning = __webpack_require__(17); var validateDOMNesting = emptyFunction; if (process.env.NODE_ENV !== 'production') { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; var emptyAncestorInfo = { current: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }; var updatedAncestorInfo = function (oldInfo, tag, instance) { var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo); var info = { tag: tag, instance: instance }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.current = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body'; case '#document': return tag === 'html'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'body': case 'caption': case 'col': case 'colgroup': case 'frame': case 'head': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ var findInvalidAncestorForTag = function (tag, ancestorInfo) { switch (tag) { case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dialog': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'main': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': case 'pre': case 'listing': case 'table': case 'hr': case 'xmp': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; /** * Given a ReactCompositeComponent instance, return a list of its recursive * owners, starting at the root and ending with the instance itself. */ var findOwnerStack = function (instance) { if (!instance) { return []; } var stack = []; do { stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }; var didWarn = {}; validateDOMNesting = function (childTag, childText, childInstance, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; if (childText != null) { process.env.NODE_ENV !== 'production' ? warning(childTag == null, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0; childTag = '#text'; } var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var problematic = invalidParent || invalidAncestor; if (problematic) { var ancestorTag = problematic.tag; var ancestorInstance = problematic.instance; var childOwner = childInstance && childInstance._currentElement._owner; var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner; var childOwners = findOwnerStack(childOwner); var ancestorOwners = findOwnerStack(ancestorOwner); var minStackLen = Math.min(childOwners.length, ancestorOwners.length); var i; var deepestCommon = -1; for (i = 0; i < minStackLen; i++) { if (childOwners[i] === ancestorOwners[i]) { deepestCommon = i; } else { break; } } var UNKNOWN = '(unknown)'; var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ownerInfo = [].concat( // If the parent and child instances have a common owner ancestor, start // with that -- otherwise we just start with the parent's owners. deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag, // If we're warning about an invalid (non-parent) ancestry, add '...' invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > '); var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; var tagDisplayName = childTag; var whitespaceInfo = ''; if (childTag === '#text') { if (/\S/.test(childText)) { tagDisplayName = 'Text nodes'; } else { tagDisplayName = 'Whitespace text nodes'; whitespaceInfo = ' Make sure you don\'t have any extra whitespace between tags on ' + 'each line of your source code.'; } } else { tagDisplayName = '<' + childTag + '>'; } if (invalidParent) { var info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.'; } process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s ' + 'See %s.%s', tagDisplayName, ancestorTag, whitespaceInfo, ownerInfo, info) : void 0; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>. See %s.', tagDisplayName, ancestorTag, ownerInfo) : void 0; } } }; validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; // For testing validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); }; } module.exports = validateDOMNesting; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var DOMLazyTree = __webpack_require__(87); var ReactDOMComponentTree = __webpack_require__(40); var ReactDOMEmptyComponent = function (instantiate) { // ReactCompositeComponent uses this: this._currentElement = null; // ReactDOMComponentTree uses these: this._hostNode = null; this._hostParent = null; this._hostContainerInfo = null; this._domID = 0; }; _assign(ReactDOMEmptyComponent.prototype, { mountComponent: function (transaction, hostParent, hostContainerInfo, context) { var domID = hostContainerInfo._idCounter++; this._domID = domID; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var nodeValue = ' react-empty: ' + this._domID + ' '; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var node = ownerDocument.createComment(nodeValue); ReactDOMComponentTree.precacheNode(this, node); return DOMLazyTree(node); } else { if (transaction.renderToStaticMarkup) { // Normally we'd insert a comment node, but since this is a situation // where React won't take over (static pages), we can simply return // nothing. return ''; } return '<!--' + nodeValue + '-->'; } }, receiveComponent: function () {}, getHostNode: function () { return ReactDOMComponentTree.getNodeFromInstance(this); }, unmountComponent: function () { ReactDOMComponentTree.uncacheNode(this); } }); module.exports = ReactDOMEmptyComponent; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA, instB) { !('_hostNode' in instA) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; !('_hostNode' in instB) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; var depthA = 0; for (var tempA = instA; tempA; tempA = tempA._hostParent) { depthA++; } var depthB = 0; for (var tempB = instB; tempB; tempB = tempB._hostParent) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = instA._hostParent; depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = instB._hostParent; depthB--; } // Walk in lockstep until we find a match. var depth = depthA; while (depth--) { if (instA === instB) { return instA; } instA = instA._hostParent; instB = instB._hostParent; } return null; } /** * Return if A is an ancestor of B. */ function isAncestor(instA, instB) { !('_hostNode' in instA) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0; !('_hostNode' in instB) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0; while (instB) { if (instB === instA) { return true; } instB = instB._hostParent; } return false; } /** * Return the parent instance of the passed-in instance. */ function getParentInstance(inst) { !('_hostNode' in inst) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : _prodInvariant('36') : void 0; return inst._hostParent; } /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ function traverseTwoPhase(inst, fn, arg) { var path = []; while (inst) { path.push(inst); inst = inst._hostParent; } var i; for (i = path.length; i-- > 0;) { fn(path[i], 'captured', arg); } for (i = 0; i < path.length; i++) { fn(path[i], 'bubbled', arg); } } /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * Does not invoke the callback on the nearest common ancestor because nothing * "entered" or "left" that element. */ function traverseEnterLeave(from, to, fn, argFrom, argTo) { var common = from && to ? getLowestCommonAncestor(from, to) : null; var pathFrom = []; while (from && from !== common) { pathFrom.push(from); from = from._hostParent; } var pathTo = []; while (to && to !== common) { pathTo.push(to); to = to._hostParent; } var i; for (i = 0; i < pathFrom.length; i++) { fn(pathFrom[i], 'bubbled', argFrom); } for (i = pathTo.length; i-- > 0;) { fn(pathTo[i], 'captured', argTo); } } module.exports = { isAncestor: isAncestor, getLowestCommonAncestor: getLowestCommonAncestor, getParentInstance: getParentInstance, traverseTwoPhase: traverseTwoPhase, traverseEnterLeave: traverseEnterLeave }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41), _assign = __webpack_require__(10); var DOMChildrenOperations = __webpack_require__(86); var DOMLazyTree = __webpack_require__(87); var ReactDOMComponentTree = __webpack_require__(40); var escapeTextContentForBrowser = __webpack_require__(92); var invariant = __webpack_require__(14); var validateDOMNesting = __webpack_require__(142); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings between comment nodes so that they * can undergo the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactDOMTextComponent * @extends ReactComponent * @internal */ var ReactDOMTextComponent = function (text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text; this._stringText = '' + text; // ReactDOMComponentTree uses these: this._hostNode = null; this._hostParent = null; // Properties this._domID = 0; this._mountIndex = 0; this._closingComment = null; this._commentNodes = null; }; _assign(ReactDOMTextComponent.prototype, { /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { if (process.env.NODE_ENV !== 'production') { var parentInfo; if (hostParent != null) { parentInfo = hostParent._ancestorInfo; } else if (hostContainerInfo != null) { parentInfo = hostContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting(null, this._stringText, this, parentInfo); } } var domID = hostContainerInfo._idCounter++; var openingValue = ' react-text: ' + domID + ' '; var closingValue = ' /react-text '; this._domID = domID; this._hostParent = hostParent; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var openingComment = ownerDocument.createComment(openingValue); var closingComment = ownerDocument.createComment(closingValue); var lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment()); DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment)); if (this._stringText) { DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText))); } DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment)); ReactDOMComponentTree.precacheNode(this, openingComment); this._closingComment = closingComment; return lazyTree; } else { var escapedText = escapeTextContentForBrowser(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this between comment nodes for the reasons stated // above, but since this is a situation where React won't take over // (static pages), we can simply return the text as it is. return escapedText; } return '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->'; } }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function (nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; var commentNodes = this.getHostNode(); DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText); } } }, getHostNode: function () { var hostNode = this._commentNodes; if (hostNode) { return hostNode; } if (!this._closingComment) { var openingComment = ReactDOMComponentTree.getNodeFromInstance(this); var node = openingComment.nextSibling; while (true) { !(node != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing closing comment for text component %s', this._domID) : _prodInvariant('67', this._domID) : void 0; if (node.nodeType === 8 && node.nodeValue === ' /react-text ') { this._closingComment = node; break; } node = node.nextSibling; } } hostNode = [this._hostNode, this._closingComment]; this._commentNodes = hostNode; return hostNode; }, unmountComponent: function () { this._closingComment = null; this._commentNodes = null; ReactDOMComponentTree.uncacheNode(this); } }); module.exports = ReactDOMTextComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var ReactUpdates = __webpack_require__(62); var Transaction = __webpack_require__(74); var emptyFunction = __webpack_require__(18); var RESET_BATCHED_UPDATES = { initialize: emptyFunction, close: function () { ReactDefaultBatchingStrategy.isBatchingUpdates = false; } }; var FLUSH_BATCHED_UPDATES = { initialize: emptyFunction, close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) }; var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } _assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; } }); var transaction = new ReactDefaultBatchingStrategyTransaction(); var ReactDefaultBatchingStrategy = { isBatchingUpdates: false, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function (callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { return callback(a, b, c, d, e); } else { return transaction.perform(callback, null, a, b, c, d, e); } } }; module.exports = ReactDefaultBatchingStrategy; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var EventListener = __webpack_require__(148); var ExecutionEnvironment = __webpack_require__(54); var PooledClass = __webpack_require__(56); var ReactDOMComponentTree = __webpack_require__(40); var ReactUpdates = __webpack_require__(62); var getEventTarget = __webpack_require__(75); var getUnboundedScrollPosition = __webpack_require__(149); /** * Find the deepest React component completely containing the root of the * passed-in instance (for use when entire React trees are nested within each * other). If React trees are not nested, returns null. */ function findParent(inst) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. while (inst._hostParent) { inst = inst._hostParent; } var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst); var container = rootNode.parentNode; return ReactDOMComponentTree.getClosestInstanceFromNode(container); } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.ancestors = []; } _assign(TopLevelCallbackBookKeeping.prototype, { destructor: function () { this.topLevelType = null; this.nativeEvent = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler); function handleTopLevelImpl(bookKeeping) { var nativeEventTarget = getEventTarget(bookKeeping.nativeEvent); var targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(nativeEventTarget); // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = targetInst; do { bookKeeping.ancestors.push(ancestor); ancestor = ancestor && findParent(ancestor); } while (ancestor); for (var i = 0; i < bookKeeping.ancestors.length; i++) { targetInst = bookKeeping.ancestors[i]; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function (handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function (enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function () { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} element Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function (topLevelType, handlerBaseName, element) { if (!element) { return null; } return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} element Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function (topLevelType, handlerBaseName, element) { if (!element) { return null; } return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, monitorScrollValue: function (refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, 'scroll', callback); }, dispatchEvent: function (topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; module.exports = ReactEventListener; /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * * 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. * * @typechecks */ var emptyFunction = __webpack_require__(18); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function listen(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function remove() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function remove() { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function capture(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, true); return { remove: function remove() { target.removeEventListener(eventType, callback, true); } }; } else { if (process.env.NODE_ENV !== 'production') { console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); } return { remove: emptyFunction }; } }, registerDefault: function registerDefault() {} }; module.exports = EventListener; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 149 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(42); var EventPluginHub = __webpack_require__(48); var EventPluginUtils = __webpack_require__(50); var ReactComponentEnvironment = __webpack_require__(121); var ReactEmptyComponent = __webpack_require__(131); var ReactBrowserEventEmitter = __webpack_require__(111); var ReactHostComponent = __webpack_require__(132); var ReactUpdates = __webpack_require__(62); var ReactInjection = { Component: ReactComponentEnvironment.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventPluginUtils: EventPluginUtils.injection, EventEmitter: ReactBrowserEventEmitter.injection, HostComponent: ReactHostComponent.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var CallbackQueue = __webpack_require__(63); var PooledClass = __webpack_require__(56); var ReactBrowserEventEmitter = __webpack_require__(111); var ReactInputSelection = __webpack_require__(152); var ReactInstrumentation = __webpack_require__(68); var Transaction = __webpack_require__(74); var ReactUpdateQueue = __webpack_require__(141); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function () { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); ReactBrowserEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` * restores the previous value. */ close: function (previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function () { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function () { this.reactMountReady.notifyAll(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING]; if (process.env.NODE_ENV !== 'production') { TRANSACTION_WRAPPERS.push({ initialize: ReactInstrumentation.debugTool.onBeginFlush, close: ReactInstrumentation.debugTool.onEndFlush }); } /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction(useCreateElement) { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactDOMTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = useCreateElement; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap procedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * @return {object} The queue to collect React async events. */ getUpdateQueue: function () { return ReactUpdateQueue; }, /** * Save current transaction state -- if the return value from this method is * passed to `rollback`, the transaction will be reset to that state. */ checkpoint: function () { // reactMountReady is the our only stateful wrapper return this.reactMountReady.checkpoint(); }, rollback: function (checkpoint) { this.reactMountReady.rollback(checkpoint); }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; } }; _assign(ReactReconcileTransaction.prototype, Transaction, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMSelection = __webpack_require__(153); var containsNode = __webpack_require__(155); var focusNode = __webpack_require__(100); var getActiveElement = __webpack_require__(158); function isInDocument(node) { return containsNode(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function (elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); }, getSelectionInformation: function () { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function (priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); } focusNode(priorFocusedElem); } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function (input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || { start: 0, end: 0 }; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function (input, offsets) { var start = offsets.start; var end = offsets.end; if (end === undefined) { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection; /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(54); var getNodeForCharacterOffset = __webpack_require__(154); var getTextContentAccessor = __webpack_require__(57); /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * Get the appropriate anchor and focus node/offset pairs for IE. * * The catch here is that IE's selection API doesn't provide information * about whether the selection is forward or backward, so we have to * behave as though it's always forward. * * IE text differs from modern selection in that it behaves as though * block elements end with a new line. This means character offsets will * differ between the two APIs. * * @param {DOMElement} node * @return {object} */ function getIEOffsets(node) { var selection = document.selection; var selectedRange = selection.createRange(); var selectedLength = selectedRange.text.length; // Duplicate selection so we can move range without breaking user selection. var fromStart = selectedRange.duplicate(); fromStart.moveToElementText(node); fromStart.setEndPoint('EndToStart', selectedRange); var startOffset = fromStart.text.length; var endOffset = startOffset + selectedLength; return { start: startOffset, end: endOffset }; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection && window.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode; var anchorOffset = selection.anchorOffset; var focusNode = selection.focusNode; var focusOffset = selection.focusOffset; var currentRange = selection.getRangeAt(0); // In Firefox, range.startContainer and range.endContainer can be "anonymous // divs", e.g. the up/down buttons on an <input type="number">. Anonymous // divs do not seem to expose properties, triggering a "Permission denied // error" if any of its properties are accessed. The only seemingly possible // way to avoid erroring is to access a property that typically works for // non-anonymous divs and catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ currentRange.startContainer.nodeType; currentRange.endContainer.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (offsets.end === undefined) { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programmatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window); var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; /***/ }, /* 154 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var isTextNode = __webpack_require__(156); /*eslint-disable no-bitwise */ /** * Checks if a given DOM node contains or is another DOM node. */ function containsNode(outerNode, innerNode) { if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { return containsNode(outerNode, innerNode.parentNode); } else if ('contains' in outerNode) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } module.exports = containsNode; /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var isNode = __webpack_require__(157); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode; /***/ }, /* 157 */ /***/ function(module, exports) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } module.exports = isNode; /***/ }, /* 158 */ /***/ function(module, exports) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /* eslint-disable fb-www/typeof-undefined */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document or document body is not * yet defined. */ function getActiveElement() /*?DOMElement*/{ if (typeof document === 'undefined') { return null; } try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; /***/ }, /* 159 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var NS = { xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; // We use attributes for everything SVG so let's avoid some duplication and run // code instead. // The following are all specified in the HTML config already so we exclude here. // - class (as className) // - color // - height // - id // - lang // - max // - media // - method // - min // - name // - style // - target // - type // - width var ATTRS = { accentHeight: 'accent-height', accumulate: 0, additive: 0, alignmentBaseline: 'alignment-baseline', allowReorder: 'allowReorder', alphabetic: 0, amplitude: 0, arabicForm: 'arabic-form', ascent: 0, attributeName: 'attributeName', attributeType: 'attributeType', autoReverse: 'autoReverse', azimuth: 0, baseFrequency: 'baseFrequency', baseProfile: 'baseProfile', baselineShift: 'baseline-shift', bbox: 0, begin: 0, bias: 0, by: 0, calcMode: 'calcMode', capHeight: 'cap-height', clip: 0, clipPath: 'clip-path', clipRule: 'clip-rule', clipPathUnits: 'clipPathUnits', colorInterpolation: 'color-interpolation', colorInterpolationFilters: 'color-interpolation-filters', colorProfile: 'color-profile', colorRendering: 'color-rendering', contentScriptType: 'contentScriptType', contentStyleType: 'contentStyleType', cursor: 0, cx: 0, cy: 0, d: 0, decelerate: 0, descent: 0, diffuseConstant: 'diffuseConstant', direction: 0, display: 0, divisor: 0, dominantBaseline: 'dominant-baseline', dur: 0, dx: 0, dy: 0, edgeMode: 'edgeMode', elevation: 0, enableBackground: 'enable-background', end: 0, exponent: 0, externalResourcesRequired: 'externalResourcesRequired', fill: 0, fillOpacity: 'fill-opacity', fillRule: 'fill-rule', filter: 0, filterRes: 'filterRes', filterUnits: 'filterUnits', floodColor: 'flood-color', floodOpacity: 'flood-opacity', focusable: 0, fontFamily: 'font-family', fontSize: 'font-size', fontSizeAdjust: 'font-size-adjust', fontStretch: 'font-stretch', fontStyle: 'font-style', fontVariant: 'font-variant', fontWeight: 'font-weight', format: 0, from: 0, fx: 0, fy: 0, g1: 0, g2: 0, glyphName: 'glyph-name', glyphOrientationHorizontal: 'glyph-orientation-horizontal', glyphOrientationVertical: 'glyph-orientation-vertical', glyphRef: 'glyphRef', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', hanging: 0, horizAdvX: 'horiz-adv-x', horizOriginX: 'horiz-origin-x', ideographic: 0, imageRendering: 'image-rendering', 'in': 0, in2: 0, intercept: 0, k: 0, k1: 0, k2: 0, k3: 0, k4: 0, kernelMatrix: 'kernelMatrix', kernelUnitLength: 'kernelUnitLength', kerning: 0, keyPoints: 'keyPoints', keySplines: 'keySplines', keyTimes: 'keyTimes', lengthAdjust: 'lengthAdjust', letterSpacing: 'letter-spacing', lightingColor: 'lighting-color', limitingConeAngle: 'limitingConeAngle', local: 0, markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', markerHeight: 'markerHeight', markerUnits: 'markerUnits', markerWidth: 'markerWidth', mask: 0, maskContentUnits: 'maskContentUnits', maskUnits: 'maskUnits', mathematical: 0, mode: 0, numOctaves: 'numOctaves', offset: 0, opacity: 0, operator: 0, order: 0, orient: 0, orientation: 0, origin: 0, overflow: 0, overlinePosition: 'overline-position', overlineThickness: 'overline-thickness', paintOrder: 'paint-order', panose1: 'panose-1', pathLength: 'pathLength', patternContentUnits: 'patternContentUnits', patternTransform: 'patternTransform', patternUnits: 'patternUnits', pointerEvents: 'pointer-events', points: 0, pointsAtX: 'pointsAtX', pointsAtY: 'pointsAtY', pointsAtZ: 'pointsAtZ', preserveAlpha: 'preserveAlpha', preserveAspectRatio: 'preserveAspectRatio', primitiveUnits: 'primitiveUnits', r: 0, radius: 0, refX: 'refX', refY: 'refY', renderingIntent: 'rendering-intent', repeatCount: 'repeatCount', repeatDur: 'repeatDur', requiredExtensions: 'requiredExtensions', requiredFeatures: 'requiredFeatures', restart: 0, result: 0, rotate: 0, rx: 0, ry: 0, scale: 0, seed: 0, shapeRendering: 'shape-rendering', slope: 0, spacing: 0, specularConstant: 'specularConstant', specularExponent: 'specularExponent', speed: 0, spreadMethod: 'spreadMethod', startOffset: 'startOffset', stdDeviation: 'stdDeviation', stemh: 0, stemv: 0, stitchTiles: 'stitchTiles', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strikethroughPosition: 'strikethrough-position', strikethroughThickness: 'strikethrough-thickness', string: 0, stroke: 0, strokeDasharray: 'stroke-dasharray', strokeDashoffset: 'stroke-dashoffset', strokeLinecap: 'stroke-linecap', strokeLinejoin: 'stroke-linejoin', strokeMiterlimit: 'stroke-miterlimit', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', surfaceScale: 'surfaceScale', systemLanguage: 'systemLanguage', tableValues: 'tableValues', targetX: 'targetX', targetY: 'targetY', textAnchor: 'text-anchor', textDecoration: 'text-decoration', textRendering: 'text-rendering', textLength: 'textLength', to: 0, transform: 0, u1: 0, u2: 0, underlinePosition: 'underline-position', underlineThickness: 'underline-thickness', unicode: 0, unicodeBidi: 'unicode-bidi', unicodeRange: 'unicode-range', unitsPerEm: 'units-per-em', vAlphabetic: 'v-alphabetic', vHanging: 'v-hanging', vIdeographic: 'v-ideographic', vMathematical: 'v-mathematical', values: 0, vectorEffect: 'vector-effect', version: 0, vertAdvY: 'vert-adv-y', vertOriginX: 'vert-origin-x', vertOriginY: 'vert-origin-y', viewBox: 'viewBox', viewTarget: 'viewTarget', visibility: 0, widths: 0, wordSpacing: 'word-spacing', writingMode: 'writing-mode', x: 0, xHeight: 'x-height', x1: 0, x2: 0, xChannelSelector: 'xChannelSelector', xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', xmlns: 0, xmlnsXlink: 'xmlns:xlink', xmlLang: 'xml:lang', xmlSpace: 'xml:space', y: 0, y1: 0, y2: 0, yChannelSelector: 'yChannelSelector', z: 0, zoomAndPan: 'zoomAndPan' }; var SVGDOMPropertyConfig = { Properties: {}, DOMAttributeNamespaces: { xlinkActuate: NS.xlink, xlinkArcrole: NS.xlink, xlinkHref: NS.xlink, xlinkRole: NS.xlink, xlinkShow: NS.xlink, xlinkTitle: NS.xlink, xlinkType: NS.xlink, xmlBase: NS.xml, xmlLang: NS.xml, xmlSpace: NS.xml }, DOMAttributeNames: {} }; Object.keys(ATTRS).forEach(function (key) { SVGDOMPropertyConfig.Properties[key] = 0; if (ATTRS[key]) { SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key]; } }); module.exports = SVGDOMPropertyConfig; /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPropagators = __webpack_require__(47); var ExecutionEnvironment = __webpack_require__(54); var ReactDOMComponentTree = __webpack_require__(40); var ReactInputSelection = __webpack_require__(152); var SyntheticEvent = __webpack_require__(59); var getActiveElement = __webpack_require__(158); var isTextInputElement = __webpack_require__(77); var shallowEqual = __webpack_require__(129); var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; var eventTypes = { select: { phasedRegistrationNames: { bubbled: 'onSelect', captured: 'onSelectCapture' }, dependencies: ['topBlur', 'topContextMenu', 'topFocus', 'topKeyDown', 'topKeyUp', 'topMouseDown', 'topMouseUp', 'topSelectionChange'] } }; var activeElement = null; var activeElementInst = null; var lastSelection = null; var mouseDown = false; // Track whether a listener exists for this plugin. If none exist, we do // not extract events. See #3639. var hasListener = false; /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @return {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (!hasListener) { return null; } var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; switch (topLevelType) { // Track the input node that has focus. case 'topFocus': if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') { activeElement = targetNode; activeElementInst = targetInst; lastSelection = null; } break; case 'topBlur': activeElement = null; activeElementInst = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case 'topMouseDown': mouseDown = true; break; case 'topContextMenu': case 'topMouseUp': mouseDown = false; return constructSelectEvent(nativeEvent, nativeEventTarget); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case 'topSelectionChange': if (skipSelectionChangeEvent) { break; } // falls through case 'topKeyDown': case 'topKeyUp': return constructSelectEvent(nativeEvent, nativeEventTarget); } return null; }, didPutListener: function (inst, registrationName, listener) { if (registrationName === 'onSelect') { hasListener = true; } } }; module.exports = SelectEventPlugin; /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var EventListener = __webpack_require__(148); var EventPropagators = __webpack_require__(47); var ReactDOMComponentTree = __webpack_require__(40); var SyntheticAnimationEvent = __webpack_require__(162); var SyntheticClipboardEvent = __webpack_require__(163); var SyntheticEvent = __webpack_require__(59); var SyntheticFocusEvent = __webpack_require__(164); var SyntheticKeyboardEvent = __webpack_require__(165); var SyntheticMouseEvent = __webpack_require__(80); var SyntheticDragEvent = __webpack_require__(168); var SyntheticTouchEvent = __webpack_require__(169); var SyntheticTransitionEvent = __webpack_require__(170); var SyntheticUIEvent = __webpack_require__(81); var SyntheticWheelEvent = __webpack_require__(171); var emptyFunction = __webpack_require__(18); var getEventCharCode = __webpack_require__(166); var invariant = __webpack_require__(14); /** * Turns * ['abort', ...] * into * eventTypes = { * 'abort': { * phasedRegistrationNames: { * bubbled: 'onAbort', * captured: 'onAbortCapture', * }, * dependencies: ['topAbort'], * }, * ... * }; * topLevelEventsToDispatchConfig = { * 'topAbort': { sameConfig } * }; */ var eventTypes = {}; var topLevelEventsToDispatchConfig = {}; ['abort', 'animationEnd', 'animationIteration', 'animationStart', 'blur', 'canPlay', 'canPlayThrough', 'click', 'contextMenu', 'copy', 'cut', 'doubleClick', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'focus', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'mouseDown', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp', 'paste', 'pause', 'play', 'playing', 'progress', 'rateChange', 'reset', 'scroll', 'seeked', 'seeking', 'stalled', 'submit', 'suspend', 'timeUpdate', 'touchCancel', 'touchEnd', 'touchMove', 'touchStart', 'transitionEnd', 'volumeChange', 'waiting', 'wheel'].forEach(function (event) { var capitalizedEvent = event[0].toUpperCase() + event.slice(1); var onEvent = 'on' + capitalizedEvent; var topEvent = 'top' + capitalizedEvent; var type = { phasedRegistrationNames: { bubbled: onEvent, captured: onEvent + 'Capture' }, dependencies: [topEvent] }; eventTypes[event] = type; topLevelEventsToDispatchConfig[topEvent] = type; }); var onClickListeners = {}; function getDictionaryKey(inst) { // Prevents V8 performance issue: // https://github.com/facebook/react/pull/7232 return '.' + inst._rootNodeID; } function isInteractive(tag) { return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea'; } var SimpleEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case 'topAbort': case 'topCanPlay': case 'topCanPlayThrough': case 'topDurationChange': case 'topEmptied': case 'topEncrypted': case 'topEnded': case 'topError': case 'topInput': case 'topInvalid': case 'topLoad': case 'topLoadedData': case 'topLoadedMetadata': case 'topLoadStart': case 'topPause': case 'topPlay': case 'topPlaying': case 'topProgress': case 'topRateChange': case 'topReset': case 'topSeeked': case 'topSeeking': case 'topStalled': case 'topSubmit': case 'topSuspend': case 'topTimeUpdate': case 'topVolumeChange': case 'topWaiting': // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case 'topKeyPress': // Firefox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case 'topKeyDown': case 'topKeyUp': EventConstructor = SyntheticKeyboardEvent; break; case 'topBlur': case 'topFocus': EventConstructor = SyntheticFocusEvent; break; case 'topClick': // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case 'topDoubleClick': case 'topMouseDown': case 'topMouseMove': case 'topMouseUp': // TODO: Disabled elements should not respond to mouse events /* falls through */ case 'topMouseOut': case 'topMouseOver': case 'topContextMenu': EventConstructor = SyntheticMouseEvent; break; case 'topDrag': case 'topDragEnd': case 'topDragEnter': case 'topDragExit': case 'topDragLeave': case 'topDragOver': case 'topDragStart': case 'topDrop': EventConstructor = SyntheticDragEvent; break; case 'topTouchCancel': case 'topTouchEnd': case 'topTouchMove': case 'topTouchStart': EventConstructor = SyntheticTouchEvent; break; case 'topAnimationEnd': case 'topAnimationIteration': case 'topAnimationStart': EventConstructor = SyntheticAnimationEvent; break; case 'topTransitionEnd': EventConstructor = SyntheticTransitionEvent; break; case 'topScroll': EventConstructor = SyntheticUIEvent; break; case 'topWheel': EventConstructor = SyntheticWheelEvent; break; case 'topCopy': case 'topCut': case 'topPaste': EventConstructor = SyntheticClipboardEvent; break; } !EventConstructor ? process.env.NODE_ENV !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : _prodInvariant('86', topLevelType) : void 0; var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget); EventPropagators.accumulateTwoPhaseDispatches(event); return event; }, didPutListener: function (inst, registrationName, listener) { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html if (registrationName === 'onClick' && !isInteractive(inst._tag)) { var key = getDictionaryKey(inst); var node = ReactDOMComponentTree.getNodeFromInstance(inst); if (!onClickListeners[key]) { onClickListeners[key] = EventListener.listen(node, 'click', emptyFunction); } } }, willDeleteListener: function (inst, registrationName) { if (registrationName === 'onClick' && !isInteractive(inst._tag)) { var key = getDictionaryKey(inst); onClickListeners[key].remove(); delete onClickListeners[key]; } } }; module.exports = SimpleEventPlugin; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(59); /** * @interface Event * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent */ var AnimationEventInterface = { animationName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface); module.exports = SyntheticAnimationEvent; /***/ }, /* 163 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(59); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = { clipboardData: function (event) { return 'clipboardData' in event ? event.clipboardData : window.clipboardData; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticUIEvent = __webpack_require__(81); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = { relatedTarget: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; /***/ }, /* 165 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticUIEvent = __webpack_require__(81); var getEventCharCode = __webpack_require__(166); var getEventKey = __webpack_require__(167); var getEventModifierState = __webpack_require__(83); /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = { key: getEventKey, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, getModifierState: getEventModifierState, // Legacy Interface charCode: function (event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function (event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function (event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; /***/ }, /* 166 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } module.exports = getEventCharCode; /***/ }, /* 167 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var getEventCharCode = __webpack_require__(166); /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { 'Esc': 'Escape', 'Spacebar': ' ', 'Left': 'ArrowLeft', 'Up': 'ArrowUp', 'Right': 'ArrowRight', 'Down': 'ArrowDown', 'Del': 'Delete', 'Win': 'OS', 'Menu': 'ContextMenu', 'Apps': 'ContextMenu', 'Scroll': 'ScrollLock', 'MozPrintableKey': 'Unidentified' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { 8: 'Backspace', 9: 'Tab', 12: 'Clear', 13: 'Enter', 16: 'Shift', 17: 'Control', 18: 'Alt', 19: 'Pause', 20: 'CapsLock', 27: 'Escape', 32: ' ', 33: 'PageUp', 34: 'PageDown', 35: 'End', 36: 'Home', 37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown', 45: 'Insert', 46: 'Delete', 112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6', 118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12', 144: 'NumLock', 145: 'ScrollLock', 224: 'Meta' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } module.exports = getEventKey; /***/ }, /* 168 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticMouseEvent = __webpack_require__(80); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = { dataTransfer: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; /***/ }, /* 169 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticUIEvent = __webpack_require__(81); var getEventModifierState = __webpack_require__(83); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null, getModifierState: getEventModifierState }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; /***/ }, /* 170 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(59); /** * @interface Event * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events- * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent */ var TransitionEventInterface = { propertyName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface); module.exports = SyntheticTransitionEvent; /***/ }, /* 171 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticMouseEvent = __webpack_require__(80); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function (event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY: function (event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0; }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; /***/ }, /* 172 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var DOMLazyTree = __webpack_require__(87); var DOMProperty = __webpack_require__(42); var React = __webpack_require__(8); var ReactBrowserEventEmitter = __webpack_require__(111); var ReactCurrentOwner = __webpack_require__(16); var ReactDOMComponentTree = __webpack_require__(40); var ReactDOMContainerInfo = __webpack_require__(173); var ReactDOMFeatureFlags = __webpack_require__(174); var ReactFeatureFlags = __webpack_require__(64); var ReactInstanceMap = __webpack_require__(122); var ReactInstrumentation = __webpack_require__(68); var ReactMarkupChecksum = __webpack_require__(175); var ReactReconciler = __webpack_require__(65); var ReactUpdateQueue = __webpack_require__(141); var ReactUpdates = __webpack_require__(62); var emptyObject = __webpack_require__(26); var instantiateReactComponent = __webpack_require__(124); var invariant = __webpack_require__(14); var setInnerHTML = __webpack_require__(89); var shouldUpdateReactComponent = __webpack_require__(130); var warning = __webpack_require__(17); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var ROOT_ATTR_NAME = DOMProperty.ROOT_ATTRIBUTE_NAME; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; var instancesByReactRootID = {}; /** * Finds the index of the first character * that's not common between the two given strings. * * @return {number} the index of the character where the strings diverge */ function firstDifferenceIndex(string1, string2) { var minLen = Math.min(string1.length, string2.length); for (var i = 0; i < minLen; i++) { if (string1.charAt(i) !== string2.charAt(i)) { return i; } } return string1.length === string2.length ? -1 : minLen; } /** * @param {DOMElement|DOMDocument} container DOM element that may contain * a React component * @return {?*} DOM element that may have the reactRoot ID, or null. */ function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOC_NODE_TYPE) { return container.documentElement; } else { return container.firstChild; } } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Mounts this component and inserts it into the DOM. * * @param {ReactComponent} componentInstance The instance to mount. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function mountComponentIntoNode(wrapperInstance, container, transaction, shouldReuseMarkup, context) { var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var wrappedElement = wrapperInstance._currentElement.props.child; var type = wrappedElement.type; markerName = 'React mount: ' + (typeof type === 'string' ? type : type.displayName || type.name); console.time(markerName); } var markup = ReactReconciler.mountComponent(wrapperInstance, transaction, null, ReactDOMContainerInfo(wrapperInstance, container), context, 0 /* parentDebugID */ ); if (markerName) { console.timeEnd(markerName); } wrapperInstance._renderedComponent._topLevelWrapper = wrapperInstance; ReactMount._mountImageIntoNode(markup, container, wrapperInstance, shouldReuseMarkup, transaction); } /** * Batched mount. * * @param {ReactComponent} componentInstance The instance to mount. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */ !shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement); transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context); ReactUpdates.ReactReconcileTransaction.release(transaction); } /** * Unmounts a component and removes it from the DOM. * * @param {ReactComponent} instance React component instance. * @param {DOMElement} container DOM element to unmount from. * @final * @internal * @see {ReactMount.unmountComponentAtNode} */ function unmountComponentFromNode(instance, container, safely) { if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onBeginFlush(); } ReactReconciler.unmountComponent(instance, safely); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onEndFlush(); } if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } } /** * True if the supplied DOM node has a direct React-rendered child that is * not a React root element. Useful for warning in `render`, * `unmountComponentAtNode`, etc. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM element contains a direct child that was * rendered by React but is not a root element. * @internal */ function hasNonRootReactChild(container) { var rootEl = getReactRootElementInContainer(container); if (rootEl) { var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl); return !!(inst && inst._hostParent); } } /** * True if the supplied DOM node is a React DOM element and * it has been rendered by another copy of React. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM has been rendered by another copy of React * @internal */ function nodeIsRenderedByOtherInstance(container) { var rootEl = getReactRootElementInContainer(container); return !!(rootEl && isReactNode(rootEl) && !ReactDOMComponentTree.getInstanceFromNode(rootEl)); } /** * True if the supplied DOM node is a valid node element. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM is a valid DOM node. * @internal */ function isValidContainer(node) { return !!(node && (node.nodeType === ELEMENT_NODE_TYPE || node.nodeType === DOC_NODE_TYPE || node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)); } /** * True if the supplied DOM node is a valid React node element. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM is a valid React DOM node. * @internal */ function isReactNode(node) { return isValidContainer(node) && (node.hasAttribute(ROOT_ATTR_NAME) || node.hasAttribute(ATTR_NAME)); } function getHostRootInstanceInContainer(container) { var rootEl = getReactRootElementInContainer(container); var prevHostInstance = rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl); return prevHostInstance && !prevHostInstance._hostParent ? prevHostInstance : null; } function getTopLevelWrapperInContainer(container) { var root = getHostRootInstanceInContainer(container); return root ? root._hostContainerInfo._topLevelWrapper : null; } /** * Temporary (?) hack so that we can store all top-level pending updates on * composites instead of having to worry about different types of components * here. */ var topLevelRootCounter = 1; var TopLevelWrapper = function () { this.rootID = topLevelRootCounter++; }; TopLevelWrapper.prototype.isReactComponent = {}; if (process.env.NODE_ENV !== 'production') { TopLevelWrapper.displayName = 'TopLevelWrapper'; } TopLevelWrapper.prototype.render = function () { return this.props.child; }; TopLevelWrapper.isReactTopLevelWrapper = true; /** * Mounting is the process of initializing a React component by creating its * representative DOM elements and inserting them into a supplied `container`. * Any prior content inside `container` is destroyed in the process. * * ReactMount.render( * component, * document.getElementById('container') * ); * * <div id="container"> <-- Supplied `container`. * <div data-reactid=".3"> <-- Rendered reactRoot of React * // ... component. * </div> * </div> * * Inside of `container`, the first element rendered is the "reactRoot". */ var ReactMount = { TopLevelWrapper: TopLevelWrapper, /** * Used by devtools. The keys are not important. */ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function (container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactElement} nextElement component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function (prevComponent, nextElement, nextContext, container, callback) { ReactMount.scrollMonitor(container, function () { ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement, nextContext); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); } }); return prevComponent; }, /** * Render a new component into the DOM. Hooked by hooks! * * @param {ReactElement} nextElement element to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : _prodInvariant('37') : void 0; ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var componentInstance = instantiateReactComponent(nextElement, false); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context); var wrapperID = componentInstance._instance.rootID; instancesByReactRootID[wrapperID] = componentInstance; return componentInstance; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactComponent} parentComponent The conceptual parent of this render tree. * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { !(parentComponent != null && ReactInstanceMap.has(parentComponent)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : _prodInvariant('38') : void 0; return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback); }, _renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { ReactUpdateQueue.validateCallback(callback, 'ReactDOM.render'); !React.isValidElement(nextElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : // Check if it quacks like an element nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : _prodInvariant('39', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : void 0; process.env.NODE_ENV !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : void 0; var nextWrappedElement = React.createElement(TopLevelWrapper, { child: nextElement }); var nextContext; if (parentComponent) { var parentInst = ReactInstanceMap.get(parentComponent); nextContext = parentInst._processChildContext(parentInst._context); } else { nextContext = emptyObject; } var prevComponent = getTopLevelWrapperInContainer(container); if (prevComponent) { var prevWrappedElement = prevComponent._currentElement; var prevElement = prevWrappedElement.props.child; if (shouldUpdateReactComponent(prevElement, nextElement)) { var publicInst = prevComponent._renderedComponent.getPublicInstance(); var updatedCallback = callback && function () { callback.call(publicInst); }; ReactMount._updateRootComponent(prevComponent, nextWrappedElement, nextContext, container, updatedCallback); return publicInst; } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement); var containerHasNonRootReactChild = hasNonRootReactChild(container); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : void 0; if (!containerHasReactMarkup || reactRootElement.nextSibling) { var rootElementSibling = reactRootElement; while (rootElementSibling) { if (internalGetID(rootElementSibling)) { process.env.NODE_ENV !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : void 0; break; } rootElementSibling = rootElementSibling.nextSibling; } } } var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild; var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, nextContext)._renderedComponent.getPublicInstance(); if (callback) { callback.call(component); } return component; }, /** * Renders a React component into the DOM in the supplied `container`. * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.render * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ render: function (nextElement, container, callback) { return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback); }, /** * Unmounts and destroys the React component rendered in the `container`. * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.unmountcomponentatnode * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function (container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : _prodInvariant('40') : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!nodeIsRenderedByOtherInstance(container), 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by another copy of React.') : void 0; } var prevComponent = getTopLevelWrapperInContainer(container); if (!prevComponent) { // Check if the node being unmounted was rendered by React, but isn't a // root node. var containerHasNonRootReactChild = hasNonRootReactChild(container); // Check if the container itself is a React root node. var isContainerReactRoot = container.nodeType === 1 && container.hasAttribute(ROOT_ATTR_NAME); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : void 0; } return false; } delete instancesByReactRootID[prevComponent._instance.rootID]; ReactUpdates.batchedUpdates(unmountComponentFromNode, prevComponent, container, false); return true; }, _mountImageIntoNode: function (markup, container, instance, shouldReuseMarkup, transaction) { !isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : _prodInvariant('41') : void 0; if (shouldReuseMarkup) { var rootElement = getReactRootElementInContainer(container); if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) { ReactDOMComponentTree.precacheNode(instance, rootElement); return; } else { var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); var rootMarkup = rootElement.outerHTML; rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum); var normalizedMarkup = markup; if (process.env.NODE_ENV !== 'production') { // because rootMarkup is retrieved from the DOM, various normalizations // will have occurred which will not be present in `markup`. Here, // insert markup into a <div> or <iframe> depending on the container // type to perform the same normalizations before comparing. var normalizer; if (container.nodeType === ELEMENT_NODE_TYPE) { normalizer = document.createElement('div'); normalizer.innerHTML = markup; normalizedMarkup = normalizer.innerHTML; } else { normalizer = document.createElement('iframe'); document.body.appendChild(normalizer); normalizer.contentDocument.write(markup); normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML; document.body.removeChild(normalizer); } } var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup); var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20); !(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using server rendering but the checksum was invalid. This usually means you rendered a different component type or props on the client from the one on the server, or your render() methods are impure. React cannot handle this case due to cross-browser quirks by rendering at the document root. You should look for environment dependent code in your components and ensure the props are the same client and server side:\n%s', difference) : _prodInvariant('42', difference) : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : void 0; } } } !(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but you didn\'t use server rendering. We can\'t do this without using server rendering due to cross-browser quirks. See ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('43') : void 0; if (transaction.useCreateElement) { while (container.lastChild) { container.removeChild(container.lastChild); } DOMLazyTree.insertTreeBefore(container, markup, null); } else { setInnerHTML(container, markup); ReactDOMComponentTree.precacheNode(instance, container.firstChild); } if (process.env.NODE_ENV !== 'production') { var hostNode = ReactDOMComponentTree.getInstanceFromNode(container.firstChild); if (hostNode._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: hostNode._debugID, type: 'mount', payload: markup.toString() }); } } } }; module.exports = ReactMount; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var validateDOMNesting = __webpack_require__(142); var DOC_NODE_TYPE = 9; function ReactDOMContainerInfo(topLevelWrapper, node) { var info = { _topLevelWrapper: topLevelWrapper, _idCounter: 1, _ownerDocument: node ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument : null, _node: node, _tag: node ? node.nodeName.toLowerCase() : null, _namespaceURI: node ? node.namespaceURI : null }; if (process.env.NODE_ENV !== 'production') { info._ancestorInfo = node ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null; } return info; } module.exports = ReactDOMContainerInfo; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 174 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMFeatureFlags = { useCreateElement: true, useFiber: false }; module.exports = ReactDOMFeatureFlags; /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var adler32 = __webpack_require__(176); var TAG_END = /\/?>/; var COMMENT_START = /^<\!\-\-/; var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function (markup) { var checksum = adler32(markup); // Add checksum (handle both parent tags, comments and self-closing tags) if (COMMENT_START.test(markup)) { return markup; } else { return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); } }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function (markup, element) { var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; /***/ }, /* 176 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var MOD = 65521; // adler32 is not cryptographically strong, and is only used to sanity check that // markup generated on the server matches the markup generated on the client. // This implementation (a modified version of the SheetJS version) has been optimized // for our use case, at the expense of conforming to the adler32 specification // for non-ascii inputs. function adler32(data) { var a = 1; var b = 0; var i = 0; var l = data.length; var m = l & ~0x3; while (i < m) { var n = Math.min(i + 4096, m); for (; i < n; i += 4) { b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); } a %= MOD; b %= MOD; } for (; i < l; i++) { b += a += data.charCodeAt(i); } a %= MOD; b %= MOD; return a | b << 16; } module.exports = adler32; /***/ }, /* 177 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; module.exports = '15.4.2'; /***/ }, /* 178 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var ReactCurrentOwner = __webpack_require__(16); var ReactDOMComponentTree = __webpack_require__(40); var ReactInstanceMap = __webpack_require__(122); var getHostComponentFromComposite = __webpack_require__(179); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); /** * Returns the DOM node rendered by this element. * * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode * * @param {ReactComponent|DOMElement} componentOrElement * @return {?DOMElement} The root node of this element. */ function findDOMNode(componentOrElement) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } var inst = ReactInstanceMap.get(componentOrElement); if (inst) { inst = getHostComponentFromComposite(inst); return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null; } if (typeof componentOrElement.render === 'function') { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : _prodInvariant('44') : void 0; } else { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement)) : void 0; } } module.exports = findDOMNode; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactNodeTypes = __webpack_require__(126); function getHostComponentFromComposite(inst) { var type; while ((type = inst._renderedNodeType) === ReactNodeTypes.COMPOSITE) { inst = inst._renderedComponent; } if (type === ReactNodeTypes.HOST) { return inst._renderedComponent; } else if (type === ReactNodeTypes.EMPTY) { return null; } } module.exports = getHostComponentFromComposite; /***/ }, /* 180 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactMount = __webpack_require__(172); module.exports = ReactMount.renderSubtreeIntoContainer; /***/ }, /* 181 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(42); var EventPluginRegistry = __webpack_require__(49); var ReactComponentTreeHook = __webpack_require__(32); var warning = __webpack_require__(17); if (process.env.NODE_ENV !== 'production') { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true, autoFocus: true, defaultValue: true, valueLink: true, defaultChecked: true, checkedLink: true, innerHTML: true, suppressContentEditableWarning: true, onFocusIn: true, onFocusOut: true }; var warnedProperties = {}; var validateProperty = function (tagName, name, debugID) { if (DOMProperty.properties.hasOwnProperty(name) || DOMProperty.isCustomAttribute(name)) { return true; } if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return true; } if (EventPluginRegistry.registrationNameModules.hasOwnProperty(name)) { return true; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; var registrationName = EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? EventPluginRegistry.possibleRegistrationNames[lowerCasedName] : null; if (standardName != null) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown DOM property %s. Did you mean %s?%s', name, standardName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; return true; } else if (registrationName != null) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown event handler property %s. Did you mean `%s`?%s', name, registrationName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; return true; } else { // We were unable to guess which prop the user intended. // It is likely that the user was just blindly spreading/forwarding props // Components should be careful to only render valid props/attributes. // Warning will be invoked in warnUnknownProperties to allow grouping. return false; } }; } var warnUnknownProperties = function (debugID, element) { var unknownProps = []; for (var key in element.props) { var isValid = validateProperty(element.type, key, debugID); if (!isValid) { unknownProps.push(key); } } var unknownPropString = unknownProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (unknownProps.length === 1) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown prop %s on <%s> tag. Remove this prop from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } else if (unknownProps.length > 1) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown props %s on <%s> tag. Remove these props from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } }; function handleElement(debugID, element) { if (element == null || typeof element.type !== 'string') { return; } if (element.type.indexOf('-') >= 0 || element.props.is) { return; } warnUnknownProperties(debugID, element); } var ReactDOMUnknownPropertyHook = { onBeforeMountComponent: function (debugID, element) { handleElement(debugID, element); }, onBeforeUpdateComponent: function (debugID, element) { handleElement(debugID, element); } }; module.exports = ReactDOMUnknownPropertyHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 182 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactComponentTreeHook = __webpack_require__(32); var warning = __webpack_require__(17); var didWarnValueNull = false; function handleElement(debugID, element) { if (element == null) { return; } if (element.type !== 'input' && element.type !== 'textarea' && element.type !== 'select') { return; } if (element.props != null && element.props.value === null && !didWarnValueNull) { process.env.NODE_ENV !== 'production' ? warning(false, '`value` prop on `%s` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.%s', element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; didWarnValueNull = true; } } var ReactDOMNullInputValuePropHook = { onBeforeMountComponent: function (debugID, element) { handleElement(debugID, element); }, onBeforeUpdateComponent: function (debugID, element) { handleElement(debugID, element); } }; module.exports = ReactDOMNullInputValuePropHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 183 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(42); var ReactComponentTreeHook = __webpack_require__(32); var warning = __webpack_require__(17); var warnedProperties = {}; var rARIA = new RegExp('^(aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$'); function validateProperty(tagName, name, debugID) { if (warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return true; } if (rARIA.test(name)) { var lowerCasedName = name.toLowerCase(); var standardName = DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; // If this is an aria-* attribute, but is not listed in the known DOM // DOM properties, then it is an invalid aria-* attribute. if (standardName == null) { warnedProperties[name] = true; return false; } // aria-* attributes should be lowercase; suggest the lowercase version. if (name !== standardName) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown ARIA attribute %s. Did you mean %s?%s', name, standardName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; warnedProperties[name] = true; return true; } } return true; } function warnInvalidARIAProps(debugID, element) { var invalidProps = []; for (var key in element.props) { var isValid = validateProperty(element.type, key, debugID); if (!isValid) { invalidProps.push(key); } } var unknownPropString = invalidProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (invalidProps.length === 1) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } else if (invalidProps.length > 1) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } } function handleElement(debugID, element) { if (element == null || typeof element.type !== 'string') { return; } if (element.type.indexOf('-') >= 0 || element.props.is) { return; } warnInvalidARIAProps(debugID, element); } var ReactDOMInvalidARIAHook = { onBeforeMountComponent: function (debugID, element) { if (process.env.NODE_ENV !== 'production') { handleElement(debugID, element); } }, onBeforeUpdateComponent: function (debugID, element) { if (process.env.NODE_ENV !== 'production') { handleElement(debugID, element); } } }; module.exports = ReactDOMInvalidARIAHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(7); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(38); var _reactDom2 = _interopRequireDefault(_reactDom); var _utilities = __webpack_require__(185); var _utilities2 = _interopRequireDefault(_utilities); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Riverine = _react2.default.createClass({ displayName: 'Riverine', propTypes: { hover: _react2.default.PropTypes.bool.isRequired, source: _react2.default.PropTypes.string.isRequired }, scrubberClicked: false, duration: '', audioNode: '', playButton: '', playHead: '', timeline: '', timelineWidth: '', sourceDuration: '', componentDidMount: function componentDidMount() { var that = _reactDom2.default.findDOMNode(this).children[0].children[0].children[0]; this.audioNode = that.children[0]; this.duration = that.children[3]; this.hover = that.children[2].children[0]; this.playButton = that.children[1].children[0].children[0]; this.playHead = that.children[2].children[0].children[0]; this.timeline = that.children[2]; this.timelineWidth = this.timeline.offsetWidth - this.playHead.offsetWidth; window.addEventListener('mouseup', this.mouseUp, false); window.addEventListener('resize', this.handleResize, false); this.audioNode.addEventListener('timeupdate', this.handlePlayhead, false); this.timeline.addEventListener('mouseover', this.handleHover, false); }, addHover: function addHover(e) { var positionOffset = _utilities2.default.handleOffsetParent(this.timeline); var newMargLeft = e.pageX - positionOffset; if (newMargLeft >= 0 && newMargLeft <= this.timelineWidth) { this.hover.style.width = newMargLeft + 'px'; }; if (newMargLeft < 0) { this.hover.style.width = '0px'; }; if (newMargLeft > this.timelineWidth) { this.hover.style.width = this.timelineWidth + 'px'; }; }, clickPercent: function clickPercent(e) { var positionOffset = _utilities2.default.handleOffsetParent(this.timeline); return (e.pageX - positionOffset) / this.timelineWidth; }, returnDuration: function returnDuration() { this.sourceDuration = this.audioNode.duration; this.duration.innerHTML = _utilities2.default.handleTime(this.audioNode.duration); this.updateTime(); }, play: function play() { if (this.audioNode.paused) { this.audioNode.play(); this.playButton.children[0].classList = ''; this.playButton.children[0].classList = 'fa fa-pause'; } else { this.audioNode.pause(); this.playButton.children[0].classList = ''; this.playButton.children[0].classList = 'fa fa-play'; }; }, updateTime: function updateTime() { this.duration.innerHTML = _utilities2.default.handleTime(this.audioNode.currentTime) + ' / ' + _utilities2.default.handleTime(this.audioNode.duration); if (this.audioNode.currentTime === this.sourceDuration) { this.playButton.children[0].classList = ''; this.playButton.children[0].classList = 'fa fa-play'; }; }, handleHover: function handleHover() { if (this.props.hover) { this.timeline.addEventListener('mousemove', this.addHover, false); this.timeline.addEventListener('mouseout', this.removeHover, false); }; }, handlePlayhead: function handlePlayhead() { var playPercent = this.timelineWidth * (this.audioNode.currentTime / this.audioNode.duration); if (this.props.margin) { this.playHead.style.marginLeft = playPercent + 'px'; } else { this.playHead.style.paddingLeft = playPercent + 'px'; }; }, handleResize: function handleResize() { var padding = this.playHead.style.paddingLeft; var p = void 0; padding === '' ? p = 0 : p = parseInt(padding.substring(0, padding.length - 2)); this.timelineWidth = this.timeline.offsetWidth - this.playHead.offsetWidth + p; this.handlePlayhead(); }, mouseDown: function mouseDown() { this.scrubberClicked = true; window.addEventListener('mousemove', this.moveplayhead, true); this.audioNode.removeEventListener('timeupdate', this.handlePlayhead, false); }, mouseUp: function mouseUp(e) { if (this.scrubberClicked === false) { return; }; this.moveplayhead(e); window.removeEventListener('mousemove', this.moveplayhead, true); this.audioNode.currentTime = this.audioNode.duration * this.clickPercent(e); this.audioNode.addEventListener('timeupdate', this.handlePlayhead, false); this.scrubberClicked = false; }, moveplayhead: function moveplayhead(e) { var positionOffset = _utilities2.default.handleOffsetParent(this.timeline); var newMargLeft = e.pageX - positionOffset; var n = this.playHead.style.width; if (newMargLeft >= 0 && newMargLeft <= this.timelineWidth) { n = newMargLeft + 'px'; }; if (newMargLeft < 0) { n = '0px'; }; if (newMargLeft > this.timelineWidth) { n = this.timelineWidth + 'px'; }; }, removeHover: function removeHover() { this.hover.style.width = '0px'; }, render: function render() { return _react2.default.createElement( 'div', null, _react2.default.createElement( 'div', { className: 'riverine-player' }, _react2.default.createElement( 'div', { className: 'riverine-type-single' }, _react2.default.createElement( 'div', { className: 'riverine-gui riverine-interface riverine-player' }, _react2.default.createElement( 'audio', { id: _utilities2.default.newId('audio-'), preload: 'auto', onDurationChange: this.returnDuration, onTimeUpdate: this.updateTime, loop: this.props.loop }, _react2.default.createElement('source', { src: this.props.source }) ), _react2.default.createElement( 'ul', { className: 'riverine-controls' }, _react2.default.createElement( 'li', { className: 'play-button-container' }, _react2.default.createElement( 'a', { className: 'riverine-play', onClick: this.play }, _react2.default.createElement('i', { className: 'fa fa-play' }) ) ) ), _react2.default.createElement( 'div', { className: 'riverine-progress', onMouseDown: this.mouseDown }, _react2.default.createElement( 'div', { className: 'riverine-seek-bar' }, _react2.default.createElement('div', { className: 'riverine-play-bar', onMouseDown: this.mouseDown }) ) ), _react2.default.createElement( 'div', { className: 'riverine-time-holder' }, _react2.default.createElement('span', null) ) ) ) ) ); } }); exports.default = Riverine; /***/ }, /* 185 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var utilities = { handleTime: function handleTime(duration) { var sec_num = parseInt(duration, 10); var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - hours * 3600) / 60); var seconds = sec_num - hours * 3600 - minutes * 60; if (hours < 10 && hours > 0) { hours = '0' + hours + ':'; } else { hours = ''; } if (minutes < 10) { minutes = '0' + minutes; } if (seconds < 10) { seconds = '0' + seconds; } return hours + minutes + ':' + seconds; }, handleOffsetParent: function handleOffsetParent(node) { var n = node; var o = 0; while (n.offsetParent !== null) { o = o + n.offsetLeft; n = n.offsetParent; }; return o; }, newId: function newId(prefix) { return '' + prefix + new Date().getTime(); } }; exports.default = utilities; /***/ } /******/ ]);
public/bundle.js
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(1); __webpack_require__(5); var _react = __webpack_require__(7); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(38); var _riverine = __webpack_require__(184); var _riverine2 = _interopRequireDefault(_riverine); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Root = function Root() { return _react2.default.createElement( 'div', null, _react2.default.createElement(_riverine2.default, { hover: true, source: 'audio/1.mp3' }) ); }; (0, _reactDom.render)(_react2.default.createElement(Root, null), document.querySelector('#root')); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__(2); if(typeof content === 'string') content = [[module.id, content, '']]; // add the styles to the DOM var update = __webpack_require__(4)(content, {}); if(content.locals) module.exports = content.locals; // Hot Module Replacement if(false) { // When the styles change, update the <style> tags if(!content.locals) { module.hot.accept("!!./../../node_modules/css-loader/index.js!./style.css", function() { var newContent = require("!!./../../node_modules/css-loader/index.js!./style.css"); if(typeof newContent === 'string') newContent = [[module.id, newContent, '']]; update(newContent); }); } // When the module is disposed, remove the <style> tags module.hot.dispose(function() { update(); }); } /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(3)(); // imports // module exports.push([module.id, "html {\n background-color: #f2f2f2;\n}\n\nbody {\n text-rendering: optimizeLegibility;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.004);\n cursor: default;\n color: #2b2b2b;\n}\n\na.link {\n text-decoration: none;\n color: #808080;\n position: relative;\n -moz-transition: all 250ms ease-in-out;\n -webkit-transition: all 250ms ease-in-out;\n -o-transition: all 250ms ease-in-out;\n transition: all 250ms ease-in-out;\n}\n\na.link:after {\n position: absolute;\n bottom: -2px;\n left: 0;\n width: 50%;\n height: 3px;\n background: #808080;\n -ms-filter: \"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)\";\n filter: alpha(opacity=(50));\n opacity: 0.5;\n content: \"\";\n -moz-transition: all 250ms ease-in-out;\n -webkit-transition: all 250ms ease-in-out;\n -o-transition: all 250ms ease-in-out;\n transition: all 250ms ease-in-out;\n}\n\na.link:hover {\n color: #ff5f6d;\n}\n\na.link:hover:after {\n width: 99%;\n background: #ff5f6d;\n}\n\na.mosaic-icon:hover svg g {\n fill: #ffc371;\n}\n\nfooter p {\n text-align: center;\n margin: 2em 0;\n}\n\nfooter p span a {\n text-decoration: none;\n color: #5a5a5a;\n font-size: 1.1em;\n}\n\nfooter p span:not(:first-child) {\n margin-left: 30px;\n}\n\nfooter p span a i:before,\nsvg g {\n transition: 0.3s ease;\n}\n\na:hover i.fa-github {\n color: #4078c0;\n}\n\na:hover i.fa-linkedin {\n color: #0077B5;\n}\n\nh1, h2, h3, h4, h5, h6 {\n font-family: 'Merriweather Sans', sans-serif;\n}\n\nh1 {\n font-size: 4.15em;\n text-align: center;\n letter-spacing: .418em;\n margin-bottom: 2em;\n}\n\nhr {\n height: .2em;\n background-color: rgba(90, 90, 90, 0.5);\n border-style: none;\n border-width: 0;\n margin: 4em 0 3em;\n}\n\nmain {\n padding: 200px 10px 0;\n}\n\np {\n font-family: 'Noto Serif', serif;\n font-size: 1.35em;\n letter-spacing: 0.05em;\n line-height: 1.8em;\n text-align: justify;\n}\n\nsvg {\n width: 20px;\n padding-top: 1px;\n}\n\n.container {\n max-width: 500px;\n margin: 0 auto;\n}\n\n.code {\n font-family: 'Ubuntu Mono', monospace;\n color: #5a5a5a;\n font-size: 1.15em;\n padding-left: 1.5em;\n margin: 4em 0;\n background: -webkit-linear-gradient(right, red, #2b2b2b);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n}\n\n::selection {\n background-color: rgba(0, 0, 0, 0);\n}\n\n@media screen and (max-width: 600px) {\n h1 {\n letter-spacing: .2em;\n font-size: 3.5em;\n margin-bottom: 1em;\n }\n}\n\n@media screen and (max-width: 500px) {\n p {\n font-size: 1em;\n }\n\n .code {\n font-size: .8em;\n }\n\n svg {\n width: .8em;\n }\n}\n", ""]); // exports /***/ }, /* 3 */ /***/ function(module, exports) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ // css base code, injected by the css-loader module.exports = function() { var list = []; // return the list of modules as css string list.toString = function toString() { var result = []; for(var i = 0; i < this.length; i++) { var item = this[i]; if(item[2]) { result.push("@media " + item[2] + "{" + item[1] + "}"); } else { result.push(item[1]); } } return result.join(""); }; // import a list of modules into the list list.i = function(modules, mediaQuery) { if(typeof modules === "string") modules = [[null, modules, ""]]; var alreadyImportedModules = {}; for(var i = 0; i < this.length; i++) { var id = this[i][0]; if(typeof id === "number") alreadyImportedModules[id] = true; } for(i = 0; i < modules.length; i++) { var item = modules[i]; // skip already imported module // this implementation is not 100% perfect for weird media query combinations // when a module is imported multiple times with different media queries. // I hope this will never occur (Hey this way we have smaller bundles) if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) { if(mediaQuery && !item[2]) { item[2] = mediaQuery; } else if(mediaQuery) { item[2] = "(" + item[2] + ") and (" + mediaQuery + ")"; } list.push(item); } } }; return list; }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var stylesInDom = {}, memoize = function(fn) { var memo; return function () { if (typeof memo === "undefined") memo = fn.apply(this, arguments); return memo; }; }, isOldIE = memoize(function() { return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase()); }), getHeadElement = memoize(function () { return document.head || document.getElementsByTagName("head")[0]; }), singletonElement = null, singletonCounter = 0, styleElementsInsertedAtTop = []; module.exports = function(list, options) { if(false) { if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment"); } options = options || {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style> // tags it will allow on a page if (typeof options.singleton === "undefined") options.singleton = isOldIE(); // By default, add <style> tags to the bottom of <head>. if (typeof options.insertAt === "undefined") options.insertAt = "bottom"; var styles = listToStyles(list); addStylesToDom(styles, options); return function update(newList) { var mayRemove = []; for(var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; domStyle.refs--; mayRemove.push(domStyle); } if(newList) { var newStyles = listToStyles(newList); addStylesToDom(newStyles, options); } for(var i = 0; i < mayRemove.length; i++) { var domStyle = mayRemove[i]; if(domStyle.refs === 0) { for(var j = 0; j < domStyle.parts.length; j++) domStyle.parts[j](); delete stylesInDom[domStyle.id]; } } }; } function addStylesToDom(styles, options) { for(var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; if(domStyle) { domStyle.refs++; for(var j = 0; j < domStyle.parts.length; j++) { domStyle.parts[j](item.parts[j]); } for(; j < item.parts.length; j++) { domStyle.parts.push(addStyle(item.parts[j], options)); } } else { var parts = []; for(var j = 0; j < item.parts.length; j++) { parts.push(addStyle(item.parts[j], options)); } stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts}; } } } function listToStyles(list) { var styles = []; var newStyles = {}; for(var i = 0; i < list.length; i++) { var item = list[i]; var id = item[0]; var css = item[1]; var media = item[2]; var sourceMap = item[3]; var part = {css: css, media: media, sourceMap: sourceMap}; if(!newStyles[id]) styles.push(newStyles[id] = {id: id, parts: [part]}); else newStyles[id].parts.push(part); } return styles; } function insertStyleElement(options, styleElement) { var head = getHeadElement(); var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1]; if (options.insertAt === "top") { if(!lastStyleElementInsertedAtTop) { head.insertBefore(styleElement, head.firstChild); } else if(lastStyleElementInsertedAtTop.nextSibling) { head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling); } else { head.appendChild(styleElement); } styleElementsInsertedAtTop.push(styleElement); } else if (options.insertAt === "bottom") { head.appendChild(styleElement); } else { throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'."); } } function removeStyleElement(styleElement) { styleElement.parentNode.removeChild(styleElement); var idx = styleElementsInsertedAtTop.indexOf(styleElement); if(idx >= 0) { styleElementsInsertedAtTop.splice(idx, 1); } } function createStyleElement(options) { var styleElement = document.createElement("style"); styleElement.type = "text/css"; insertStyleElement(options, styleElement); return styleElement; } function createLinkElement(options) { var linkElement = document.createElement("link"); linkElement.rel = "stylesheet"; insertStyleElement(options, linkElement); return linkElement; } function addStyle(obj, options) { var styleElement, update, remove; if (options.singleton) { var styleIndex = singletonCounter++; styleElement = singletonElement || (singletonElement = createStyleElement(options)); update = applyToSingletonTag.bind(null, styleElement, styleIndex, false); remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true); } else if(obj.sourceMap && typeof URL === "function" && typeof URL.createObjectURL === "function" && typeof URL.revokeObjectURL === "function" && typeof Blob === "function" && typeof btoa === "function") { styleElement = createLinkElement(options); update = updateLink.bind(null, styleElement); remove = function() { removeStyleElement(styleElement); if(styleElement.href) URL.revokeObjectURL(styleElement.href); }; } else { styleElement = createStyleElement(options); update = applyToTag.bind(null, styleElement); remove = function() { removeStyleElement(styleElement); }; } update(obj); return function updateStyle(newObj) { if(newObj) { if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) return; update(obj = newObj); } else { remove(); } }; } var replaceText = (function () { var textStore = []; return function (index, replacement) { textStore[index] = replacement; return textStore.filter(Boolean).join('\n'); }; })(); function applyToSingletonTag(styleElement, index, remove, obj) { var css = remove ? "" : obj.css; if (styleElement.styleSheet) { styleElement.styleSheet.cssText = replaceText(index, css); } else { var cssNode = document.createTextNode(css); var childNodes = styleElement.childNodes; if (childNodes[index]) styleElement.removeChild(childNodes[index]); if (childNodes.length) { styleElement.insertBefore(cssNode, childNodes[index]); } else { styleElement.appendChild(cssNode); } } } function applyToTag(styleElement, obj) { var css = obj.css; var media = obj.media; if(media) { styleElement.setAttribute("media", media) } if(styleElement.styleSheet) { styleElement.styleSheet.cssText = css; } else { while(styleElement.firstChild) { styleElement.removeChild(styleElement.firstChild); } styleElement.appendChild(document.createTextNode(css)); } } function updateLink(linkElement, obj) { var css = obj.css; var sourceMap = obj.sourceMap; if(sourceMap) { // http://stackoverflow.com/a/26603875 css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */"; } var blob = new Blob([css], { type: "text/css" }); var oldSrc = linkElement.href; linkElement.href = URL.createObjectURL(blob); if(oldSrc) URL.revokeObjectURL(oldSrc); } /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__(6); if(typeof content === 'string') content = [[module.id, content, '']]; // add the styles to the DOM var update = __webpack_require__(4)(content, {}); if(content.locals) module.exports = content.locals; // Hot Module Replacement if(false) { // When the styles change, update the <style> tags if(!content.locals) { module.hot.accept("!!./../../node_modules/css-loader/index.js!./player.css", function() { var newContent = require("!!./../../node_modules/css-loader/index.js!./player.css"); if(typeof newContent === 'string') newContent = [[module.id, newContent, '']]; update(newContent); }); } // When the module is disposed, remove the <style> tags module.hot.dispose(function() { update(); }); } /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(3)(); // imports // module exports.push([module.id, ".fa-play, .fa-pause {\n background: -webkit-linear-gradient(left, #ff5f6d, #2b2b2b);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n transition: 0.2s ease;\n -moz-transition: 0.2s ease;\n -webkit-transition: 0.2s ease;\n}\n\n.fa-play:hover, .fa-pause:hover {\n opacity: 0.5;\n}\n\n.riverine-player,.riverine-audio {\n width: 100%;\n margin: 25px auto;\n}\n\n.riverine-gui {\n position: relative;\n overflow: hidden;\n margin-top: 10px;\n}\n\n.riverine-seek-bar, .riverine-play-bar {\n max-width: 100%;\n}\n\n.riverine-controls {\n padding: 0;\n margin: 0;\n list-style: none;\n font-family: \"FontAwesome\";\n}\n\n.riverine-controls li {\n display: inline;\n}\n\n.riverine-controls a {\n color: rgba(0, 0, 0, 0.6);\n}\n\n.riverine-play,.riverine-pause {\n width: 14px;\n height: 59px;\n display: inline-block;\n line-height: 59px;\n cursor: pointer;\n}\n\n.riverine-play i {\n transition: 0.2s ease;\n -moz-transition: 0.2s ease;\n -webkit-transition: 0.2s ease;\n}\n\n.riverine-seek-bar {\n width: 0;\n top: 1px;\n height: 2px;\n background-color: rgba(255,255,255,.5);\n}\n\n.riverine-title ul, .riverine-time-holder {\n font-family: 'Ubuntu Mono', monospace;\n color: rgba(0, 0, 0, 0.6);\n font-size: 16px;\n line-height: 30px;\n position: absolute;\n top: 14px;\n pointer-events: none;\n}\n\n.riverine-time-holder {\n right: 15px;\n}\n\n.riverine-title ul {\n left: 35px;\n list-style: none;\n}\n\n.riverine-progress {\n overflow: hidden;\n position: absolute;\n left: 20px;\n top: 0;\n width: calc(100% - 150px);\n cursor: pointer;\n background-color: rgba(0, 0, 0, 0.3);\n height: 2px;\n margin-top: 28px;\n}\n\n.riverine-play-bar {\n width: 0;\n top: 1px;\n height: 2px;\n background-color: #f2f2f2;\n transition: 0.1s ease;\n}\n\n@media (max-width: 1150px) {\n .riverine-title ul {\n font-size: 10px;\n }\n}\n", ""]); // exports /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(8); /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var ReactChildren = __webpack_require__(11); var ReactComponent = __webpack_require__(24); var ReactPureComponent = __webpack_require__(27); var ReactClass = __webpack_require__(28); var ReactDOMFactories = __webpack_require__(30); var ReactElement = __webpack_require__(15); var ReactPropTypes = __webpack_require__(35); var ReactVersion = __webpack_require__(36); var onlyChild = __webpack_require__(37); var warning = __webpack_require__(17); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if (process.env.NODE_ENV !== 'production') { var ReactElementValidator = __webpack_require__(31); createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var __spread = _assign; if (process.env.NODE_ENV !== 'production') { var warned = false; __spread = function () { process.env.NODE_ENV !== 'production' ? warning(warned, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See https://fb.me/react-spread-deprecation for more details.') : void 0; warned = true; return _assign.apply(null, arguments); }; } var React = { // Modern Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, toArray: ReactChildren.toArray, only: onlyChild }, Component: ReactComponent, PureComponent: ReactPureComponent, createElement: createElement, cloneElement: cloneElement, isValidElement: ReactElement.isValidElement, // Classic PropTypes: ReactPropTypes, createClass: ReactClass.createClass, createFactory: createFactory, createMixin: function (mixin) { // Currently a noop. Will be used to validate and trace mixins. return mixin; }, // This looks DOM specific but these are actually isomorphic helpers // since they are just generating DOM strings. DOM: ReactDOMFactories, version: ReactVersion, // Deprecated hook for JSX spread, don't use this for anything. __spread: __spread }; module.exports = React; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 9 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 10 */ /***/ function(module, exports) { /* object-assign (c) Sindre Sorhus @license MIT */ 'use strict'; /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var PooledClass = __webpack_require__(12); var ReactElement = __webpack_require__(15); var emptyFunction = __webpack_require__(18); var traverseAllChildren = __webpack_require__(21); var twoArgumentPooler = PooledClass.twoArgumentPooler; var fourArgumentPooler = PooledClass.fourArgumentPooler; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/'); } /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.func = forEachFunction; this.context = forEachContext; this.count = 0; } ForEachBookKeeping.prototype.destructor = function () { this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func, context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) { this.result = mapResult; this.keyPrefix = keyPrefix; this.func = mapFunction; this.context = mapContext; this.count = 0; } MapBookKeeping.prototype.destructor = function () { this.result = null; this.keyPrefix = null; this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result, keyPrefix = bookKeeping.keyPrefix, func = bookKeeping.func, context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument); } else if (mappedChild != null) { if (ReactElement.isValidElement(mappedChild)) { mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.map * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } function forEachSingleChildDummy(traverseContext, child, name) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.count * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument); return result; } var ReactChildren = { forEach: forEachChildren, map: mapChildren, mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, count: countChildren, toArray: toArray }; module.exports = ReactChildren; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(13); var invariant = __webpack_require__(14); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances. * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { // Casting as any so that flow ignores the actual implementation and trusts // it to match the type we declared var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler }; module.exports = PooledClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 13 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * WARNING: DO NOT manually require this module. * This is a replacement for `invariant(...)` used by the error code system * and will _only_ be required by the corresponding babel pass. * It always throws. */ function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; } module.exports = reactProdInvariant; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if (process.env.NODE_ENV !== 'production') { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var ReactCurrentOwner = __webpack_require__(16); var warning = __webpack_require__(17); var canDefineProperty = __webpack_require__(19); var hasOwnProperty = Object.prototype.hasOwnProperty; var REACT_ELEMENT_TYPE = __webpack_require__(20); var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown; function hasValidRef(config) { if (process.env.NODE_ENV !== 'production') { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { if (process.env.NODE_ENV !== 'production') { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; process.env.NODE_ENV !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0; } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; process.env.NODE_ENV !== 'production' ? warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0; } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, no instanceof check * will work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allow us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; if (process.env.NODE_ENV !== 'production') { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. if (canDefineProperty) { Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); } else { element._store.validated = false; element._self = self; element._source = source; } if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createelement */ ReactElement.createElement = function (type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; } if (hasValidKey(config)) { key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } if (process.env.NODE_ENV !== 'production') { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if (process.env.NODE_ENV !== 'production') { if (key || ref) { if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); }; /** * Return a function that produces ReactElements of a given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory */ ReactElement.createFactory = function (type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. `<Foo />.type === Foo`. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceKey = function (oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; }; /** * Clone and return a new ReactElement using element as the starting point. * See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement */ ReactElement.cloneElement = function (element, config, children) { var propName; // Original props are copied var props = _assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { key = '' + config.key; } // Remaining properties override existing props var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); }; /** * Verifies the object is a ReactElement. * See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function (object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; module.exports = ReactElement; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 16 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyFunction = __webpack_require__(18); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if (process.env.NODE_ENV !== 'production') { (function () { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; })(); } module.exports = warning; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 18 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var canDefineProperty = false; if (process.env.NODE_ENV !== 'production') { try { // $FlowFixMe https://github.com/facebook/flow/issues/285 Object.defineProperty({}, 'x', { get: function () {} }); canDefineProperty = true; } catch (x) { // IE will fail on defineProperty } } module.exports = canDefineProperty; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 20 */ /***/ function(module, exports) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; module.exports = REACT_ELEMENT_TYPE; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(13); var ReactCurrentOwner = __webpack_require__(16); var REACT_ELEMENT_TYPE = __webpack_require__(20); var getIteratorFn = __webpack_require__(22); var invariant = __webpack_require__(14); var KeyEscapeUtils = __webpack_require__(23); var warning = __webpack_require__(17); var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * This is inlined from ReactElement since this file is shared between * isomorphic and renderers. We could extract this to a * */ /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || // The following is inlined from ReactElement. This means we can optimize // some checks. React Fiber also inlines this logic for similar purposes. type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if (process.env.NODE_ENV !== 'production') { var mapsAsChildrenAddendum = ''; if (ReactCurrentOwner.current) { var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName(); if (mapsAsChildrenOwnerName) { mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.'; } } process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if (process.env.NODE_ENV !== 'production') { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 22 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; /***/ }, /* 23 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; module.exports = KeyEscapeUtils; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(13); var ReactNoopUpdateQueue = __webpack_require__(25); var canDefineProperty = __webpack_require__(19); var emptyObject = __webpack_require__(26); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } ReactComponent.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ ReactComponent.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0; this.updater.enqueueSetState(this, partialState); if (callback) { this.updater.enqueueCallback(this, callback, 'setState'); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this); if (callback) { this.updater.enqueueCallback(this, callback, 'forceUpdate'); } }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if (process.env.NODE_ENV !== 'production') { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { if (canDefineProperty) { Object.defineProperty(ReactComponent.prototype, methodName, { get: function () { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : void 0; return undefined; } }); } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } module.exports = ReactComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var warning = __webpack_require__(17); function warnNoop(publicInstance, callerName) { if (process.env.NODE_ENV !== 'production') { var constructor = publicInstance.constructor; process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function (publicInstance, callback) {}, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { warnNoop(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { warnNoop(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { warnNoop(publicInstance, 'setState'); } }; module.exports = ReactNoopUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyObject = {}; if (process.env.NODE_ENV !== 'production') { Object.freeze(emptyObject); } module.exports = emptyObject; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var ReactComponent = __webpack_require__(24); var ReactNoopUpdateQueue = __webpack_require__(25); var emptyObject = __webpack_require__(26); /** * Base class helpers for the updating state of a component. */ function ReactPureComponent(props, context, updater) { // Duplicated from ReactComponent. this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } function ComponentDummy() {} ComponentDummy.prototype = ReactComponent.prototype; ReactPureComponent.prototype = new ComponentDummy(); ReactPureComponent.prototype.constructor = ReactPureComponent; // Avoid an extra prototype jump for these methods. _assign(ReactPureComponent.prototype, ReactComponent.prototype); ReactPureComponent.prototype.isPureReactComponent = true; module.exports = ReactPureComponent; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(13), _assign = __webpack_require__(10); var ReactComponent = __webpack_require__(24); var ReactElement = __webpack_require__(15); var ReactPropTypeLocationNames = __webpack_require__(29); var ReactNoopUpdateQueue = __webpack_require__(25); var emptyObject = __webpack_require__(26); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); var MIXINS_KEY = 'mixins'; // Helper function to allow the creation of anonymous functions which do not // have .name set to the name of the variable being assigned to. function identity(fn) { return fn; } /** * Policies that describe methods in `ReactClassInterface`. */ var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or host components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: 'DEFINE_MANY', /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: 'DEFINE_MANY', /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: 'DEFINE_MANY', /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: 'DEFINE_MANY', /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: 'DEFINE_MANY', // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: 'DEFINE_MANY_MERGED', /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: 'DEFINE_MANY_MERGED', /** * @return {object} * @optional */ getChildContext: 'DEFINE_MANY_MERGED', /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: 'DEFINE_ONCE', // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: 'DEFINE_MANY', /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: 'DEFINE_MANY', /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: 'DEFINE_MANY', /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: 'DEFINE_ONCE', /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: 'DEFINE_MANY', /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: 'DEFINE_MANY', /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: 'DEFINE_MANY', // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: 'OVERRIDE_BASE' }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function (Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function (Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function (Constructor, childContextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, childContextTypes, 'childContext'); } Constructor.childContextTypes = _assign({}, Constructor.childContextTypes, childContextTypes); }, contextTypes: function (Constructor, contextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, contextTypes, 'context'); } Constructor.contextTypes = _assign({}, Constructor.contextTypes, contextTypes); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function (Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function (Constructor, propTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, propTypes, 'prop'); } Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function (Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function () {} }; function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an invariant so components // don't show up in prod but only in __DEV__ process.env.NODE_ENV !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : void 0; } } } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { !(specPolicy === 'OVERRIDE_BASE') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.', name) : _prodInvariant('73', name) : void 0; } // Disallow defining methods more than once unless explicitly allowed. if (isAlreadyDefined) { !(specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('74', name) : void 0; } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if (process.env.NODE_ENV !== 'production') { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; process.env.NODE_ENV !== 'production' ? warning(isMixinValid, '%s: You\'re attempting to include a mixin that is either null ' + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec) : void 0; } return; } !(typeof spec !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component class or function as a mixin. Instead, just use a regular object.') : _prodInvariant('75') : void 0; !!ReactElement.isValidElement(spec) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component as a mixin. Instead, just use a regular object.') : _prodInvariant('76') : void 0; var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. !(isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.', specPolicy, name) : _prodInvariant('77', specPolicy, name) : void 0; // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === 'DEFINE_MANY_MERGED') { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === 'DEFINE_MANY') { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (process.env.NODE_ENV !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; !!isReserved ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.', name) : _prodInvariant('78', name) : void 0; var isInherited = name in Constructor; !!isInherited ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('79', name) : void 0; Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { !(one && two && typeof one === 'object' && typeof two === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : _prodInvariant('80') : void 0; for (var key in two) { if (two.hasOwnProperty(key)) { !(one[key] === undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.', key) : _prodInvariant('81', key) : void 0; one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if (process.env.NODE_ENV !== 'production') { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function (newThis) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : void 0; } else if (!args.length) { process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : void 0; return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { var pairs = component.__reactAutoBindPairs; for (var i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i]; var method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function (newState, callback) { this.updater.enqueueReplaceState(this, newState); if (callback) { this.updater.enqueueCallback(this, callback, 'replaceState'); } }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function () { return this.updater.isMounted(this); } }; var ReactClassComponent = function () {}; _assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); /** * Module for creating composite components. * * @class ReactClass */ var ReactClass = { /** * Creates a composite component class given a class specification. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function (spec) { // To keep our warnings more understandable, we'll use a little hack here to // ensure that Constructor.name !== 'Constructor'. This makes sure we don't // unnecessarily identify a class without displayName as 'Constructor'. var Constructor = identity(function (props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : void 0; } // Wire up auto-binding if (this.__reactAutoBindPairs.length) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (initialState === undefined && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : _prodInvariant('82', Constructor.displayName || 'ReactCompositeComponent') : void 0; this.state = initialState; }); Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; Constructor.prototype.__reactAutoBindPairs = []; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if (process.env.NODE_ENV !== 'production') { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } !Constructor.prototype.render ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : _prodInvariant('83') : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : void 0; } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; }, injection: { injectMixin: function (mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypeLocationNames = {}; if (process.env.NODE_ENV !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactElement = __webpack_require__(15); /** * Create a factory that creates HTML tag elements. * * @private */ var createDOMFactory = ReactElement.createFactory; if (process.env.NODE_ENV !== 'production') { var ReactElementValidator = __webpack_require__(31); createDOMFactory = ReactElementValidator.createFactory; } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOMFactories = { a: createDOMFactory('a'), abbr: createDOMFactory('abbr'), address: createDOMFactory('address'), area: createDOMFactory('area'), article: createDOMFactory('article'), aside: createDOMFactory('aside'), audio: createDOMFactory('audio'), b: createDOMFactory('b'), base: createDOMFactory('base'), bdi: createDOMFactory('bdi'), bdo: createDOMFactory('bdo'), big: createDOMFactory('big'), blockquote: createDOMFactory('blockquote'), body: createDOMFactory('body'), br: createDOMFactory('br'), button: createDOMFactory('button'), canvas: createDOMFactory('canvas'), caption: createDOMFactory('caption'), cite: createDOMFactory('cite'), code: createDOMFactory('code'), col: createDOMFactory('col'), colgroup: createDOMFactory('colgroup'), data: createDOMFactory('data'), datalist: createDOMFactory('datalist'), dd: createDOMFactory('dd'), del: createDOMFactory('del'), details: createDOMFactory('details'), dfn: createDOMFactory('dfn'), dialog: createDOMFactory('dialog'), div: createDOMFactory('div'), dl: createDOMFactory('dl'), dt: createDOMFactory('dt'), em: createDOMFactory('em'), embed: createDOMFactory('embed'), fieldset: createDOMFactory('fieldset'), figcaption: createDOMFactory('figcaption'), figure: createDOMFactory('figure'), footer: createDOMFactory('footer'), form: createDOMFactory('form'), h1: createDOMFactory('h1'), h2: createDOMFactory('h2'), h3: createDOMFactory('h3'), h4: createDOMFactory('h4'), h5: createDOMFactory('h5'), h6: createDOMFactory('h6'), head: createDOMFactory('head'), header: createDOMFactory('header'), hgroup: createDOMFactory('hgroup'), hr: createDOMFactory('hr'), html: createDOMFactory('html'), i: createDOMFactory('i'), iframe: createDOMFactory('iframe'), img: createDOMFactory('img'), input: createDOMFactory('input'), ins: createDOMFactory('ins'), kbd: createDOMFactory('kbd'), keygen: createDOMFactory('keygen'), label: createDOMFactory('label'), legend: createDOMFactory('legend'), li: createDOMFactory('li'), link: createDOMFactory('link'), main: createDOMFactory('main'), map: createDOMFactory('map'), mark: createDOMFactory('mark'), menu: createDOMFactory('menu'), menuitem: createDOMFactory('menuitem'), meta: createDOMFactory('meta'), meter: createDOMFactory('meter'), nav: createDOMFactory('nav'), noscript: createDOMFactory('noscript'), object: createDOMFactory('object'), ol: createDOMFactory('ol'), optgroup: createDOMFactory('optgroup'), option: createDOMFactory('option'), output: createDOMFactory('output'), p: createDOMFactory('p'), param: createDOMFactory('param'), picture: createDOMFactory('picture'), pre: createDOMFactory('pre'), progress: createDOMFactory('progress'), q: createDOMFactory('q'), rp: createDOMFactory('rp'), rt: createDOMFactory('rt'), ruby: createDOMFactory('ruby'), s: createDOMFactory('s'), samp: createDOMFactory('samp'), script: createDOMFactory('script'), section: createDOMFactory('section'), select: createDOMFactory('select'), small: createDOMFactory('small'), source: createDOMFactory('source'), span: createDOMFactory('span'), strong: createDOMFactory('strong'), style: createDOMFactory('style'), sub: createDOMFactory('sub'), summary: createDOMFactory('summary'), sup: createDOMFactory('sup'), table: createDOMFactory('table'), tbody: createDOMFactory('tbody'), td: createDOMFactory('td'), textarea: createDOMFactory('textarea'), tfoot: createDOMFactory('tfoot'), th: createDOMFactory('th'), thead: createDOMFactory('thead'), time: createDOMFactory('time'), title: createDOMFactory('title'), tr: createDOMFactory('tr'), track: createDOMFactory('track'), u: createDOMFactory('u'), ul: createDOMFactory('ul'), 'var': createDOMFactory('var'), video: createDOMFactory('video'), wbr: createDOMFactory('wbr'), // SVG circle: createDOMFactory('circle'), clipPath: createDOMFactory('clipPath'), defs: createDOMFactory('defs'), ellipse: createDOMFactory('ellipse'), g: createDOMFactory('g'), image: createDOMFactory('image'), line: createDOMFactory('line'), linearGradient: createDOMFactory('linearGradient'), mask: createDOMFactory('mask'), path: createDOMFactory('path'), pattern: createDOMFactory('pattern'), polygon: createDOMFactory('polygon'), polyline: createDOMFactory('polyline'), radialGradient: createDOMFactory('radialGradient'), rect: createDOMFactory('rect'), stop: createDOMFactory('stop'), svg: createDOMFactory('svg'), text: createDOMFactory('text'), tspan: createDOMFactory('tspan') }; module.exports = ReactDOMFactories; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ 'use strict'; var ReactCurrentOwner = __webpack_require__(16); var ReactComponentTreeHook = __webpack_require__(32); var ReactElement = __webpack_require__(15); var checkReactTypeSpec = __webpack_require__(33); var canDefineProperty = __webpack_require__(19); var getIteratorFn = __webpack_require__(22); var warning = __webpack_require__(17); function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = ' Check the top-level render call using <' + parentName + '>.'; } } return info; } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var memoizer = ownerHasKeyUseWarning.uniqueKey || (ownerHasKeyUseWarning.uniqueKey = {}); var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (memoizer[currentComponentErrorInfo]) { return; } memoizer[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; } process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.%s', currentComponentErrorInfo, childOwner, ReactComponentTreeHook.getCurrentStackAddendum(element)) : void 0; } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); // Entry iterators provide implicit keys. if (iteratorFn) { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (ReactElement.isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { var componentClass = element.type; if (typeof componentClass !== 'function') { return; } var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkReactTypeSpec(componentClass.propTypes, element.props, 'prop', name, element, null); } if (typeof componentClass.getDefaultProps === 'function') { process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0; } } var ReactElementValidator = { createElement: function (type, props, children) { var validType = typeof type === 'string' || typeof type === 'function'; // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { if (typeof type !== 'function' && typeof type !== 'string') { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + 'it\'s defined in.'; } info += getDeclarationErrorAddendum(); process.env.NODE_ENV !== 'production' ? warning(false, 'React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', type == null ? type : typeof type, info) : void 0; } } var element = ReactElement.createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } validatePropTypes(element); return element; }, createFactory: function (type) { var validatedFactory = ReactElementValidator.createElement.bind(null, type); // Legacy hook TODO: Warn if this is accessed validatedFactory.type = type; if (process.env.NODE_ENV !== 'production') { if (canDefineProperty) { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { process.env.NODE_ENV !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : void 0; Object.defineProperty(this, 'type', { value: type }); return type; } }); } } return validatedFactory; }, cloneElement: function (element, props, children) { var newElement = ReactElement.cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } }; module.exports = ReactElementValidator; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(13); var ReactCurrentOwner = __webpack_require__(16); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); function isNative(fn) { // Based on isNative() from Lodash var funcToString = Function.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var reIsNative = RegExp('^' + funcToString // Take an example native function source for comparison .call(hasOwnProperty) // Strip regex characters so we can use it for regex .replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') // Remove hasOwnProperty from the template to make it generic .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'); try { var source = funcToString.call(fn); return reIsNative.test(source); } catch (err) { return false; } } var canUseCollections = // Array.from typeof Array.from === 'function' && // Map typeof Map === 'function' && isNative(Map) && // Map.prototype.keys Map.prototype != null && typeof Map.prototype.keys === 'function' && isNative(Map.prototype.keys) && // Set typeof Set === 'function' && isNative(Set) && // Set.prototype.keys Set.prototype != null && typeof Set.prototype.keys === 'function' && isNative(Set.prototype.keys); var setItem; var getItem; var removeItem; var getItemIDs; var addRoot; var removeRoot; var getRootIDs; if (canUseCollections) { var itemMap = new Map(); var rootIDSet = new Set(); setItem = function (id, item) { itemMap.set(id, item); }; getItem = function (id) { return itemMap.get(id); }; removeItem = function (id) { itemMap['delete'](id); }; getItemIDs = function () { return Array.from(itemMap.keys()); }; addRoot = function (id) { rootIDSet.add(id); }; removeRoot = function (id) { rootIDSet['delete'](id); }; getRootIDs = function () { return Array.from(rootIDSet.keys()); }; } else { var itemByKey = {}; var rootByKey = {}; // Use non-numeric keys to prevent V8 performance issues: // https://github.com/facebook/react/pull/7232 var getKeyFromID = function (id) { return '.' + id; }; var getIDFromKey = function (key) { return parseInt(key.substr(1), 10); }; setItem = function (id, item) { var key = getKeyFromID(id); itemByKey[key] = item; }; getItem = function (id) { var key = getKeyFromID(id); return itemByKey[key]; }; removeItem = function (id) { var key = getKeyFromID(id); delete itemByKey[key]; }; getItemIDs = function () { return Object.keys(itemByKey).map(getIDFromKey); }; addRoot = function (id) { var key = getKeyFromID(id); rootByKey[key] = true; }; removeRoot = function (id) { var key = getKeyFromID(id); delete rootByKey[key]; }; getRootIDs = function () { return Object.keys(rootByKey).map(getIDFromKey); }; } var unmountedIDs = []; function purgeDeep(id) { var item = getItem(id); if (item) { var childIDs = item.childIDs; removeItem(id); childIDs.forEach(purgeDeep); } } function describeComponentFrame(name, source, ownerName) { return '\n in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : ''); } function getDisplayName(element) { if (element == null) { return '#empty'; } else if (typeof element === 'string' || typeof element === 'number') { return '#text'; } else if (typeof element.type === 'string') { return element.type; } else { return element.type.displayName || element.type.name || 'Unknown'; } } function describeID(id) { var name = ReactComponentTreeHook.getDisplayName(id); var element = ReactComponentTreeHook.getElement(id); var ownerID = ReactComponentTreeHook.getOwnerID(id); var ownerName; if (ownerID) { ownerName = ReactComponentTreeHook.getDisplayName(ownerID); } process.env.NODE_ENV !== 'production' ? warning(element, 'ReactComponentTreeHook: Missing React element for debugID %s when ' + 'building stack', id) : void 0; return describeComponentFrame(name, element && element._source, ownerName); } var ReactComponentTreeHook = { onSetChildren: function (id, nextChildIDs) { var item = getItem(id); !item ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0; item.childIDs = nextChildIDs; for (var i = 0; i < nextChildIDs.length; i++) { var nextChildID = nextChildIDs[i]; var nextChild = getItem(nextChildID); !nextChild ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected hook events to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('140') : void 0; !(nextChild.childIDs != null || typeof nextChild.element !== 'object' || nextChild.element == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onSetChildren() to fire for a container child before its parent includes it in onSetChildren().') : _prodInvariant('141') : void 0; !nextChild.isMounted ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('71') : void 0; if (nextChild.parentID == null) { nextChild.parentID = id; // TODO: This shouldn't be necessary but mounting a new root during in // componentWillMount currently causes not-yet-mounted components to // be purged from our tree data so their parent id is missing. } !(nextChild.parentID === id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onBeforeMountComponent() parent and onSetChildren() to be consistent (%s has parents %s and %s).', nextChildID, nextChild.parentID, id) : _prodInvariant('142', nextChildID, nextChild.parentID, id) : void 0; } }, onBeforeMountComponent: function (id, element, parentID) { var item = { element: element, parentID: parentID, text: null, childIDs: [], isMounted: false, updateCount: 0 }; setItem(id, item); }, onBeforeUpdateComponent: function (id, element) { var item = getItem(id); if (!item || !item.isMounted) { // We may end up here as a result of setState() in componentWillUnmount(). // In this case, ignore the element. return; } item.element = element; }, onMountComponent: function (id) { var item = getItem(id); !item ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0; item.isMounted = true; var isRoot = item.parentID === 0; if (isRoot) { addRoot(id); } }, onUpdateComponent: function (id) { var item = getItem(id); if (!item || !item.isMounted) { // We may end up here as a result of setState() in componentWillUnmount(). // In this case, ignore the element. return; } item.updateCount++; }, onUnmountComponent: function (id) { var item = getItem(id); if (item) { // We need to check if it exists. // `item` might not exist if it is inside an error boundary, and a sibling // error boundary child threw while mounting. Then this instance never // got a chance to mount, but it still gets an unmounting event during // the error boundary cleanup. item.isMounted = false; var isRoot = item.parentID === 0; if (isRoot) { removeRoot(id); } } unmountedIDs.push(id); }, purgeUnmountedComponents: function () { if (ReactComponentTreeHook._preventPurging) { // Should only be used for testing. return; } for (var i = 0; i < unmountedIDs.length; i++) { var id = unmountedIDs[i]; purgeDeep(id); } unmountedIDs.length = 0; }, isMounted: function (id) { var item = getItem(id); return item ? item.isMounted : false; }, getCurrentStackAddendum: function (topElement) { var info = ''; if (topElement) { var name = getDisplayName(topElement); var owner = topElement._owner; info += describeComponentFrame(name, topElement._source, owner && owner.getName()); } var currentOwner = ReactCurrentOwner.current; var id = currentOwner && currentOwner._debugID; info += ReactComponentTreeHook.getStackAddendumByID(id); return info; }, getStackAddendumByID: function (id) { var info = ''; while (id) { info += describeID(id); id = ReactComponentTreeHook.getParentID(id); } return info; }, getChildIDs: function (id) { var item = getItem(id); return item ? item.childIDs : []; }, getDisplayName: function (id) { var element = ReactComponentTreeHook.getElement(id); if (!element) { return null; } return getDisplayName(element); }, getElement: function (id) { var item = getItem(id); return item ? item.element : null; }, getOwnerID: function (id) { var element = ReactComponentTreeHook.getElement(id); if (!element || !element._owner) { return null; } return element._owner._debugID; }, getParentID: function (id) { var item = getItem(id); return item ? item.parentID : null; }, getSource: function (id) { var item = getItem(id); var element = item ? item.element : null; var source = element != null ? element._source : null; return source; }, getText: function (id) { var element = ReactComponentTreeHook.getElement(id); if (typeof element === 'string') { return element; } else if (typeof element === 'number') { return '' + element; } else { return null; } }, getUpdateCount: function (id) { var item = getItem(id); return item ? item.updateCount : 0; }, getRootIDs: getRootIDs, getRegisteredIDs: getItemIDs }; module.exports = ReactComponentTreeHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(13); var ReactPropTypeLocationNames = __webpack_require__(29); var ReactPropTypesSecret = __webpack_require__(34); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = __webpack_require__(32); } var loggedTypeFailures = {}; /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?object} element The React element that is being type-checked * @param {?number} debugID The React component instance that is being type-checked * @private */ function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof typeSpecs[typeSpecName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0; error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var componentStackInfo = ''; if (process.env.NODE_ENV !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = __webpack_require__(32); } if (debugID !== null) { componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID); } else if (element !== null) { componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element); } } process.env.NODE_ENV !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0; } } } } module.exports = checkReactTypeSpec; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 34 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactElement = __webpack_require__(15); var ReactPropTypeLocationNames = __webpack_require__(29); var ReactPropTypesSecret = __webpack_require__(34); var emptyFunction = __webpack_require__(18); var getIteratorFn = __webpack_require__(22); var warning = __webpack_require__(17); /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (process.env.NODE_ENV !== 'production') { var manualPropTypeCallCache = {}; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (process.env.NODE_ENV !== 'production') { if (secret !== ReactPropTypesSecret && typeof console !== 'undefined') { var cacheKey = componentName + ':' + propName; if (!manualPropTypeCallCache[cacheKey]) { process.env.NODE_ENV !== 'production' ? warning(false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will not work in production with the next major version. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName) : void 0; manualPropTypeCallCache[cacheKey] = true; } } } if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + locationName + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + locationName + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var locationName = ReactPropTypeLocationNames[location]; // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturns(null)); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!ReactElement.isValidElement(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var locationName = ReactPropTypeLocationNames[location]; var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var locationName = ReactPropTypeLocationNames[location]; var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || ReactElement.isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } module.exports = ReactPropTypes; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 36 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; module.exports = '15.4.2'; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(13); var ReactElement = __webpack_require__(15); var invariant = __webpack_require__(14); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.only * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { !ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React.Children.only expected to receive a single React element child.') : _prodInvariant('143') : void 0; return children; } module.exports = onlyChild; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(39); /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ 'use strict'; var ReactDOMComponentTree = __webpack_require__(40); var ReactDefaultInjection = __webpack_require__(44); var ReactMount = __webpack_require__(172); var ReactReconciler = __webpack_require__(65); var ReactUpdates = __webpack_require__(62); var ReactVersion = __webpack_require__(177); var findDOMNode = __webpack_require__(178); var getHostComponentFromComposite = __webpack_require__(179); var renderSubtreeIntoContainer = __webpack_require__(180); var warning = __webpack_require__(17); ReactDefaultInjection.inject(); var ReactDOM = { findDOMNode: findDOMNode, render: ReactMount.render, unmountComponentAtNode: ReactMount.unmountComponentAtNode, version: ReactVersion, /* eslint-disable camelcase */ unstable_batchedUpdates: ReactUpdates.batchedUpdates, unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ ComponentTree: { getClosestInstanceFromNode: ReactDOMComponentTree.getClosestInstanceFromNode, getNodeFromInstance: function (inst) { // inst is an internal instance (but could be a composite) if (inst._renderedComponent) { inst = getHostComponentFromComposite(inst); } if (inst) { return ReactDOMComponentTree.getNodeFromInstance(inst); } else { return null; } } }, Mount: ReactMount, Reconciler: ReactReconciler }); } if (process.env.NODE_ENV !== 'production') { var ExecutionEnvironment = __webpack_require__(54); if (ExecutionEnvironment.canUseDOM && window.top === window.self) { // First check if devtools is not installed if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { // If we're in Chrome or Firefox, provide a download link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { // Firefox does not have the issue with devtools loaded over file:// var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 && navigator.userAgent.indexOf('Firefox') === -1; console.debug('Download the React DevTools ' + (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') + 'for a better development experience: ' + 'https://fb.me/react-devtools'); } } var testFunc = function testFn() {}; process.env.NODE_ENV !== 'production' ? warning((testFunc.name || testFunc.toString()).indexOf('testFn') !== -1, 'It looks like you\'re using a minified copy of the development build ' + 'of React. When deploying React apps to production, make sure to use ' + 'the production build which skips development warnings and is faster. ' + 'See https://fb.me/react-minification for more details.') : void 0; // If we're in IE8, check to see if we are in compatibility mode and provide // information on preventing compatibility mode var ieCompatibilityMode = document.documentMode && document.documentMode < 8; process.env.NODE_ENV !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : void 0; var expectedFeatures = [ // shims Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.trim]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { process.env.NODE_ENV !== 'production' ? warning(false, 'One or more ES5 shims expected by React are not available: ' + 'https://fb.me/react-warning-polyfills') : void 0; break; } } } } if (process.env.NODE_ENV !== 'production') { var ReactInstrumentation = __webpack_require__(68); var ReactDOMUnknownPropertyHook = __webpack_require__(181); var ReactDOMNullInputValuePropHook = __webpack_require__(182); var ReactDOMInvalidARIAHook = __webpack_require__(183); ReactInstrumentation.debugTool.addHook(ReactDOMUnknownPropertyHook); ReactInstrumentation.debugTool.addHook(ReactDOMNullInputValuePropHook); ReactInstrumentation.debugTool.addHook(ReactDOMInvalidARIAHook); } module.exports = ReactDOM; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var DOMProperty = __webpack_require__(42); var ReactDOMComponentFlags = __webpack_require__(43); var invariant = __webpack_require__(14); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var Flags = ReactDOMComponentFlags; var internalInstanceKey = '__reactInternalInstance$' + Math.random().toString(36).slice(2); /** * Check if a given node should be cached. */ function shouldPrecacheNode(node, nodeID) { return node.nodeType === 1 && node.getAttribute(ATTR_NAME) === String(nodeID) || node.nodeType === 8 && node.nodeValue === ' react-text: ' + nodeID + ' ' || node.nodeType === 8 && node.nodeValue === ' react-empty: ' + nodeID + ' '; } /** * Drill down (through composites and empty components) until we get a host or * host text component. * * This is pretty polymorphic but unavoidable with the current structure we have * for `_renderedChildren`. */ function getRenderedHostOrTextFromComponent(component) { var rendered; while (rendered = component._renderedComponent) { component = rendered; } return component; } /** * Populate `_hostNode` on the rendered host/text component with the given * DOM node. The passed `inst` can be a composite. */ function precacheNode(inst, node) { var hostInst = getRenderedHostOrTextFromComponent(inst); hostInst._hostNode = node; node[internalInstanceKey] = hostInst; } function uncacheNode(inst) { var node = inst._hostNode; if (node) { delete node[internalInstanceKey]; inst._hostNode = null; } } /** * Populate `_hostNode` on each child of `inst`, assuming that the children * match up with the DOM (element) children of `node`. * * We cache entire levels at once to avoid an n^2 problem where we access the * children of a node sequentially and have to walk from the start to our target * node every time. * * Since we update `_renderedChildren` and the actual DOM at (slightly) * different times, we could race here and see a newer `_renderedChildren` than * the DOM nodes we see. To avoid this, ReactMultiChild calls * `prepareToManageChildren` before we change `_renderedChildren`, at which * time the container's child nodes are always cached (until it unmounts). */ function precacheChildNodes(inst, node) { if (inst._flags & Flags.hasCachedChildNodes) { return; } var children = inst._renderedChildren; var childNode = node.firstChild; outer: for (var name in children) { if (!children.hasOwnProperty(name)) { continue; } var childInst = children[name]; var childID = getRenderedHostOrTextFromComponent(childInst)._domID; if (childID === 0) { // We're currently unmounting this child in ReactMultiChild; skip it. continue; } // We assume the child nodes are in the same order as the child instances. for (; childNode !== null; childNode = childNode.nextSibling) { if (shouldPrecacheNode(childNode, childID)) { precacheNode(childInst, childNode); continue outer; } } // We reached the end of the DOM children without finding an ID match. true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unable to find element with ID %s.', childID) : _prodInvariant('32', childID) : void 0; } inst._flags |= Flags.hasCachedChildNodes; } /** * Given a DOM node, return the closest ReactDOMComponent or * ReactDOMTextComponent instance ancestor. */ function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) { return node[internalInstanceKey]; } // Walk up the tree until we find an ancestor whose instance we have cached. var parents = []; while (!node[internalInstanceKey]) { parents.push(node); if (node.parentNode) { node = node.parentNode; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; } } var closest; var inst; for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) { closest = inst; if (parents.length) { precacheChildNodes(inst, node); } } return closest; } /** * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent * instance, or null if the node was not rendered by this React. */ function getInstanceFromNode(node) { var inst = getClosestInstanceFromNode(node); if (inst != null && inst._hostNode === node) { return inst; } else { return null; } } /** * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding * DOM node. */ function getNodeFromInstance(inst) { // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. !(inst._hostNode !== undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; if (inst._hostNode) { return inst._hostNode; } // Walk up the tree until we find an ancestor whose DOM node we have cached. var parents = []; while (!inst._hostNode) { parents.push(inst); !inst._hostParent ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React DOM tree root should always have a node reference.') : _prodInvariant('34') : void 0; inst = inst._hostParent; } // Now parents contains each ancestor that does *not* have a cached native // node, and `inst` is the deepest ancestor that does. for (; parents.length; inst = parents.pop()) { precacheChildNodes(inst, inst._hostNode); } return inst._hostNode; } var ReactDOMComponentTree = { getClosestInstanceFromNode: getClosestInstanceFromNode, getInstanceFromNode: getInstanceFromNode, getNodeFromInstance: getNodeFromInstance, precacheChildNodes: precacheChildNodes, precacheNode: precacheNode, uncacheNode: uncacheNode }; module.exports = ReactDOMComponentTree; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 41 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * WARNING: DO NOT manually require this module. * This is a replacement for `invariant(...)` used by the error code system * and will _only_ be required by the corresponding babel pass. * It always throws. */ function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; } module.exports = reactProdInvariant; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_PROPERTY: 0x1, HAS_BOOLEAN_VALUE: 0x4, HAS_NUMERIC_VALUE: 0x8, HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8, HAS_OVERLOADED_BOOLEAN_VALUE: 0x20, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMAttributeNamespaces: object mapping React attribute name to the DOM * attribute namespace URL. (Attribute names not specified use no namespace.) * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function (domPropertyConfig) { var Injection = DOMPropertyInjection; var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute); } for (var propName in Properties) { !!DOMProperty.properties.hasOwnProperty(propName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property \'%s\' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.', propName) : _prodInvariant('48', propName) : void 0; var lowerCased = propName.toLowerCase(); var propConfig = Properties[propName]; var propertyInfo = { attributeName: lowerCased, attributeNamespace: null, propertyName: propName, mutationMethod: null, mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) }; !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s', propName) : _prodInvariant('50', propName) : void 0; if (process.env.NODE_ENV !== 'production') { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; if (process.env.NODE_ENV !== 'production') { DOMProperty.getPossibleStandardName[attributeName] = propName; } } if (DOMAttributeNamespaces.hasOwnProperty(propName)) { propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; } if (DOMPropertyNames.hasOwnProperty(propName)) { propertyInfo.propertyName = DOMPropertyNames[propName]; } if (DOMMutationMethods.hasOwnProperty(propName)) { propertyInfo.mutationMethod = DOMMutationMethods[propName]; } DOMProperty.properties[propName] = propertyInfo; } } }; /* eslint-disable max-len */ var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; /* eslint-enable max-len */ /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', ROOT_ATTRIBUTE_NAME: 'data-reactroot', ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR, ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040', /** * Map from property "standard name" to an object with info about how to set * the property in the DOM. Each object contains: * * attributeName: * Used when rendering markup or with `*Attribute()`. * attributeNamespace * propertyName: * Used on DOM node instances. (This includes properties that mutate due to * external factors.) * mutationMethod: * If non-null, used instead of the property or `setAttribute()` after * initial render. * mustUseProperty: * Whether the property must be accessed and mutated as an object property. * hasBooleanValue: * Whether the property should be removed when set to a falsey value. * hasNumericValue: * Whether the property must be numeric or parse as a numeric and should be * removed when set to a falsey value. * hasPositiveNumericValue: * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * hasOverloadedBooleanValue: * Whether the property can be used as a flag as well as with a value. * Removed when strictly equal to false; present without a value when * strictly equal to true; present with a value otherwise. */ properties: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. Available only in __DEV__. * * autofocus is predefined, because adding it to the property whitelist * causes unintended side effects. * * @type {Object} */ getPossibleStandardName: process.env.NODE_ENV !== 'production' ? { autofocus: 'autoFocus' } : null, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function (attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 43 */ /***/ function(module, exports) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMComponentFlags = { hasCachedChildNodes: 1 << 0 }; module.exports = ReactDOMComponentFlags; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ARIADOMPropertyConfig = __webpack_require__(45); var BeforeInputEventPlugin = __webpack_require__(46); var ChangeEventPlugin = __webpack_require__(61); var DefaultEventPluginOrder = __webpack_require__(78); var EnterLeaveEventPlugin = __webpack_require__(79); var HTMLDOMPropertyConfig = __webpack_require__(84); var ReactComponentBrowserEnvironment = __webpack_require__(85); var ReactDOMComponent = __webpack_require__(98); var ReactDOMComponentTree = __webpack_require__(40); var ReactDOMEmptyComponent = __webpack_require__(143); var ReactDOMTreeTraversal = __webpack_require__(144); var ReactDOMTextComponent = __webpack_require__(145); var ReactDefaultBatchingStrategy = __webpack_require__(146); var ReactEventListener = __webpack_require__(147); var ReactInjection = __webpack_require__(150); var ReactReconcileTransaction = __webpack_require__(151); var SVGDOMPropertyConfig = __webpack_require__(159); var SelectEventPlugin = __webpack_require__(160); var SimpleEventPlugin = __webpack_require__(161); var alreadyInjected = false; function inject() { if (alreadyInjected) { // TODO: This is currently true because these injections are shared between // the client and the server package. They should be built independently // and not share any injection state. Then this problem will be solved. return; } alreadyInjected = true; ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginUtils.injectComponentTree(ReactDOMComponentTree); ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.HostComponent.injectGenericComponentClass(ReactDOMComponent); ReactInjection.HostComponent.injectTextComponentClass(ReactDOMTextComponent); ReactInjection.DOMProperty.injectDOMPropertyConfig(ARIADOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponentFactory(function (instantiate) { return new ReactDOMEmptyComponent(instantiate); }); ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction); ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); } module.exports = { inject: inject }; /***/ }, /* 45 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ARIADOMPropertyConfig = { Properties: { // Global States and Properties 'aria-current': 0, // state 'aria-details': 0, 'aria-disabled': 0, // state 'aria-hidden': 0, // state 'aria-invalid': 0, // state 'aria-keyshortcuts': 0, 'aria-label': 0, 'aria-roledescription': 0, // Widget Attributes 'aria-autocomplete': 0, 'aria-checked': 0, 'aria-expanded': 0, 'aria-haspopup': 0, 'aria-level': 0, 'aria-modal': 0, 'aria-multiline': 0, 'aria-multiselectable': 0, 'aria-orientation': 0, 'aria-placeholder': 0, 'aria-pressed': 0, 'aria-readonly': 0, 'aria-required': 0, 'aria-selected': 0, 'aria-sort': 0, 'aria-valuemax': 0, 'aria-valuemin': 0, 'aria-valuenow': 0, 'aria-valuetext': 0, // Live Region Attributes 'aria-atomic': 0, 'aria-busy': 0, 'aria-live': 0, 'aria-relevant': 0, // Drag-and-Drop Attributes 'aria-dropeffect': 0, 'aria-grabbed': 0, // Relationship Attributes 'aria-activedescendant': 0, 'aria-colcount': 0, 'aria-colindex': 0, 'aria-colspan': 0, 'aria-controls': 0, 'aria-describedby': 0, 'aria-errormessage': 0, 'aria-flowto': 0, 'aria-labelledby': 0, 'aria-owns': 0, 'aria-posinset': 0, 'aria-rowcount': 0, 'aria-rowindex': 0, 'aria-rowspan': 0, 'aria-setsize': 0 }, DOMAttributeNames: {}, DOMPropertyNames: {} }; module.exports = ARIADOMPropertyConfig; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPropagators = __webpack_require__(47); var ExecutionEnvironment = __webpack_require__(54); var FallbackCompositionState = __webpack_require__(55); var SyntheticCompositionEvent = __webpack_require__(58); var SyntheticInputEvent = __webpack_require__(60); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window; var documentMode = null; if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto(); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: 'onBeforeInput', captured: 'onBeforeInputCapture' }, dependencies: ['topCompositionEnd', 'topKeyPress', 'topTextInput', 'topPaste'] }, compositionEnd: { phasedRegistrationNames: { bubbled: 'onCompositionEnd', captured: 'onCompositionEndCapture' }, dependencies: ['topBlur', 'topCompositionEnd', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] }, compositionStart: { phasedRegistrationNames: { bubbled: 'onCompositionStart', captured: 'onCompositionStartCapture' }, dependencies: ['topBlur', 'topCompositionStart', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] }, compositionUpdate: { phasedRegistrationNames: { bubbled: 'onCompositionUpdate', captured: 'onCompositionUpdateCapture' }, dependencies: ['topBlur', 'topCompositionUpdate', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] } }; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey); } /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case 'topCompositionStart': return eventTypes.compositionStart; case 'topCompositionEnd': return eventTypes.compositionEnd; case 'topCompositionUpdate': return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionStart(topLevelType, nativeEvent) { return topLevelType === 'topKeyDown' && nativeEvent.keyCode === START_KEYCODE; } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case 'topKeyUp': // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case 'topKeyDown': // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case 'topKeyPress': case 'topMouseDown': case 'topBlur': // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } // Track the current IME composition fallback object, if any. var currentComposition = null; /** * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackCompositionStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (!eventType) { return null; } if (useFallbackCompositionData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = FallbackCompositionState.getPooled(nativeEventTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case 'topCompositionEnd': return getDataFromCustomEvent(nativeEvent); case 'topKeyPress': /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case 'topTextInput': // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. // If composition event is available, we extract a string only at // compositionevent, otherwise extract it at fallback events. if (currentComposition) { if (topLevelType === 'topCompositionEnd' || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) { var chars = currentComposition.getData(); FallbackCompositionState.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case 'topPaste': // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case 'topKeyPress': /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { return String.fromCharCode(nativeEvent.which); } return null; case 'topCompositionEnd': return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget); event.data = chars; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)]; } }; module.exports = BeforeInputEventPlugin; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPluginHub = __webpack_require__(48); var EventPluginUtils = __webpack_require__(50); var accumulateInto = __webpack_require__(52); var forEachAccumulated = __webpack_require__(53); var warning = __webpack_require__(17); var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(inst, phase, event) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(inst, 'Dispatching inst must not be null') : void 0; } var listener = listenerAtPhase(inst, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; var parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null; EventPluginUtils.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(inst, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, from, to) { EventPluginUtils.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var EventPluginRegistry = __webpack_require__(49); var EventPluginUtils = __webpack_require__(50); var ReactErrorUtils = __webpack_require__(51); var accumulateInto = __webpack_require__(52); var forEachAccumulated = __webpack_require__(53); var invariant = __webpack_require__(14); /** * Internal store for event listeners */ var listenerBank = {}; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @param {boolean} simulated If the event is simulated (changes exn behavior) * @private */ var executeDispatchesAndRelease = function (event, simulated) { if (event) { EventPluginUtils.executeDispatchesInOrder(event, simulated); if (!event.isPersistent()) { event.constructor.release(event); } } }; var executeDispatchesAndReleaseSimulated = function (e) { return executeDispatchesAndRelease(e, true); }; var executeDispatchesAndReleaseTopLevel = function (e) { return executeDispatchesAndRelease(e, false); }; var getDictionaryKey = function (inst) { // Prevents V8 performance issue: // https://github.com/facebook/react/pull/7232 return '.' + inst._rootNodeID; }; function isInteractive(tag) { return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea'; } function shouldPreventMouseEvent(name, type, props) { switch (name) { case 'onClick': case 'onClickCapture': case 'onDoubleClick': case 'onDoubleClickCapture': case 'onMouseDown': case 'onMouseDownCapture': case 'onMouseMove': case 'onMouseMoveCapture': case 'onMouseUp': case 'onMouseUpCapture': return !!(props.disabled && isInteractive(type)); default: return false; } } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, /** * Stores `listener` at `listenerBank[registrationName][key]`. Is idempotent. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {function} listener The callback to store. */ putListener: function (inst, registrationName, listener) { !(typeof listener === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : _prodInvariant('94', registrationName, typeof listener) : void 0; var key = getDictionaryKey(inst); var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[key] = listener; var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.didPutListener) { PluginModule.didPutListener(inst, registrationName, listener); } }, /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function (inst, registrationName) { // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not // live here; needs to be moved to a better place soon var bankForRegistrationName = listenerBank[registrationName]; if (shouldPreventMouseEvent(registrationName, inst._currentElement.type, inst._currentElement.props)) { return null; } var key = getDictionaryKey(inst); return bankForRegistrationName && bankForRegistrationName[key]; }, /** * Deletes a listener from the registration bank. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function (inst, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? if (bankForRegistrationName) { var key = getDictionaryKey(inst); delete bankForRegistrationName[key]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {object} inst The instance, which is the source of events. */ deleteAllListeners: function (inst) { var key = getDictionaryKey(inst); for (var registrationName in listenerBank) { if (!listenerBank.hasOwnProperty(registrationName)) { continue; } if (!listenerBank[registrationName][key]) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } delete listenerBank[registrationName][key]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function (events) { if (events) { eventQueue = accumulateInto(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function (simulated) { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; if (simulated) { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); } else { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); } !!eventQueue ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : _prodInvariant('95') : void 0; // This would be a good time to rethrow if any of the event handlers threw. ReactErrorUtils.rethrowCaughtError(); }, /** * These are needed for tests only. Do not use! */ __purge: function () { listenerBank = {}; }, __getListenerBank: function () { return listenerBank; } }; module.exports = EventPluginHub; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); /** * Injectable ordering of event plugins. */ var eventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!eventPluginOrder) { // Wait until an `eventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var pluginModule = namesToPlugins[pluginName]; var pluginIndex = eventPluginOrder.indexOf(pluginName); !(pluginIndex > -1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : _prodInvariant('96', pluginName) : void 0; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !pluginModule.extractEvents ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : _prodInvariant('97', pluginName) : void 0; EventPluginRegistry.plugins[pluginIndex] = pluginModule; var publishedEvents = pluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : _prodInvariant('98', eventName, pluginName) : void 0; } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : _prodInvariant('99', eventName) : void 0; EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName(phasedRegistrationName, pluginModule, eventName); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, pluginModule, eventName) { !!EventPluginRegistry.registrationNameModules[registrationName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : _prodInvariant('100', registrationName) : void 0; EventPluginRegistry.registrationNameModules[registrationName] = pluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; if (process.env.NODE_ENV !== 'production') { var lowerCasedName = registrationName.toLowerCase(); EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName; if (registrationName === 'onDoubleClick') { EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName; } } } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in __DEV__. * @type {Object} */ possibleRegistrationNames: process.env.NODE_ENV !== 'production' ? {} : null, // Trust the developer to only use possibleRegistrationNames in __DEV__ /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function (injectedEventPluginOrder) { !!eventPluginOrder ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : _prodInvariant('101') : void 0; // Clone the ordering so it cannot be dynamically mutated. eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function (injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var pluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) { !!namesToPlugins[pluginName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : _prodInvariant('102', pluginName) : void 0; namesToPlugins[pluginName] = pluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function (event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; } if (dispatchConfig.phasedRegistrationNames !== undefined) { // pulling phasedRegistrationNames out of dispatchConfig helps Flow see // that it is not undefined. var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; for (var phase in phasedRegistrationNames) { if (!phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var pluginModule = EventPluginRegistry.registrationNameModules[phasedRegistrationNames[phase]]; if (pluginModule) { return pluginModule; } } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function () { eventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } if (process.env.NODE_ENV !== 'production') { var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames; for (var lowerCasedName in possibleRegistrationNames) { if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) { delete possibleRegistrationNames[lowerCasedName]; } } } } }; module.exports = EventPluginRegistry; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var ReactErrorUtils = __webpack_require__(51); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); /** * Injected dependencies: */ /** * - `ComponentTree`: [required] Module that can convert between React instances * and actual node references. */ var ComponentTree; var TreeTraversal; var injection = { injectComponentTree: function (Injected) { ComponentTree = Injected; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0; } }, injectTreeTraversal: function (Injected) { TreeTraversal = Injected; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, 'EventPluginUtils.injection.injectTreeTraversal(...): Injected ' + 'module is missing isAncestor or getLowestCommonAncestor.') : void 0; } } }; function isEndish(topLevelType) { return topLevelType === 'topMouseUp' || topLevelType === 'topTouchEnd' || topLevelType === 'topTouchCancel'; } function isMoveish(topLevelType) { return topLevelType === 'topMouseMove' || topLevelType === 'topTouchMove'; } function isStartish(topLevelType) { return topLevelType === 'topMouseDown' || topLevelType === 'topTouchStart'; } var validateEventDispatches; if (process.env.NODE_ENV !== 'production') { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; process.env.NODE_ENV !== 'production' ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : void 0; }; } /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {boolean} simulated If the event is simulated (changes exn behavior) * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ function executeDispatch(event, simulated, listener, inst) { var type = event.type || 'unknown-event'; event.currentTarget = EventPluginUtils.getNodeFromInstance(inst); if (simulated) { ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event); } else { ReactErrorUtils.invokeGuardedCallback(type, listener, event); } event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, simulated, dispatchListeners, dispatchInstances); } event._dispatchListeners = null; event._dispatchInstances = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchInstances)) { return dispatchInstances; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; !!Array.isArray(dispatchListener) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : _prodInvariant('103') : void 0; event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; var res = dispatchListener ? dispatchListener(event) : null; event.currentTarget = null; event._dispatchListeners = null; event._dispatchInstances = null; return res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, getInstanceFromNode: function (node) { return ComponentTree.getInstanceFromNode(node); }, getNodeFromInstance: function (node) { return ComponentTree.getNodeFromInstance(node); }, isAncestor: function (a, b) { return TreeTraversal.isAncestor(a, b); }, getLowestCommonAncestor: function (a, b) { return TreeTraversal.getLowestCommonAncestor(a, b); }, getParentInstance: function (inst) { return TreeTraversal.getParentInstance(inst); }, traverseTwoPhase: function (target, fn, arg) { return TreeTraversal.traverseTwoPhase(target, fn, arg); }, traverseEnterLeave: function (from, to, fn, argFrom, argTo) { return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo); }, injection: injection }; module.exports = EventPluginUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var caughtError = null; /** * Call a function while guarding against errors that happens within it. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} a First argument * @param {*} b Second argument */ function invokeGuardedCallback(name, func, a) { try { func(a); } catch (x) { if (caughtError === null) { caughtError = x; } } } var ReactErrorUtils = { invokeGuardedCallback: invokeGuardedCallback, /** * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event * handler are sure to be rethrown by rethrowCaughtError. */ invokeGuardedCallbackWithCatch: invokeGuardedCallback, /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ rethrowCaughtError: function () { if (caughtError) { var error = caughtError; caughtError = null; throw error; } } }; if (process.env.NODE_ENV !== 'production') { /** * To help development we can get better devtools integration by simulating a * real browser event. */ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); ReactErrorUtils.invokeGuardedCallback = function (name, func, a) { var boundFunc = func.bind(null, a); var evtType = 'react-' + name; fakeNode.addEventListener(evtType, boundFunc, false); var evt = document.createEvent('Event'); // $FlowFixMe https://github.com/facebook/flow/issues/2336 evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); fakeNode.removeEventListener(evtType, boundFunc, false); }; } } module.exports = ReactErrorUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); /** * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { !(next != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : _prodInvariant('30') : void 0; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). if (Array.isArray(current)) { if (Array.isArray(next)) { current.push.apply(current, next); return current; } current.push(next); return current; } if (Array.isArray(next)) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 53 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ function forEachAccumulated(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } } module.exports = forEachAccumulated; /***/ }, /* 54 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var PooledClass = __webpack_require__(56); var getTextContentAccessor = __webpack_require__(57); /** * This helper class stores information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this._root = root; this._startText = this.getText(); this._fallbackText = null; } _assign(FallbackCompositionState.prototype, { destructor: function () { this._root = null; this._startText = null; this._fallbackText = null; }, /** * Get current text of input. * * @return {string} */ getText: function () { if ('value' in this._root) { return this._root.value; } return this._root[getTextContentAccessor()]; }, /** * Determine the differing substring between the initially stored * text content and the current content. * * @return {string} */ getData: function () { if (this._fallbackText) { return this._fallbackText; } var start; var startValue = this._startText; var startLength = startValue.length; var end; var endValue = this.getText(); var endLength = endValue.length; for (start = 0; start < startLength; start++) { if (startValue[start] !== endValue[start]) { break; } } var minEnd = startLength - start; for (end = 1; end <= minEnd; end++) { if (startValue[startLength - end] !== endValue[endLength - end]) { break; } } var sliceTail = end > 1 ? 1 - end : undefined; this._fallbackText = endValue.slice(start, sliceTail); return this._fallbackText; } }); PooledClass.addPoolingTo(FallbackCompositionState); module.exports = FallbackCompositionState; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances. * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { // Casting as any so that flow ignores the actual implementation and trusts // it to match the type we declared var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler }; module.exports = PooledClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(54); var contentKey = null; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(59); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); module.exports = SyntheticCompositionEvent; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var PooledClass = __webpack_require__(56); var emptyFunction = __webpack_require__(18); var warning = __webpack_require__(17); var didWarnForAddedNewProperty = false; var isProxySupported = typeof Proxy === 'function'; var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances']; /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {*} targetInst Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { if (process.env.NODE_ENV !== 'production') { // these have a getter/setter for warnings delete this.nativeEvent; delete this.preventDefault; delete this.stopPropagation; } this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } if (process.env.NODE_ENV !== 'production') { delete this[propName]; // this has a getter/setter for warnings } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; return this; } _assign(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (!event) { return; } if (event.preventDefault) { event.preventDefault(); } else if (typeof event.returnValue !== 'unknown') { // eslint-disable-line valid-typeof event.returnValue = false; } this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else if (typeof event.cancelBubble !== 'unknown') { // eslint-disable-line valid-typeof // The ChangeEventPlugin registers a "propertychange" event for // IE. This event does not support bubbling or cancelling, and // any references to cancelBubble throw "Member not found". A // typeof check of "unknown" circumvents this issue (and is also // IE specific). event.cancelBubble = true; } this.isPropagationStopped = emptyFunction.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function () { var Interface = this.constructor.Interface; for (var propName in Interface) { if (process.env.NODE_ENV !== 'production') { Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); } else { this[propName] = null; } } for (var i = 0; i < shouldBeReleasedProperties.length; i++) { this[shouldBeReleasedProperties[i]] = null; } if (process.env.NODE_ENV !== 'production') { Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction)); Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction)); } } }); SyntheticEvent.Interface = EventInterface; if (process.env.NODE_ENV !== 'production') { if (isProxySupported) { /*eslint-disable no-func-assign */ SyntheticEvent = new Proxy(SyntheticEvent, { construct: function (target, args) { return this.apply(target, Object.create(target.prototype), args); }, apply: function (constructor, that, args) { return new Proxy(constructor.apply(that, args), { set: function (target, prop, value) { if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) { process.env.NODE_ENV !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re adding a new property in the synthetic event object. ' + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0; didWarnForAddedNewProperty = true; } target[prop] = value; return true; } }); } }); /*eslint-enable no-func-assign */ } } /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function (Class, Interface) { var Super = this; var E = function () {}; E.prototype = Super.prototype; var prototype = new E(); _assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = _assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler); module.exports = SyntheticEvent; /** * Helper to nullify syntheticEvent instance properties when destructing * * @param {object} SyntheticEvent * @param {String} propName * @return {object} defineProperty object */ function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; process.env.NODE_ENV !== 'production' ? warning(warningCondition, 'This synthetic event is reused for performance reasons. If you\'re seeing this, ' + 'you\'re %s `%s` on a released/nullified synthetic event. %s. ' + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0; } } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(59); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ var InputEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface); module.exports = SyntheticInputEvent; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPluginHub = __webpack_require__(48); var EventPropagators = __webpack_require__(47); var ExecutionEnvironment = __webpack_require__(54); var ReactDOMComponentTree = __webpack_require__(40); var ReactUpdates = __webpack_require__(62); var SyntheticEvent = __webpack_require__(59); var getEventTarget = __webpack_require__(75); var isEventSupported = __webpack_require__(76); var isTextInputElement = __webpack_require__(77); var eventTypes = { change: { phasedRegistrationNames: { bubbled: 'onChange', captured: 'onChangeCapture' }, dependencies: ['topBlur', 'topChange', 'topClick', 'topFocus', 'topInput', 'topKeyDown', 'topKeyUp', 'topSelectionChange'] } }; /** * For IE shims */ var activeElement = null; var activeElementInst = null; var activeElementValue = null; var activeElementValueProp = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && (!document.documentMode || document.documentMode > 8); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled(eventTypes.change, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); EventPropagators.accumulateTwoPhaseDispatches(event); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(false); } function startWatchingForChangeEventIE8(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementInst = null; } function getTargetInstForChangeEvent(topLevelType, targetInst) { if (topLevelType === 'topChange') { return targetInst; } } function handleEventsForChangeEventIE8(topLevelType, target, targetInst) { if (topLevelType === 'topFocus') { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(target, targetInst); } else if (topLevelType === 'topBlur') { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events. // IE10+ fire input events to often, such when a placeholder // changes or when an input with a placeholder is focused. isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 11); } /** * (For IE <=11) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function () { return activeElementValueProp.get.call(this); }, set: function (val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For IE <=11) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value'); // Not guarded in a canDefineProperty check: IE8 supports defineProperty only // on DOM elements Object.defineProperty(activeElement, 'value', newValueProp); if (activeElement.attachEvent) { activeElement.attachEvent('onpropertychange', handlePropertyChange); } else { activeElement.addEventListener('propertychange', handlePropertyChange, false); } } /** * (For IE <=11) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; if (activeElement.detachEvent) { activeElement.detachEvent('onpropertychange', handlePropertyChange); } else { activeElement.removeEventListener('propertychange', handlePropertyChange, false); } activeElement = null; activeElementInst = null; activeElementValue = null; activeElementValueProp = null; } /** * (For IE <=11) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetInstForInputEvent(topLevelType, targetInst) { if (topLevelType === 'topInput') { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return targetInst; } } function handleEventsForInputEventIE(topLevelType, target, targetInst) { if (topLevelType === 'topFocus') { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9-11, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(target, targetInst); } else if (topLevelType === 'topBlur') { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetInstForInputEventIE(topLevelType, targetInst) { if (topLevelType === 'topSelectionChange' || topLevelType === 'topKeyUp' || topLevelType === 'topKeyDown') { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementInst; } } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetInstForClickEvent(topLevelType, targetInst) { if (topLevelType === 'topClick') { return targetInst; } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; var getTargetInstFunc, handleEventFunc; if (shouldUseChangeEvent(targetNode)) { if (doesChangeEventBubble) { getTargetInstFunc = getTargetInstForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(targetNode)) { if (isInputEventSupported) { getTargetInstFunc = getTargetInstForInputEvent; } else { getTargetInstFunc = getTargetInstForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(targetNode)) { getTargetInstFunc = getTargetInstForClickEvent; } if (getTargetInstFunc) { var inst = getTargetInstFunc(topLevelType, targetInst); if (inst) { var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, nativeEventTarget); event.type = 'change'; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc(topLevelType, targetNode, targetInst); } } }; module.exports = ChangeEventPlugin; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41), _assign = __webpack_require__(10); var CallbackQueue = __webpack_require__(63); var PooledClass = __webpack_require__(56); var ReactFeatureFlags = __webpack_require__(64); var ReactReconciler = __webpack_require__(65); var Transaction = __webpack_require__(74); var invariant = __webpack_require__(14); var dirtyComponents = []; var updateBatchNumber = 0; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching strategy') : _prodInvariant('123') : void 0; } var NESTED_UPDATES = { initialize: function () { this.dirtyComponentsLength = dirtyComponents.length; }, close: function () { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function () { this.callbackQueue.reset(); }, close: function () { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */true); } _assign(ReactUpdatesFlushTransaction.prototype, Transaction, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, destructor: function () { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function (method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(); return batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; !(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to match dirty-components array length (%s).', len, dirtyComponents.length) : _prodInvariant('124', len, dirtyComponents.length) : void 0; // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); // Any updates enqueued while reconciling must be performed after this entire // batch. Otherwise, if dirtyComponents is [A, B] where A has children B and // C, B could update twice in a single batch if C's render enqueues an update // to B (since B would have already updated, we should skip it, and the only // way we can know to do so is by checking the batch counter). updateBatchNumber++; for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var namedComponent = component; // Duck type TopLevelWrapper. This is probably always true. if (component._currentElement.type.isReactTopLevelWrapper) { namedComponent = component._renderedComponent; } markerName = 'React update: ' + namedComponent.getName(); console.time(markerName); } ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber); if (markerName) { console.timeEnd(markerName); } if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance()); } } } } var flushBatchedUpdates = function () { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } }; /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); if (component._updateBatchNumber == null) { component._updateBatchNumber = updateBatchNumber + 1; } } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { !batchingStrategy.isBatchingUpdates ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context whereupdates are not being batched.') : _prodInvariant('125') : void 0; asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function (ReconcileTransaction) { !ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : _prodInvariant('126') : void 0; ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function (_batchingStrategy) { !_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : _prodInvariant('127') : void 0; !(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : _prodInvariant('128') : void 0; !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : _prodInvariant('129') : void 0; batchingStrategy = _batchingStrategy; } }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, asap: asap }; module.exports = ReactUpdates; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var PooledClass = __webpack_require__(56); var invariant = __webpack_require__(14); /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ var CallbackQueue = function () { function CallbackQueue(arg) { _classCallCheck(this, CallbackQueue); this._callbacks = null; this._contexts = null; this._arg = arg; } /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ CallbackQueue.prototype.enqueue = function enqueue(callback, context) { this._callbacks = this._callbacks || []; this._callbacks.push(callback); this._contexts = this._contexts || []; this._contexts.push(context); }; /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ CallbackQueue.prototype.notifyAll = function notifyAll() { var callbacks = this._callbacks; var contexts = this._contexts; var arg = this._arg; if (callbacks && contexts) { !(callbacks.length === contexts.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : _prodInvariant('24') : void 0; this._callbacks = null; this._contexts = null; for (var i = 0; i < callbacks.length; i++) { callbacks[i].call(contexts[i], arg); } callbacks.length = 0; contexts.length = 0; } }; CallbackQueue.prototype.checkpoint = function checkpoint() { return this._callbacks ? this._callbacks.length : 0; }; CallbackQueue.prototype.rollback = function rollback(len) { if (this._callbacks && this._contexts) { this._callbacks.length = len; this._contexts.length = len; } }; /** * Resets the internal queue. * * @internal */ CallbackQueue.prototype.reset = function reset() { this._callbacks = null; this._contexts = null; }; /** * `PooledClass` looks for this. */ CallbackQueue.prototype.destructor = function destructor() { this.reset(); }; return CallbackQueue; }(); module.exports = PooledClass.addPoolingTo(CallbackQueue); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 64 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactFeatureFlags = { // When true, call console.time() before and .timeEnd() after each top-level // render (both initial renders and updates). Useful when looking at prod-mode // timeline profiles in Chrome, for example. logTopLevelRenders: false }; module.exports = ReactFeatureFlags; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactRef = __webpack_require__(66); var ReactInstrumentation = __webpack_require__(68); var warning = __webpack_require__(17); /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef.attachRefs(this, this._currentElement); } var ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} the containing host component instance * @param {?object} info about the host container * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (internalInstance, transaction, hostParent, hostContainerInfo, context, parentDebugID // 0 in production and for roots ) { if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeMountComponent(internalInstance._debugID, internalInstance._currentElement, parentDebugID); } } var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context, parentDebugID); if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID); } } return markup; }, /** * Returns a value that can be passed to * ReactComponentEnvironment.replaceNodeWithMarkup. */ getHostNode: function (internalInstance) { return internalInstance.getHostNode(); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (internalInstance, safely) { if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUnmountComponent(internalInstance._debugID); } } ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(safely); if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID); } } }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function (internalInstance, nextElement, transaction, context) { var prevElement = internalInstance._currentElement; if (nextElement === prevElement && context === internalInstance._context) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for an element created outside a composite to be // deeply mutated and reused. // TODO: Bailing out early is just a perf optimization right? // TODO: Removing the return statement should affect correctness? return; } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement); } } var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement); if (refsChanged) { ReactRef.detachRefs(internalInstance, prevElement); } internalInstance.receiveComponent(nextElement, transaction, context); if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (internalInstance, transaction, updateBatchNumber) { if (internalInstance._updateBatchNumber !== updateBatchNumber) { // The component's enqueued batch number should always be the current // batch or the following one. process.env.NODE_ENV !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0; return; } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement); } } internalInstance.performUpdateIfNecessary(transaction); if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } } }; module.exports = ReactReconciler; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactOwner = __webpack_require__(67); var ReactRef = {}; function attachRef(ref, component, owner) { if (typeof ref === 'function') { ref(component.getPublicInstance()); } else { // Legacy ref ReactOwner.addComponentAsRefTo(component, ref, owner); } } function detachRef(ref, component, owner) { if (typeof ref === 'function') { ref(null); } else { // Legacy ref ReactOwner.removeComponentAsRefFrom(component, ref, owner); } } ReactRef.attachRefs = function (instance, element) { if (element === null || typeof element !== 'object') { return; } var ref = element.ref; if (ref != null) { attachRef(ref, instance, element._owner); } }; ReactRef.shouldUpdateRefs = function (prevElement, nextElement) { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. var prevRef = null; var prevOwner = null; if (prevElement !== null && typeof prevElement === 'object') { prevRef = prevElement.ref; prevOwner = prevElement._owner; } var nextRef = null; var nextOwner = null; if (nextElement !== null && typeof nextElement === 'object') { nextRef = nextElement.ref; nextOwner = nextElement._owner; } return prevRef !== nextRef || // If owner changes but we have an unchanged function ref, don't update refs typeof nextRef === 'string' && nextOwner !== prevOwner; }; ReactRef.detachRefs = function (instance, element) { if (element === null || typeof element !== 'object') { return; } var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; module.exports = ReactRef; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ function isValidOwner(object) { return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function'); } /** * ReactOwners are capable of storing references to owned components. * * All components are capable of //being// referenced by owner components, but * only ReactOwner components are capable of //referencing// owned components. * The named reference is known as a "ref". * * Refs are available when mounted and updated during reconciliation. * * var MyComponent = React.createClass({ * render: function() { * return ( * <div onClick={this.handleClick}> * <CustomComponent ref="custom" /> * </div> * ); * }, * handleClick: function() { * this.refs.custom.handleClick(); * }, * componentDidMount: function() { * this.refs.custom.initialize(); * } * }); * * Refs should rarely be used. When refs are used, they should only be done to * control data that is not handled by React's data flow. * * @class ReactOwner */ var ReactOwner = { /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function (component, ref, owner) { !isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('119') : void 0; owner.attachRef(ref, component); }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function (component, ref, owner) { !isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might be removing a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('120') : void 0; var ownerPublicInstance = owner.getPublicInstance(); // Check that `component`'s owner is still alive and that `component` is still the current ref // because we do not want to detach the ref if another component stole it. if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } }; module.exports = ReactOwner; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; // Trust the developer to only use ReactInstrumentation with a __DEV__ check var debugTool = null; if (process.env.NODE_ENV !== 'production') { var ReactDebugTool = __webpack_require__(69); debugTool = ReactDebugTool; } module.exports = { debugTool: debugTool }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactInvalidSetStateWarningHook = __webpack_require__(70); var ReactHostOperationHistoryHook = __webpack_require__(71); var ReactComponentTreeHook = __webpack_require__(32); var ExecutionEnvironment = __webpack_require__(54); var performanceNow = __webpack_require__(72); var warning = __webpack_require__(17); var hooks = []; var didHookThrowForEvent = {}; function callHook(event, fn, context, arg1, arg2, arg3, arg4, arg5) { try { fn.call(context, arg1, arg2, arg3, arg4, arg5); } catch (e) { process.env.NODE_ENV !== 'production' ? warning(didHookThrowForEvent[event], 'Exception thrown by hook while handling %s: %s', event, e + '\n' + e.stack) : void 0; didHookThrowForEvent[event] = true; } } function emitEvent(event, arg1, arg2, arg3, arg4, arg5) { for (var i = 0; i < hooks.length; i++) { var hook = hooks[i]; var fn = hook[event]; if (fn) { callHook(event, fn, hook, arg1, arg2, arg3, arg4, arg5); } } } var isProfiling = false; var flushHistory = []; var lifeCycleTimerStack = []; var currentFlushNesting = 0; var currentFlushMeasurements = []; var currentFlushStartTime = 0; var currentTimerDebugID = null; var currentTimerStartTime = 0; var currentTimerNestedFlushDuration = 0; var currentTimerType = null; var lifeCycleTimerHasWarned = false; function clearHistory() { ReactComponentTreeHook.purgeUnmountedComponents(); ReactHostOperationHistoryHook.clearHistory(); } function getTreeSnapshot(registeredIDs) { return registeredIDs.reduce(function (tree, id) { var ownerID = ReactComponentTreeHook.getOwnerID(id); var parentID = ReactComponentTreeHook.getParentID(id); tree[id] = { displayName: ReactComponentTreeHook.getDisplayName(id), text: ReactComponentTreeHook.getText(id), updateCount: ReactComponentTreeHook.getUpdateCount(id), childIDs: ReactComponentTreeHook.getChildIDs(id), // Text nodes don't have owners but this is close enough. ownerID: ownerID || parentID && ReactComponentTreeHook.getOwnerID(parentID) || 0, parentID: parentID }; return tree; }, {}); } function resetMeasurements() { var previousStartTime = currentFlushStartTime; var previousMeasurements = currentFlushMeasurements; var previousOperations = ReactHostOperationHistoryHook.getHistory(); if (currentFlushNesting === 0) { currentFlushStartTime = 0; currentFlushMeasurements = []; clearHistory(); return; } if (previousMeasurements.length || previousOperations.length) { var registeredIDs = ReactComponentTreeHook.getRegisteredIDs(); flushHistory.push({ duration: performanceNow() - previousStartTime, measurements: previousMeasurements || [], operations: previousOperations || [], treeSnapshot: getTreeSnapshot(registeredIDs) }); } clearHistory(); currentFlushStartTime = performanceNow(); currentFlushMeasurements = []; } function checkDebugID(debugID) { var allowRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (allowRoot && debugID === 0) { return; } if (!debugID) { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDebugTool: debugID may not be empty.') : void 0; } } function beginLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType && !lifeCycleTimerHasWarned) { process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'Did not expect %s timer to start while %s timer is still in ' + 'progress for %s instance.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; lifeCycleTimerHasWarned = true; } currentTimerStartTime = performanceNow(); currentTimerNestedFlushDuration = 0; currentTimerDebugID = debugID; currentTimerType = timerType; } function endLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) { process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'We did not expect %s timer to stop while %s timer is still in ' + 'progress for %s instance. Please report this as a bug in React.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; lifeCycleTimerHasWarned = true; } if (isProfiling) { currentFlushMeasurements.push({ timerType: timerType, instanceID: debugID, duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration }); } currentTimerStartTime = 0; currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; } function pauseCurrentLifeCycleTimer() { var currentTimer = { startTime: currentTimerStartTime, nestedFlushStartTime: performanceNow(), debugID: currentTimerDebugID, timerType: currentTimerType }; lifeCycleTimerStack.push(currentTimer); currentTimerStartTime = 0; currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; } function resumeCurrentLifeCycleTimer() { var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop(), startTime = _lifeCycleTimerStack$.startTime, nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime, debugID = _lifeCycleTimerStack$.debugID, timerType = _lifeCycleTimerStack$.timerType; var nestedFlushDuration = performanceNow() - nestedFlushStartTime; currentTimerStartTime = startTime; currentTimerNestedFlushDuration += nestedFlushDuration; currentTimerDebugID = debugID; currentTimerType = timerType; } var lastMarkTimeStamp = 0; var canUsePerformanceMeasure = // $FlowFixMe https://github.com/facebook/flow/issues/2345 typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; function shouldMark(debugID) { if (!isProfiling || !canUsePerformanceMeasure) { return false; } var element = ReactComponentTreeHook.getElement(debugID); if (element == null || typeof element !== 'object') { return false; } var isHostElement = typeof element.type === 'string'; if (isHostElement) { return false; } return true; } function markBegin(debugID, markType) { if (!shouldMark(debugID)) { return; } var markName = debugID + '::' + markType; lastMarkTimeStamp = performanceNow(); performance.mark(markName); } function markEnd(debugID, markType) { if (!shouldMark(debugID)) { return; } var markName = debugID + '::' + markType; var displayName = ReactComponentTreeHook.getDisplayName(debugID) || 'Unknown'; // Chrome has an issue of dropping markers recorded too fast: // https://bugs.chromium.org/p/chromium/issues/detail?id=640652 // To work around this, we will not report very small measurements. // I determined the magic number by tweaking it back and forth. // 0.05ms was enough to prevent the issue, but I set it to 0.1ms to be safe. // When the bug is fixed, we can `measure()` unconditionally if we want to. var timeStamp = performanceNow(); if (timeStamp - lastMarkTimeStamp > 0.1) { var measurementName = displayName + ' [' + markType + ']'; performance.measure(measurementName, markName); } performance.clearMarks(markName); performance.clearMeasures(measurementName); } var ReactDebugTool = { addHook: function (hook) { hooks.push(hook); }, removeHook: function (hook) { for (var i = 0; i < hooks.length; i++) { if (hooks[i] === hook) { hooks.splice(i, 1); i--; } } }, isProfiling: function () { return isProfiling; }, beginProfiling: function () { if (isProfiling) { return; } isProfiling = true; flushHistory.length = 0; resetMeasurements(); ReactDebugTool.addHook(ReactHostOperationHistoryHook); }, endProfiling: function () { if (!isProfiling) { return; } isProfiling = false; resetMeasurements(); ReactDebugTool.removeHook(ReactHostOperationHistoryHook); }, getFlushHistory: function () { return flushHistory; }, onBeginFlush: function () { currentFlushNesting++; resetMeasurements(); pauseCurrentLifeCycleTimer(); emitEvent('onBeginFlush'); }, onEndFlush: function () { resetMeasurements(); currentFlushNesting--; resumeCurrentLifeCycleTimer(); emitEvent('onEndFlush'); }, onBeginLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); emitEvent('onBeginLifeCycleTimer', debugID, timerType); markBegin(debugID, timerType); beginLifeCycleTimer(debugID, timerType); }, onEndLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); endLifeCycleTimer(debugID, timerType); markEnd(debugID, timerType); emitEvent('onEndLifeCycleTimer', debugID, timerType); }, onBeginProcessingChildContext: function () { emitEvent('onBeginProcessingChildContext'); }, onEndProcessingChildContext: function () { emitEvent('onEndProcessingChildContext'); }, onHostOperation: function (operation) { checkDebugID(operation.instanceID); emitEvent('onHostOperation', operation); }, onSetState: function () { emitEvent('onSetState'); }, onSetChildren: function (debugID, childDebugIDs) { checkDebugID(debugID); childDebugIDs.forEach(checkDebugID); emitEvent('onSetChildren', debugID, childDebugIDs); }, onBeforeMountComponent: function (debugID, element, parentDebugID) { checkDebugID(debugID); checkDebugID(parentDebugID, true); emitEvent('onBeforeMountComponent', debugID, element, parentDebugID); markBegin(debugID, 'mount'); }, onMountComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'mount'); emitEvent('onMountComponent', debugID); }, onBeforeUpdateComponent: function (debugID, element) { checkDebugID(debugID); emitEvent('onBeforeUpdateComponent', debugID, element); markBegin(debugID, 'update'); }, onUpdateComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'update'); emitEvent('onUpdateComponent', debugID); }, onBeforeUnmountComponent: function (debugID) { checkDebugID(debugID); emitEvent('onBeforeUnmountComponent', debugID); markBegin(debugID, 'unmount'); }, onUnmountComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'unmount'); emitEvent('onUnmountComponent', debugID); }, onTestEvent: function () { emitEvent('onTestEvent'); } }; // TODO remove these when RN/www gets updated ReactDebugTool.addDevtool = ReactDebugTool.addHook; ReactDebugTool.removeDevtool = ReactDebugTool.removeHook; ReactDebugTool.addHook(ReactInvalidSetStateWarningHook); ReactDebugTool.addHook(ReactComponentTreeHook); var url = ExecutionEnvironment.canUseDOM && window.location.href || ''; if (/[?&]react_perf\b/.test(url)) { ReactDebugTool.beginProfiling(); } module.exports = ReactDebugTool; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var warning = __webpack_require__(17); if (process.env.NODE_ENV !== 'production') { var processingChildContext = false; var warnInvalidSetState = function () { process.env.NODE_ENV !== 'production' ? warning(!processingChildContext, 'setState(...): Cannot call setState() inside getChildContext()') : void 0; }; } var ReactInvalidSetStateWarningHook = { onBeginProcessingChildContext: function () { processingChildContext = true; }, onEndProcessingChildContext: function () { processingChildContext = false; }, onSetState: function () { warnInvalidSetState(); } }; module.exports = ReactInvalidSetStateWarningHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 71 */ /***/ function(module, exports) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var history = []; var ReactHostOperationHistoryHook = { onHostOperation: function (operation) { history.push(operation); }, clearHistory: function () { if (ReactHostOperationHistoryHook._preventClearing) { // Should only be used for tests. return; } history = []; }, getHistory: function () { return history; } }; module.exports = ReactHostOperationHistoryHook; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var performance = __webpack_require__(73); var performanceNow; /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ if (performance.now) { performanceNow = function performanceNow() { return performance.now(); }; } else { performanceNow = function performanceNow() { return Date.now(); }; } module.exports = performanceNow; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var ExecutionEnvironment = __webpack_require__(54); var performance; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.msPerformance || window.webkitPerformance; } module.exports = performance || {}; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); var OBSERVED_ERROR = {}; /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM updates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var TransactionImpl = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function () { this.transactionWrappers = this.getTransactionWrappers(); if (this.wrapperInitData) { this.wrapperInitData.length = 0; } else { this.wrapperInitData = []; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function () { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. The optional arguments helps prevent the need * to bind in many cases. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} a Argument to pass to the method. * @param {Object?=} b Argument to pass to the method. * @param {Object?=} c Argument to pass to the method. * @param {Object?=} d Argument to pass to the method. * @param {Object?=} e Argument to pass to the method. * @param {Object?=} f Argument to pass to the method. * * @return {*} Return value from `method`. */ perform: function (method, scope, a, b, c, d, e, f) { !!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.') : _prodInvariant('27') : void 0; var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) {} } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function (startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) {} } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function (startIndex) { !this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : _prodInvariant('28') : void 0; var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== OBSERVED_ERROR && wrapper.close) { wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) {} } } } this.wrapperInitData.length = 0; } }; module.exports = TransactionImpl; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 75 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963 if (target.correspondingUseElement) { target = target.correspondingUseElement; } // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; } module.exports = getEventTarget; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(54); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = eventName in document; if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; /***/ }, /* 77 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { 'color': true, 'date': true, 'datetime': true, 'datetime-local': true, 'email': true, 'month': true, 'number': true, 'password': true, 'range': true, 'search': true, 'tel': true, 'text': true, 'time': true, 'url': true, 'week': true }; function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); if (nodeName === 'input') { return !!supportedInputTypes[elem.type]; } if (nodeName === 'textarea') { return true; } return false; } module.exports = isTextInputElement; /***/ }, /* 78 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Module that is injectable into `EventPluginHub`, that specifies a * deterministic ordering of `EventPlugin`s. A convenient way to reason about * plugins, without having to package every one of them. This is better than * having plugins be ordered in the same order that they are injected because * that ordering would be influenced by the packaging order. * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that * preventing default on events is convenient in `SimpleEventPlugin` handlers. */ var DefaultEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'TapEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin']; module.exports = DefaultEventPluginOrder; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPropagators = __webpack_require__(47); var ReactDOMComponentTree = __webpack_require__(40); var SyntheticMouseEvent = __webpack_require__(80); var eventTypes = { mouseEnter: { registrationName: 'onMouseEnter', dependencies: ['topMouseOut', 'topMouseOver'] }, mouseLeave: { registrationName: 'onMouseLeave', dependencies: ['topMouseOut', 'topMouseOver'] } }; var EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (topLevelType === 'topMouseOver' && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== 'topMouseOut' && topLevelType !== 'topMouseOver') { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; if (topLevelType === 'topMouseOut') { from = targetInst; var related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromNode = from == null ? win : ReactDOMComponentTree.getNodeFromInstance(from); var toNode = to == null ? win : ReactDOMComponentTree.getNodeFromInstance(to); var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = fromNode; leave.relatedTarget = toNode; var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = toNode; enter.relatedTarget = fromNode; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; } }; module.exports = EnterLeaveEventPlugin; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticUIEvent = __webpack_require__(81); var ViewportMetrics = __webpack_require__(82); var getEventModifierState = __webpack_require__(83); /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, getModifierState: getEventModifierState, button: function (event) { // Webkit, Firefox, IE9+ // which: 1 2 3 // button: 0 1 2 (standard) var button = event.button; if ('which' in event) { return button; } // IE<9 // which: undefined // button: 0 0 0 // button: 1 4 2 (onmouseup) return button === 2 ? 2 : button === 4 ? 1 : 0; }, buttons: null, relatedTarget: function (event) { return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); }, // "Proprietary" Interface. pageX: function (event) { return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; }, pageY: function (event) { return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(59); var getEventTarget = __webpack_require__(75); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function (event) { if (event.view) { return event.view; } var target = getEventTarget(event); if (target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function (event) { return event.detail || 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; /***/ }, /* 82 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function (scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; /***/ }, /* 83 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { 'Alt': 'altKey', 'Control': 'ctrlKey', 'Meta': 'metaKey', 'Shift': 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } module.exports = getEventModifierState; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(42); var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$')), Properties: { /** * Standard Properties */ accept: 0, acceptCharset: 0, accessKey: 0, action: 0, allowFullScreen: HAS_BOOLEAN_VALUE, allowTransparency: 0, alt: 0, // specifies target context for links with `preload` type as: 0, async: HAS_BOOLEAN_VALUE, autoComplete: 0, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: HAS_BOOLEAN_VALUE, cellPadding: 0, cellSpacing: 0, charSet: 0, challenge: 0, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, cite: 0, classID: 0, className: 0, cols: HAS_POSITIVE_NUMERIC_VALUE, colSpan: 0, content: 0, contentEditable: 0, contextMenu: 0, controls: HAS_BOOLEAN_VALUE, coords: 0, crossOrigin: 0, data: 0, // For `<object />` acts as `src`. dateTime: 0, 'default': HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: 0, disabled: HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: 0, encType: 0, form: 0, formAction: 0, formEncType: 0, formMethod: 0, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: 0, frameBorder: 0, headers: 0, height: 0, hidden: HAS_BOOLEAN_VALUE, high: 0, href: 0, hrefLang: 0, htmlFor: 0, httpEquiv: 0, icon: 0, id: 0, inputMode: 0, integrity: 0, is: 0, keyParams: 0, keyType: 0, kind: 0, label: 0, lang: 0, list: 0, loop: HAS_BOOLEAN_VALUE, low: 0, manifest: 0, marginHeight: 0, marginWidth: 0, max: 0, maxLength: 0, media: 0, mediaGroup: 0, method: 0, min: 0, minLength: 0, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: 0, nonce: 0, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: 0, pattern: 0, placeholder: 0, playsInline: HAS_BOOLEAN_VALUE, poster: 0, preload: 0, profile: 0, radioGroup: 0, readOnly: HAS_BOOLEAN_VALUE, referrerPolicy: 0, rel: 0, required: HAS_BOOLEAN_VALUE, reversed: HAS_BOOLEAN_VALUE, role: 0, rows: HAS_POSITIVE_NUMERIC_VALUE, rowSpan: HAS_NUMERIC_VALUE, sandbox: 0, scope: 0, scoped: HAS_BOOLEAN_VALUE, scrolling: 0, seamless: HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: 0, size: HAS_POSITIVE_NUMERIC_VALUE, sizes: 0, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: 0, src: 0, srcDoc: 0, srcLang: 0, srcSet: 0, start: HAS_NUMERIC_VALUE, step: 0, style: 0, summary: 0, tabIndex: 0, target: 0, title: 0, // Setting .type throws on non-<input> tags type: 0, useMap: 0, value: 0, width: 0, wmode: 0, wrap: 0, /** * RDFa Properties */ about: 0, datatype: 0, inlist: 0, prefix: 0, // property is also supported for OpenGraph in meta tags. property: 0, resource: 0, 'typeof': 0, vocab: 0, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: 0, autoCorrect: 0, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: 0, // color is for Safari mask-icon link color: 0, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: 0, itemScope: HAS_BOOLEAN_VALUE, itemType: 0, // itemID and itemRef are for Microdata support as well but // only specified in the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: 0, itemRef: 0, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: 0, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: 0, // IE-only attribute that controls focus behavior unselectable: 0 }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: {} }; module.exports = HTMLDOMPropertyConfig; /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMChildrenOperations = __webpack_require__(86); var ReactDOMIDOperations = __webpack_require__(97); /** * Abstracts away all functionality of the reconciler that requires knowledge of * the browser context. TODO: These callers should be refactored to avoid the * need for this injection. */ var ReactComponentBrowserEnvironment = { processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup }; module.exports = ReactComponentBrowserEnvironment; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMLazyTree = __webpack_require__(87); var Danger = __webpack_require__(93); var ReactDOMComponentTree = __webpack_require__(40); var ReactInstrumentation = __webpack_require__(68); var createMicrosoftUnsafeLocalFunction = __webpack_require__(90); var setInnerHTML = __webpack_require__(89); var setTextContent = __webpack_require__(91); function getNodeAfter(parentNode, node) { // Special case for text components, which return [open, close] comments // from getHostNode. if (Array.isArray(node)) { node = node[1]; } return node ? node.nextSibling : parentNode.firstChild; } /** * Inserts `childNode` as a child of `parentNode` at the `index`. * * @param {DOMElement} parentNode Parent node in which to insert. * @param {DOMElement} childNode Child node to insert. * @param {number} index Index at which to insert the child. * @internal */ var insertChildAt = createMicrosoftUnsafeLocalFunction(function (parentNode, childNode, referenceNode) { // We rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. (Using `undefined` is not allowed by all browsers so // we are careful to use `null`.) parentNode.insertBefore(childNode, referenceNode); }); function insertLazyTreeChildAt(parentNode, childTree, referenceNode) { DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode); } function moveChild(parentNode, childNode, referenceNode) { if (Array.isArray(childNode)) { moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode); } else { insertChildAt(parentNode, childNode, referenceNode); } } function removeChild(parentNode, childNode) { if (Array.isArray(childNode)) { var closingComment = childNode[1]; childNode = childNode[0]; removeDelimitedText(parentNode, childNode, closingComment); parentNode.removeChild(closingComment); } parentNode.removeChild(childNode); } function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) { var node = openingComment; while (true) { var nextNode = node.nextSibling; insertChildAt(parentNode, node, referenceNode); if (node === closingComment) { break; } node = nextNode; } } function removeDelimitedText(parentNode, startNode, closingComment) { while (true) { var node = startNode.nextSibling; if (node === closingComment) { // The closing comment is removed by ReactMultiChild. break; } else { parentNode.removeChild(node); } } } function replaceDelimitedText(openingComment, closingComment, stringText) { var parentNode = openingComment.parentNode; var nodeAfterComment = openingComment.nextSibling; if (nodeAfterComment === closingComment) { // There are no text nodes between the opening and closing comments; insert // a new one if stringText isn't empty. if (stringText) { insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment); } } else { if (stringText) { // Set the text content of the first node after the opening comment, and // remove all following nodes up until the closing comment. setTextContent(nodeAfterComment, stringText); removeDelimitedText(parentNode, nodeAfterComment, closingComment); } else { removeDelimitedText(parentNode, openingComment, closingComment); } } if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID, type: 'replace text', payload: stringText }); } } var dangerouslyReplaceNodeWithMarkup = Danger.dangerouslyReplaceNodeWithMarkup; if (process.env.NODE_ENV !== 'production') { dangerouslyReplaceNodeWithMarkup = function (oldChild, markup, prevInstance) { Danger.dangerouslyReplaceNodeWithMarkup(oldChild, markup); if (prevInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: prevInstance._debugID, type: 'replace with', payload: markup.toString() }); } else { var nextInstance = ReactDOMComponentTree.getInstanceFromNode(markup.node); if (nextInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: nextInstance._debugID, type: 'mount', payload: markup.toString() }); } } }; } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup, replaceDelimitedText: replaceDelimitedText, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @internal */ processUpdates: function (parentNode, updates) { if (process.env.NODE_ENV !== 'production') { var parentNodeDebugID = ReactDOMComponentTree.getInstanceFromNode(parentNode)._debugID; } for (var k = 0; k < updates.length; k++) { var update = updates[k]; switch (update.type) { case 'INSERT_MARKUP': insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode)); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'insert child', payload: { toIndex: update.toIndex, content: update.content.toString() } }); } break; case 'MOVE_EXISTING': moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode)); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'move child', payload: { fromIndex: update.fromIndex, toIndex: update.toIndex } }); } break; case 'SET_MARKUP': setInnerHTML(parentNode, update.content); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'replace children', payload: update.content.toString() }); } break; case 'TEXT_CONTENT': setTextContent(parentNode, update.content); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'replace text', payload: update.content.toString() }); } break; case 'REMOVE_NODE': removeChild(parentNode, update.fromNode); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'remove child', payload: { fromIndex: update.fromIndex } }); } break; } } } }; module.exports = DOMChildrenOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMNamespaces = __webpack_require__(88); var setInnerHTML = __webpack_require__(89); var createMicrosoftUnsafeLocalFunction = __webpack_require__(90); var setTextContent = __webpack_require__(91); var ELEMENT_NODE_TYPE = 1; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; /** * In IE (8-11) and Edge, appending nodes with no children is dramatically * faster than appending a full subtree, so we essentially queue up the * .appendChild calls here and apply them so each node is added to its parent * before any children are added. * * In other browsers, doing so is slower or neutral compared to the other order * (in Firefox, twice as slow) so we only do this inversion in IE. * * See https://github.com/spicyj/innerhtml-vs-createelement-vs-clonenode. */ var enableLazy = typeof document !== 'undefined' && typeof document.documentMode === 'number' || typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && /\bEdge\/\d/.test(navigator.userAgent); function insertTreeChildren(tree) { if (!enableLazy) { return; } var node = tree.node; var children = tree.children; if (children.length) { for (var i = 0; i < children.length; i++) { insertTreeBefore(node, children[i], null); } } else if (tree.html != null) { setInnerHTML(node, tree.html); } else if (tree.text != null) { setTextContent(node, tree.text); } } var insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (parentNode, tree, referenceNode) { // DocumentFragments aren't actually part of the DOM after insertion so // appending children won't update the DOM. We need to ensure the fragment // is properly populated first, breaking out of our lazy approach for just // this level. Also, some <object> plugins (like Flash Player) will read // <param> nodes immediately upon insertion into the DOM, so <object> // must also be populated prior to insertion into the DOM. if (tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE || tree.node.nodeType === ELEMENT_NODE_TYPE && tree.node.nodeName.toLowerCase() === 'object' && (tree.node.namespaceURI == null || tree.node.namespaceURI === DOMNamespaces.html)) { insertTreeChildren(tree); parentNode.insertBefore(tree.node, referenceNode); } else { parentNode.insertBefore(tree.node, referenceNode); insertTreeChildren(tree); } }); function replaceChildWithTree(oldNode, newTree) { oldNode.parentNode.replaceChild(newTree.node, oldNode); insertTreeChildren(newTree); } function queueChild(parentTree, childTree) { if (enableLazy) { parentTree.children.push(childTree); } else { parentTree.node.appendChild(childTree.node); } } function queueHTML(tree, html) { if (enableLazy) { tree.html = html; } else { setInnerHTML(tree.node, html); } } function queueText(tree, text) { if (enableLazy) { tree.text = text; } else { setTextContent(tree.node, text); } } function toString() { return this.node.nodeName; } function DOMLazyTree(node) { return { node: node, children: [], html: null, text: null, toString: toString }; } DOMLazyTree.insertTreeBefore = insertTreeBefore; DOMLazyTree.replaceChildWithTree = replaceChildWithTree; DOMLazyTree.queueChild = queueChild; DOMLazyTree.queueHTML = queueHTML; DOMLazyTree.queueText = queueText; module.exports = DOMLazyTree; /***/ }, /* 88 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMNamespaces = { html: 'http://www.w3.org/1999/xhtml', mathml: 'http://www.w3.org/1998/Math/MathML', svg: 'http://www.w3.org/2000/svg' }; module.exports = DOMNamespaces; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(54); var DOMNamespaces = __webpack_require__(88); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; var createMicrosoftUnsafeLocalFunction = __webpack_require__(90); // SVG temp container for IE lacking innerHTML var reusableSVGContainer; /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) { // IE does not have innerHTML for SVG nodes, so instead we inject the // new markup in a temp node and then move the child nodes across into // the target node if (node.namespaceURI === DOMNamespaces.svg && !('innerHTML' in node)) { reusableSVGContainer = reusableSVGContainer || document.createElement('div'); reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>'; var svgNode = reusableSVGContainer.firstChild; while (svgNode.firstChild) { node.appendChild(svgNode.firstChild); } } else { node.innerHTML = html; } }); if (ExecutionEnvironment.canUseDOM) { // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement('div'); testElement.innerHTML = ' '; if (testElement.innerHTML === '') { setInnerHTML = function (node, html) { // Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. // TODO: What to do on a detached node? if (node.parentNode) { node.parentNode.replaceChild(node, node); } // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. // UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode // in hopes that this is preserved even if "\uFEFF" is transformed to // the actual Unicode character (by Babel, for example). // https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216 node.innerHTML = String.fromCharCode(0xFEFF) + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } testElement = null; } module.exports = setInnerHTML; /***/ }, /* 90 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /* globals MSApp */ 'use strict'; /** * Create a function which has 'unsafe' privileges (required by windows8 apps) */ var createMicrosoftUnsafeLocalFunction = function (func) { if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { return function (arg0, arg1, arg2, arg3) { MSApp.execUnsafeLocalFunction(function () { return func(arg0, arg1, arg2, arg3); }); }; } else { return func; } }; module.exports = createMicrosoftUnsafeLocalFunction; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(54); var escapeTextContentForBrowser = __webpack_require__(92); var setInnerHTML = __webpack_require__(89); /** * Set the textContent property of a node, ensuring that whitespace is preserved * even in IE8. innerText is a poor substitute for textContent and, among many * issues, inserts <br> instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function (node, text) { if (text) { var firstChild = node.firstChild; if (firstChild && firstChild === node.lastChild && firstChild.nodeType === 3) { firstChild.nodeValue = text; return; } } node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function (node, text) { if (node.nodeType === 3) { node.nodeValue = text; return; } setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent; /***/ }, /* 92 */ /***/ function(module, exports) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * Based on the escape-html library, which is used under the MIT License below: * * Copyright (c) 2012-2013 TJ Holowaychuk * Copyright (c) 2015 Andreas Lubbe * Copyright (c) 2015 Tiancheng "Timothy" Gu * * 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. * */ 'use strict'; // code copied and modified from escape-html /** * Module variables. * @private */ var matchHtmlRegExp = /["'&<>]/; /** * Escape special characters in the given string of html. * * @param {string} string The string to escape for inserting into HTML * @return {string} * @public */ function escapeHtml(string) { var str = '' + string; var match = matchHtmlRegExp.exec(str); if (!match) { return str; } var escape; var html = ''; var index = 0; var lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '&quot;'; break; case 38: // & escape = '&amp;'; break; case 39: // ' escape = '&#x27;'; // modified from escape-html; used to be '&#39' break; case 60: // < escape = '&lt;'; break; case 62: // > escape = '&gt;'; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escape; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; } // end code copied and modified from escape-html /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { if (typeof text === 'boolean' || typeof text === 'number') { // this shortcircuit helps perf for types that we know will never have // special characters, especially given that this function is used often // for numeric dom ids. return '' + text; } return escapeHtml(text); } module.exports = escapeTextContentForBrowser; /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var DOMLazyTree = __webpack_require__(87); var ExecutionEnvironment = __webpack_require__(54); var createNodesFromMarkup = __webpack_require__(94); var emptyFunction = __webpack_require__(18); var invariant = __webpack_require__(14); var Danger = { /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) { !ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('56') : void 0; !markup ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : _prodInvariant('57') : void 0; !(oldChild.nodeName !== 'HTML') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See ReactDOMServer.renderToString().') : _prodInvariant('58') : void 0; if (typeof markup === 'string') { var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } else { DOMLazyTree.replaceChildWithTree(oldChild, markup); } } }; module.exports = Danger; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /*eslint-disable fb-www/unsafe-html*/ var ExecutionEnvironment = __webpack_require__(54); var createArrayFromMixed = __webpack_require__(95); var getMarkupWrap = __webpack_require__(96); var invariant = __webpack_require__(14); /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Pattern used by `getNodeName`. */ var nodeNamePattern = /^\s*<(\w+)/; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; !!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : void 0; var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { !handleScript ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : void 0; createArrayFromMixed(scripts).forEach(handleScript); } var nodes = Array.from(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var invariant = __webpack_require__(14); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFromMixed. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browsers builtin objects can report typeof 'function' (e.g. NodeList // in old versions of Safari). !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : void 0; !(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : void 0; !(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : void 0; !(typeof obj.callee !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant(false) : void 0; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return ( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFromMixed; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /*eslint-disable fb-www/unsafe-html */ var ExecutionEnvironment = __webpack_require__(54); var invariant = __webpack_require__(14); /** * Dummy container used to detect which wraps are necessary. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Some browsers cannot use `innerHTML` to render certain elements standalone, * so we wrap them, render the wrapped nodes, then extract the desired node. * * In IE8, certain elements cannot render alone, so wrap all elements ('*'). */ var shouldWrap = {}; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>']; var markupWrap = { '*': [1, '?<div>', '</div>'], 'area': [1, '<map>', '</map>'], 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], 'legend': [1, '<fieldset>', '</fieldset>'], 'param': [1, '<object>', '</object>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'optgroup': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap }; // Initialize the SVG elements since we know they'll always need to be wrapped // consistently. If they are created inside a <div> they will be initialized in // the wrong namespace (and will not display). var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan']; svgElements.forEach(function (nodeName) { markupWrap[nodeName] = svgWrap; shouldWrap[nodeName] = true; }); /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { !!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : void 0; if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } module.exports = getMarkupWrap; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMChildrenOperations = __webpack_require__(86); var ReactDOMComponentTree = __webpack_require__(40); /** * Operations used to process updates to DOM nodes. */ var ReactDOMIDOperations = { /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @internal */ dangerouslyProcessChildrenUpdates: function (parentInst, updates) { var node = ReactDOMComponentTree.getNodeFromInstance(parentInst); DOMChildrenOperations.processUpdates(node, updates); } }; module.exports = ReactDOMIDOperations; /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /* global hasOwnProperty:true */ 'use strict'; var _prodInvariant = __webpack_require__(41), _assign = __webpack_require__(10); var AutoFocusUtils = __webpack_require__(99); var CSSPropertyOperations = __webpack_require__(101); var DOMLazyTree = __webpack_require__(87); var DOMNamespaces = __webpack_require__(88); var DOMProperty = __webpack_require__(42); var DOMPropertyOperations = __webpack_require__(109); var EventPluginHub = __webpack_require__(48); var EventPluginRegistry = __webpack_require__(49); var ReactBrowserEventEmitter = __webpack_require__(111); var ReactDOMComponentFlags = __webpack_require__(43); var ReactDOMComponentTree = __webpack_require__(40); var ReactDOMInput = __webpack_require__(114); var ReactDOMOption = __webpack_require__(117); var ReactDOMSelect = __webpack_require__(118); var ReactDOMTextarea = __webpack_require__(119); var ReactInstrumentation = __webpack_require__(68); var ReactMultiChild = __webpack_require__(120); var ReactServerRenderingTransaction = __webpack_require__(139); var emptyFunction = __webpack_require__(18); var escapeTextContentForBrowser = __webpack_require__(92); var invariant = __webpack_require__(14); var isEventSupported = __webpack_require__(76); var shallowEqual = __webpack_require__(129); var validateDOMNesting = __webpack_require__(142); var warning = __webpack_require__(17); var Flags = ReactDOMComponentFlags; var deleteListener = EventPluginHub.deleteListener; var getNode = ReactDOMComponentTree.getNodeFromInstance; var listenTo = ReactBrowserEventEmitter.listenTo; var registrationNameModules = EventPluginRegistry.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = { 'string': true, 'number': true }; var STYLE = 'style'; var HTML = '__html'; var RESERVED_PROPS = { children: null, dangerouslySetInnerHTML: null, suppressContentEditableWarning: null }; // Node type for document fragments (Node.DOCUMENT_FRAGMENT_NODE). var DOC_FRAGMENT_TYPE = 11; function getDeclarationErrorAddendum(internalInstance) { if (internalInstance) { var owner = internalInstance._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' This DOM node was rendered by `' + name + '`.'; } } } return ''; } function friendlyStringify(obj) { if (typeof obj === 'object') { if (Array.isArray(obj)) { return '[' + obj.map(friendlyStringify).join(', ') + ']'; } else { var pairs = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key); pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key])); } } return '{' + pairs.join(', ') + '}'; } } else if (typeof obj === 'string') { return JSON.stringify(obj); } else if (typeof obj === 'function') { return '[function object]'; } // Differs from JSON.stringify in that undefined because undefined and that // inf and nan don't become null return String(obj); } var styleMutationWarning = {}; function checkAndWarnForMutatedStyle(style1, style2, component) { if (style1 == null || style2 == null) { return; } if (shallowEqual(style1, style2)) { return; } var componentName = component._tag; var owner = component._currentElement._owner; var ownerName; if (owner) { ownerName = owner.getName(); } var hash = ownerName + '|' + componentName; if (styleMutationWarning.hasOwnProperty(hash)) { return; } styleMutationWarning[hash] = true; process.env.NODE_ENV !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : void 0; } /** * @param {object} component * @param {?object} props */ function assertValidProps(component, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (voidElementTags[component._tag]) { !(props.children == null && props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : _prodInvariant('137', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : void 0; } if (props.dangerouslySetInnerHTML != null) { !(props.children == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : _prodInvariant('60') : void 0; !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.') : _prodInvariant('61') : void 0; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : void 0; process.env.NODE_ENV !== 'production' ? warning(props.suppressContentEditableWarning || !props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : void 0; process.env.NODE_ENV !== 'production' ? warning(props.onFocusIn == null && props.onFocusOut == null, 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.') : void 0; } !(props.style == null || typeof props.style === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + \'em\'}} when using JSX.%s', getDeclarationErrorAddendum(component)) : _prodInvariant('62', getDeclarationErrorAddendum(component)) : void 0; } function enqueuePutListener(inst, registrationName, listener, transaction) { if (transaction instanceof ReactServerRenderingTransaction) { return; } if (process.env.NODE_ENV !== 'production') { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. process.env.NODE_ENV !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : void 0; } var containerInfo = inst._hostContainerInfo; var isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOC_FRAGMENT_TYPE; var doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument; listenTo(registrationName, doc); transaction.getReactMountReady().enqueue(putListener, { inst: inst, registrationName: registrationName, listener: listener }); } function putListener() { var listenerToPut = this; EventPluginHub.putListener(listenerToPut.inst, listenerToPut.registrationName, listenerToPut.listener); } function inputPostMount() { var inst = this; ReactDOMInput.postMountWrapper(inst); } function textareaPostMount() { var inst = this; ReactDOMTextarea.postMountWrapper(inst); } function optionPostMount() { var inst = this; ReactDOMOption.postMountWrapper(inst); } var setAndValidateContentChildDev = emptyFunction; if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev = function (content) { var hasExistingContent = this._contentDebugID != null; var debugID = this._debugID; // This ID represents the inlined child that has no backing instance: var contentDebugID = -debugID; if (content == null) { if (hasExistingContent) { ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID); } this._contentDebugID = null; return; } validateDOMNesting(null, String(content), this, this._ancestorInfo); this._contentDebugID = contentDebugID; if (hasExistingContent) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(contentDebugID, content); ReactInstrumentation.debugTool.onUpdateComponent(contentDebugID); } else { ReactInstrumentation.debugTool.onBeforeMountComponent(contentDebugID, content, debugID); ReactInstrumentation.debugTool.onMountComponent(contentDebugID); ReactInstrumentation.debugTool.onSetChildren(debugID, [contentDebugID]); } }; } // There are so many media events, it makes sense to just // maintain a list rather than create a `trapBubbledEvent` for each var mediaEvents = { topAbort: 'abort', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topSeeked: 'seeked', topSeeking: 'seeking', topStalled: 'stalled', topSuspend: 'suspend', topTimeUpdate: 'timeupdate', topVolumeChange: 'volumechange', topWaiting: 'waiting' }; function trapBubbledEventsLocal() { var inst = this; // If a component renders to null or if another component fatals and causes // the state of the tree to be corrupted, `node` here can be null. !inst._rootNodeID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Must be mounted to trap events') : _prodInvariant('63') : void 0; var node = getNode(inst); !node ? process.env.NODE_ENV !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : _prodInvariant('64') : void 0; switch (inst._tag) { case 'iframe': case 'object': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', node)]; break; case 'video': case 'audio': inst._wrapperState.listeners = []; // Create listener for each media event for (var event in mediaEvents) { if (mediaEvents.hasOwnProperty(event)) { inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(event, mediaEvents[event], node)); } } break; case 'source': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topError', 'error', node)]; break; case 'img': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topError', 'error', node), ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', node)]; break; case 'form': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topReset', 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent('topSubmit', 'submit', node)]; break; case 'input': case 'select': case 'textarea': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topInvalid', 'invalid', node)]; break; } } function postUpdateSelectWrapper() { ReactDOMSelect.postUpdateWrapper(this); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special-case tags. var omittedCloseTags = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true }; var newlineEatingTags = { 'listing': true, 'pre': true, 'textarea': true }; // For HTML, certain tags cannot have children. This has the same purpose as // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = _assign({ 'menuitem': true }, omittedCloseTags); // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty = {}.hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty.call(validatedTagCache, tag)) { !VALID_TAG_REGEX.test(tag) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : _prodInvariant('65', tag) : void 0; validatedTagCache[tag] = true; } } function isCustomComponent(tagName, props) { return tagName.indexOf('-') >= 0 || props.is != null; } var globalIdCounter = 1; /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactMultiChild */ function ReactDOMComponent(element) { var tag = element.type; validateDangerousTag(tag); this._currentElement = element; this._tag = tag.toLowerCase(); this._namespaceURI = null; this._renderedChildren = null; this._previousStyle = null; this._previousStyleCopy = null; this._hostNode = null; this._hostParent = null; this._rootNodeID = 0; this._domID = 0; this._hostContainerInfo = null; this._wrapperState = null; this._topLevelWrapper = null; this._flags = 0; if (process.env.NODE_ENV !== 'production') { this._ancestorInfo = null; setAndValidateContentChildDev.call(this, null); } } ReactDOMComponent.displayName = 'ReactDOMComponent'; ReactDOMComponent.Mixin = { /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?ReactDOMComponent} the parent component instance * @param {?object} info about the host container * @param {object} context * @return {string} The computed markup. */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { this._rootNodeID = globalIdCounter++; this._domID = hostContainerInfo._idCounter++; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var props = this._currentElement.props; switch (this._tag) { case 'audio': case 'form': case 'iframe': case 'img': case 'link': case 'object': case 'source': case 'video': this._wrapperState = { listeners: null }; transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'input': ReactDOMInput.mountWrapper(this, props, hostParent); props = ReactDOMInput.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'option': ReactDOMOption.mountWrapper(this, props, hostParent); props = ReactDOMOption.getHostProps(this, props); break; case 'select': ReactDOMSelect.mountWrapper(this, props, hostParent); props = ReactDOMSelect.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'textarea': ReactDOMTextarea.mountWrapper(this, props, hostParent); props = ReactDOMTextarea.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; } assertValidProps(this, props); // We create tags in the namespace of their parent container, except HTML // tags get no namespace. var namespaceURI; var parentTag; if (hostParent != null) { namespaceURI = hostParent._namespaceURI; parentTag = hostParent._tag; } else if (hostContainerInfo._tag) { namespaceURI = hostContainerInfo._namespaceURI; parentTag = hostContainerInfo._tag; } if (namespaceURI == null || namespaceURI === DOMNamespaces.svg && parentTag === 'foreignobject') { namespaceURI = DOMNamespaces.html; } if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'svg') { namespaceURI = DOMNamespaces.svg; } else if (this._tag === 'math') { namespaceURI = DOMNamespaces.mathml; } } this._namespaceURI = namespaceURI; if (process.env.NODE_ENV !== 'production') { var parentInfo; if (hostParent != null) { parentInfo = hostParent._ancestorInfo; } else if (hostContainerInfo._tag) { parentInfo = hostContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting(this._tag, null, this, parentInfo); } this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this); } var mountImage; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var el; if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'script') { // Create the script via .innerHTML so its "parser-inserted" flag is // set to true and it does not execute var div = ownerDocument.createElement('div'); var type = this._currentElement.type; div.innerHTML = '<' + type + '></' + type + '>'; el = div.removeChild(div.firstChild); } else if (props.is) { el = ownerDocument.createElement(this._currentElement.type, props.is); } else { // Separate else branch instead of using `props.is || undefined` above becuase of a Firefox bug. // See discussion in https://github.com/facebook/react/pull/6896 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240 el = ownerDocument.createElement(this._currentElement.type); } } else { el = ownerDocument.createElementNS(namespaceURI, this._currentElement.type); } ReactDOMComponentTree.precacheNode(this, el); this._flags |= Flags.hasCachedChildNodes; if (!this._hostParent) { DOMPropertyOperations.setAttributeForRoot(el); } this._updateDOMProperties(null, props, transaction); var lazyTree = DOMLazyTree(el); this._createInitialChildren(transaction, props, context, lazyTree); mountImage = lazyTree; } else { var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props); var tagContent = this._createContentMarkup(transaction, props, context); if (!tagContent && omittedCloseTags[this._tag]) { mountImage = tagOpen + '/>'; } else { mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>'; } } switch (this._tag) { case 'input': transaction.getReactMountReady().enqueue(inputPostMount, this); if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'textarea': transaction.getReactMountReady().enqueue(textareaPostMount, this); if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'select': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'button': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'option': transaction.getReactMountReady().enqueue(optionPostMount, this); break; } return mountImage; }, /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function (transaction, props) { var ret = '<' + this._currentElement.type; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { if (propValue) { enqueuePutListener(this, propKey, propValue, transaction); } } else { if (propKey === STYLE) { if (propValue) { if (process.env.NODE_ENV !== 'production') { // See `_updateDOMProperties`. style block this._previousStyle = propValue; } propValue = this._previousStyleCopy = _assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this); } var markup = null; if (this._tag != null && isCustomComponent(this._tag, props)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); } } else { markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret; } if (!this._hostParent) { ret += ' ' + DOMPropertyOperations.createMarkupForRoot(); } ret += ' ' + DOMPropertyOperations.createMarkupForID(this._domID); return ret; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function (transaction, props, context) { var ret = ''; // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { ret = innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node ret = escapeTextContentForBrowser(contentToUse); if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, contentToUse); } } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); ret = mountImages.join(''); } } if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> return '\n' + ret; } else { return ret; } }, _createInitialChildren: function (transaction, props, context, lazyTree) { // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { DOMLazyTree.queueHTML(lazyTree, innerHTML.__html); } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; // TODO: Validate that text is allowed as a child of this node if (contentToUse != null) { // Avoid setting textContent when the text is empty. In IE11 setting // textContent on a text area will cause the placeholder to not // show within the textarea until it has been focused and blurred again. // https://github.com/facebook/react/issues/6731#issuecomment-254874553 if (contentToUse !== '') { if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, contentToUse); } DOMLazyTree.queueText(lazyTree, contentToUse); } } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); for (var i = 0; i < mountImages.length; i++) { DOMLazyTree.queueChild(lazyTree, mountImages[i]); } } } }, /** * Receives a next element and updates the component. * * @internal * @param {ReactElement} nextElement * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context */ receiveComponent: function (nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function (transaction, prevElement, nextElement, context) { var lastProps = prevElement.props; var nextProps = this._currentElement.props; switch (this._tag) { case 'input': lastProps = ReactDOMInput.getHostProps(this, lastProps); nextProps = ReactDOMInput.getHostProps(this, nextProps); break; case 'option': lastProps = ReactDOMOption.getHostProps(this, lastProps); nextProps = ReactDOMOption.getHostProps(this, nextProps); break; case 'select': lastProps = ReactDOMSelect.getHostProps(this, lastProps); nextProps = ReactDOMSelect.getHostProps(this, nextProps); break; case 'textarea': lastProps = ReactDOMTextarea.getHostProps(this, lastProps); nextProps = ReactDOMTextarea.getHostProps(this, nextProps); break; } assertValidProps(this, nextProps); this._updateDOMProperties(lastProps, nextProps, transaction); this._updateDOMChildren(lastProps, nextProps, transaction, context); switch (this._tag) { case 'input': // Update the wrapper around inputs *after* updating props. This has to // happen after `_updateDOMProperties`. Otherwise HTML5 input validations // raise warnings and prevent the new value from being assigned. ReactDOMInput.updateWrapper(this); break; case 'textarea': ReactDOMTextarea.updateWrapper(this); break; case 'select': // <select> value update needs to occur after <option> children // reconciliation transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); break; } }, /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {object} nextProps * @param {?DOMElement} node */ _updateDOMProperties: function (lastProps, nextProps, transaction) { var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) { continue; } if (propKey === STYLE) { var lastStyle = this._previousStyleCopy; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } this._previousStyleCopy = null; } else if (registrationNameModules.hasOwnProperty(propKey)) { if (lastProps[propKey]) { // Only call deleteListener if there was a listener previously or // else willDeleteListener gets called when there wasn't actually a // listener (e.g., onClick={null}) deleteListener(this, propKey); } } else if (isCustomComponent(this._tag, lastProps)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations.deleteValueForAttribute(getNode(this), propKey); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps != null ? lastProps[propKey] : undefined; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) { continue; } if (propKey === STYLE) { if (nextProp) { if (process.env.NODE_ENV !== 'production') { checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this); this._previousStyle = nextProp; } nextProp = this._previousStyleCopy = _assign({}, nextProp); } else { this._previousStyleCopy = null; } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules.hasOwnProperty(propKey)) { if (nextProp) { enqueuePutListener(this, propKey, nextProp, transaction); } else if (lastProp) { deleteListener(this, propKey); } } else if (isCustomComponent(this._tag, nextProps)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations.setValueForAttribute(getNode(this), propKey, nextProp); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { var node = getNode(this); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertently setting to a string. This // brings us in line with the same behavior we have on initial render. if (nextProp != null) { DOMPropertyOperations.setValueForProperty(node, propKey, nextProp); } else { DOMPropertyOperations.deleteValueForProperty(node, propKey); } } } if (styleUpdates) { CSSPropertyOperations.setValueForStyles(getNode(this), styleUpdates, this); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {object} context */ _updateDOMChildren: function (lastProps, nextProps, transaction, context) { var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction, context); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, nextContent); } } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { this.updateMarkup('' + nextHtml); } if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } else if (nextChildren != null) { if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, null); } this.updateChildren(nextChildren, transaction, context); } }, getHostNode: function () { return getNode(this); }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function (safely) { switch (this._tag) { case 'audio': case 'form': case 'iframe': case 'img': case 'link': case 'object': case 'source': case 'video': var listeners = this._wrapperState.listeners; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].remove(); } } break; case 'html': case 'head': case 'body': /** * Components like <html> <head> and <body> can't be removed or added * easily in a cross-browser way, however it's valuable to be able to * take advantage of React's reconciliation for styling and <title> * management. So we just document it and throw in dangerous cases. */ true ? process.env.NODE_ENV !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.', this._tag) : _prodInvariant('66', this._tag) : void 0; break; } this.unmountChildren(safely); ReactDOMComponentTree.uncacheNode(this); EventPluginHub.deleteAllListeners(this); this._rootNodeID = 0; this._domID = 0; this._wrapperState = null; if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, null); } }, getPublicInstance: function () { return getNode(this); } }; _assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin); module.exports = ReactDOMComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMComponentTree = __webpack_require__(40); var focusNode = __webpack_require__(100); var AutoFocusUtils = { focusDOMComponent: function () { focusNode(ReactDOMComponentTree.getNodeFromInstance(this)); } }; module.exports = AutoFocusUtils; /***/ }, /* 100 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch (e) {} } module.exports = focusNode; /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var CSSProperty = __webpack_require__(102); var ExecutionEnvironment = __webpack_require__(54); var ReactInstrumentation = __webpack_require__(68); var camelizeStyleName = __webpack_require__(103); var dangerousStyleValue = __webpack_require__(105); var hyphenateStyleName = __webpack_require__(106); var memoizeStringOnly = __webpack_require__(108); var warning = __webpack_require__(17); var processStyleName = memoizeStringOnly(function (styleName) { return hyphenateStyleName(styleName); }); var hasShorthandPropertyBug = false; var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { var tempStyle = document.createElement('div').style; try { // IE8 throws "Invalid argument." if resetting shorthand style properties. tempStyle.font = ''; } catch (e) { hasShorthandPropertyBug = true; } // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if (process.env.NODE_ENV !== 'production') { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnedForNaNValue = false; var warnHyphenatedStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?%s', name, camelizeStyleName(name), checkRenderMessage(owner)) : void 0; }; var warnBadVendoredStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?%s', name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)) : void 0; }; var warnStyleValueWithSemicolon = function (name, value, owner) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon.%s ' + 'Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, '')) : void 0; }; var warnStyleValueIsNaN = function (name, value, owner) { if (warnedForNaNValue) { return; } warnedForNaNValue = true; process.env.NODE_ENV !== 'production' ? warning(false, '`NaN` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)) : void 0; }; var checkRenderMessage = function (owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; }; /** * @param {string} name * @param {*} value * @param {ReactDOMComponent} component */ var warnValidStyle = function (name, value, component) { var owner; if (component) { owner = component._currentElement._owner; } if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name, owner); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name, owner); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value, owner); } if (typeof value === 'number' && isNaN(value)) { warnStyleValueIsNaN(name, value, owner); } }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @param {ReactDOMComponent} component * @return {?string} */ createMarkupForStyles: function (styles, component) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (process.env.NODE_ENV !== 'production') { warnValidStyle(styleName, styleValue, component); } if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue, component) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles * @param {ReactDOMComponent} component */ setValueForStyles: function (node, styles, component) { if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: component._debugID, type: 'update styles', payload: styles }); } var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if (process.env.NODE_ENV !== 'production') { warnValidStyle(styleName, styles[styleName], component); } var styleValue = dangerousStyleValue(styleName, styles[styleName], component); if (styleName === 'float' || styleName === 'cssFloat') { styleName = styleFloatAccessor; } if (styleValue) { style[styleName] = styleValue; } else { var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; module.exports = CSSPropertyOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 102 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridRow: true, gridColumn: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundAttachment: true, backgroundColor: true, backgroundImage: true, backgroundPositionX: true, backgroundPositionY: true, backgroundRepeat: true }, backgroundPosition: { backgroundPositionX: true, backgroundPositionY: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true }, outline: { outlineWidth: true, outlineStyle: true, outlineColor: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var camelize = __webpack_require__(104); var msPattern = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); } module.exports = camelizeStyleName; /***/ }, /* 104 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } module.exports = camelize; /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var CSSProperty = __webpack_require__(102); var warning = __webpack_require__(17); var isUnitlessNumber = CSSProperty.isUnitlessNumber; var styleWarnings = {}; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @param {ReactDOMComponent} component * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, component) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value; // cast to string } if (typeof value === 'string') { if (process.env.NODE_ENV !== 'production') { // Allow '0' to pass through without warning. 0 is already special and // doesn't require units, so we don't need to warn about it. if (component && value !== '0') { var owner = component._currentElement._owner; var ownerName = owner ? owner.getName() : null; if (ownerName && !styleWarnings[ownerName]) { styleWarnings[ownerName] = {}; } var warned = false; if (ownerName) { var warnings = styleWarnings[ownerName]; warned = warnings[name]; if (!warned) { warnings[name] = true; } } if (!warned) { process.env.NODE_ENV !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value) : void 0; } } } value = value.trim(); } return value + 'px'; } module.exports = dangerousStyleValue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var hyphenate = __webpack_require__(107); var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } module.exports = hyphenateStyleName; /***/ }, /* 107 */ /***/ function(module, exports) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; /***/ }, /* 108 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * * @typechecks static-only */ 'use strict'; /** * Memoizes the return value of a function that accepts one string argument. */ function memoizeStringOnly(callback) { var cache = {}; return function (string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; } module.exports = memoizeStringOnly; /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(42); var ReactDOMComponentTree = __webpack_require__(40); var ReactInstrumentation = __webpack_require__(68); var quoteAttributeValueForBrowser = __webpack_require__(110); var warning = __webpack_require__(17); var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$'); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { return true; } if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : void 0; return false; } function shouldIgnoreValue(propertyInfo, value) { return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function (id) { return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id); }, setAttributeForID: function (node, id) { node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id); }, createMarkupForRoot: function () { return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""'; }, setAttributeForRoot: function (node) { node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, ''); }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function (name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { if (shouldIgnoreValue(propertyInfo, value)) { return ''; } var attributeName = propertyInfo.attributeName; if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { return attributeName + '=""'; } return attributeName + '=' + quoteAttributeValueForBrowser(value); } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); } return null; }, /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ createMarkupForCustomAttribute: function (name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function (node, name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(propertyInfo, value)) { this.deleteValueForProperty(node, name); return; } else if (propertyInfo.mustUseProperty) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propertyInfo.propertyName] = value; } else { var attributeName = propertyInfo.attributeName; var namespace = propertyInfo.attributeNamespace; // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. if (namespace) { node.setAttributeNS(namespace, attributeName, '' + value); } else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { node.setAttribute(attributeName, ''); } else { node.setAttribute(attributeName, '' + value); } } } else if (DOMProperty.isCustomAttribute(name)) { DOMPropertyOperations.setValueForAttribute(node, name, value); return; } if (process.env.NODE_ENV !== 'production') { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'update attribute', payload: payload }); } }, setValueForAttribute: function (node, name, value) { if (!isAttributeNameSafe(name)) { return; } if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } if (process.env.NODE_ENV !== 'production') { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'update attribute', payload: payload }); } }, /** * Deletes an attributes from a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForAttribute: function (node, name) { node.removeAttribute(name); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'remove attribute', payload: name }); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function (node, name) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, undefined); } else if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; if (propertyInfo.hasBooleanValue) { node[propName] = false; } else { node[propName] = ''; } } else { node.removeAttribute(propertyInfo.attributeName); } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'remove attribute', payload: name }); } } }; module.exports = DOMPropertyOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var escapeTextContentForBrowser = __webpack_require__(92); /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser(value) + '"'; } module.exports = quoteAttributeValueForBrowser; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var EventPluginRegistry = __webpack_require__(49); var ReactEventEmitterMixin = __webpack_require__(112); var ViewportMetrics = __webpack_require__(82); var getVendorPrefixedEventName = __webpack_require__(113); var isEventSupported = __webpack_require__(76); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var hasEventPageXY; var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topAbort: 'abort', topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend', topAnimationIteration: getVendorPrefixedEventName('animationiteration') || 'animationiteration', topAnimationStart: getVendorPrefixedEventName('animationstart') || 'animationstart', topBlur: 'blur', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topScroll: 'scroll', topSeeked: 'seeked', topSeeking: 'seeking', topSelectionChange: 'selectionchange', topStalled: 'stalled', topSuspend: 'suspend', topTextInput: 'textInput', topTimeUpdate: 'timeupdate', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topTransitionEnd: getVendorPrefixedEventName('transitionend') || 'transitionend', topVolumeChange: 'volumechange', topWaiting: 'waiting', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * EventPluginHub.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = _assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function (ReactEventListener) { ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function (enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function () { return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function (registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName]; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { if (dependency === 'topWheel') { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'wheel', mountAt); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'mousewheel', mountAt); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'DOMMouseScroll', mountAt); } } else if (dependency === 'topScroll') { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topScroll', 'scroll', mountAt); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topScroll', 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE); } } else if (dependency === 'topFocus' || dependency === 'topBlur') { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topFocus', 'focus', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topBlur', 'blur', mountAt); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topFocus', 'focusin', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topBlur', 'focusout', mountAt); } // to make sure blur and focus event listeners are only attached once isListening.topBlur = true; isListening.topFocus = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt); } isListening[dependency] = true; } } }, trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); }, trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); }, /** * Protect against document.createEvent() returning null * Some popup blocker extensions appear to do this: * https://github.com/facebook/react/issues/6887 */ supportsEventPageXY: function () { if (!document.createEvent) { return false; } var ev = document.createEvent('MouseEvent'); return ev != null && 'pageX' in ev; }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * ViewportMetrics is only used by SyntheticMouse/TouchEvent and only when * pageX/pageY isn't supported (legacy browsers). * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function () { if (hasEventPageXY === undefined) { hasEventPageXY = ReactBrowserEventEmitter.supportsEventPageXY(); } if (!hasEventPageXY && !isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } } }); module.exports = ReactBrowserEventEmitter; /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPluginHub = __webpack_require__(48); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(false); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. */ handleTopLevel: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events = EventPluginHub.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(54); /** * Generate a mapping of standard vendor prefixes using the defined style property and event name. * * @param {string} styleProp * @param {string} eventName * @returns {object} */ function makePrefixMap(styleProp, eventName) { var prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; prefixes['ms' + styleProp] = 'MS' + eventName; prefixes['O' + styleProp] = 'o' + eventName.toLowerCase(); return prefixes; } /** * A list of event names to a configurable list of vendor prefixes. */ var vendorPrefixes = { animationend: makePrefixMap('Animation', 'AnimationEnd'), animationiteration: makePrefixMap('Animation', 'AnimationIteration'), animationstart: makePrefixMap('Animation', 'AnimationStart'), transitionend: makePrefixMap('Transition', 'TransitionEnd') }; /** * Event names that have already been detected and prefixed (if applicable). */ var prefixedEventNames = {}; /** * Element to check for prefixes on. */ var style = {}; /** * Bootstrap if a DOM exists. */ if (ExecutionEnvironment.canUseDOM) { style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are usable, and if not remove them from the map. if (!('AnimationEvent' in window)) { delete vendorPrefixes.animationend.animation; delete vendorPrefixes.animationiteration.animation; delete vendorPrefixes.animationstart.animation; } // Same as above if (!('TransitionEvent' in window)) { delete vendorPrefixes.transitionend.transition; } } /** * Attempts to determine the correct vendor prefixed event name. * * @param {string} eventName * @returns {string} */ function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return prefixedEventNames[eventName] = prefixMap[styleProp]; } } return ''; } module.exports = getVendorPrefixedEventName; /***/ }, /* 114 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41), _assign = __webpack_require__(10); var DOMPropertyOperations = __webpack_require__(109); var LinkedValueUtils = __webpack_require__(115); var ReactDOMComponentTree = __webpack_require__(40); var ReactUpdates = __webpack_require__(62); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); var didWarnValueLink = false; var didWarnCheckedLink = false; var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; var didWarnUncontrolledToControlled = false; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMInput.updateWrapper(this); } } function isControlled(props) { var usesChecked = props.type === 'checkbox' || props.type === 'radio'; return usesChecked ? props.checked != null : props.value != null; } /** * Implements an <input> host component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = { getHostProps: function (inst, props) { var value = LinkedValueUtils.getValue(props); var checked = LinkedValueUtils.getChecked(props); var hostProps = _assign({ // Make sure we set .type before any other properties (setting .value // before .type means .value is lost in IE11 and below) type: undefined, // Make sure we set .step before .value (setting .value before .step // means .value is rounded on mount, based upon step precision) step: undefined, // Make sure we set .min & .max before .value (to ensure proper order // in corner cases such as min or max deriving from value, e.g. Issue #7170) min: undefined, max: undefined }, props, { defaultChecked: undefined, defaultValue: undefined, value: value != null ? value : inst._wrapperState.initialValue, checked: checked != null ? checked : inst._wrapperState.initialChecked, onChange: inst._wrapperState.onChange }); return hostProps; }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner); var owner = inst._currentElement._owner; if (props.valueLink !== undefined && !didWarnValueLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } if (props.checkedLink !== undefined && !didWarnCheckedLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`checkedLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnCheckedLink = true; } if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { process.env.NODE_ENV !== 'production' ? warning(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnCheckedDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { process.env.NODE_ENV !== 'production' ? warning(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnValueDefaultValue = true; } } var defaultValue = props.defaultValue; inst._wrapperState = { initialChecked: props.checked != null ? props.checked : props.defaultChecked, initialValue: props.value != null ? props.value : defaultValue, listeners: null, onChange: _handleChange.bind(inst) }; if (process.env.NODE_ENV !== 'production') { inst._wrapperState.controlled = isControlled(props); } }, updateWrapper: function (inst) { var props = inst._currentElement.props; if (process.env.NODE_ENV !== 'production') { var controlled = isControlled(props); var owner = inst._currentElement._owner; if (!inst._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { process.env.NODE_ENV !== 'production' ? warning(false, '%s is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnUncontrolledToControlled = true; } if (inst._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { process.env.NODE_ENV !== 'production' ? warning(false, '%s is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnControlledToUncontrolled = true; } } // TODO: Shouldn't this be getChecked(props)? var checked = props.checked; if (checked != null) { DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'checked', checked || false); } var node = ReactDOMComponentTree.getNodeFromInstance(inst); var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. var newValue = '' + value; // To avoid side effects (such as losing text selection), only set value if changed if (newValue !== node.value) { node.value = newValue; } } else { if (props.value == null && props.defaultValue != null) { // In Chrome, assigning defaultValue to certain input types triggers input validation. // For number inputs, the display value loses trailing decimal points. For email inputs, // Chrome raises "The specified value <x> is not a valid email address". // // Here we check to see if the defaultValue has actually changed, avoiding these problems // when the user is inputting text // // https://github.com/facebook/react/issues/7253 if (node.defaultValue !== '' + props.defaultValue) { node.defaultValue = '' + props.defaultValue; } } if (props.checked == null && props.defaultChecked != null) { node.defaultChecked = !!props.defaultChecked; } } }, postMountWrapper: function (inst) { var props = inst._currentElement.props; // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. var node = ReactDOMComponentTree.getNodeFromInstance(inst); // Detach value from defaultValue. We won't do anything if we're working on // submit or reset inputs as those values & defaultValues are linked. They // are not resetable nodes so this operation doesn't matter and actually // removes browser-default values (eg "Submit Query") when no value is // provided. switch (props.type) { case 'submit': case 'reset': break; case 'color': case 'date': case 'datetime': case 'datetime-local': case 'month': case 'time': case 'week': // This fixes the no-show issue on iOS Safari and Android Chrome: // https://github.com/facebook/react/issues/7233 node.value = ''; node.value = node.defaultValue; break; default: node.value = node.value; break; } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug // this is needed to work around a chrome bug where setting defaultChecked // will sometimes influence the value of checked (even after detachment). // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 // We need to temporarily unset name to avoid disrupting radio button groups. var name = node.name; if (name !== '') { node.name = ''; } node.defaultChecked = !node.defaultChecked; node.defaultChecked = !node.defaultChecked; if (name !== '') { node.name = name; } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); // Here we use asap to wait until all updates have propagated, which // is important when using controlled components within layers: // https://github.com/facebook/react/issues/1698 ReactUpdates.asap(forceUpdateIfMounted, this); var name = props.name; if (props.type === 'radio' && name != null) { var rootNode = ReactDOMComponentTree.getNodeFromInstance(this); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form, let's just use the global // `querySelectorAll` to ensure we don't miss anything. var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React radio buttons with non-React ones. var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode); !otherInstance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : _prodInvariant('90') : void 0; // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. ReactUpdates.asap(forceUpdateIfMounted, otherInstance); } } return returnValue; } module.exports = ReactDOMInput; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var React = __webpack_require__(8); var ReactPropTypesSecret = __webpack_require__(116); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(inputProps) { !(inputProps.checkedLink == null || inputProps.valueLink == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use checkedLink, you probably don\'t want to use valueLink and vice versa.') : _prodInvariant('87') : void 0; } function _assertValueLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.value == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want to use value or onChange, you probably don\'t want to use valueLink.') : _prodInvariant('88') : void 0; } function _assertCheckedLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.checked == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. If you want to use checked or onChange, you probably don\'t want to use checkedLink') : _prodInvariant('89') : void 0; } var propTypes = { value: function (props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, checked: function (props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, onChange: React.PropTypes.func }; var loggedTypeFailures = {}; function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { checkPropTypes: function (tagName, props, owner) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, tagName, 'prop', null, ReactPropTypesSecret); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(owner); process.env.NODE_ENV !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : void 0; } } }, /** * @param {object} inputProps Props for form component * @return {*} current value of the input either from value prop or link. */ getValue: function (inputProps) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.value; } return inputProps.value; }, /** * @param {object} inputProps Props for form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function (inputProps) { if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.value; } return inputProps.checked; }, /** * @param {object} inputProps Props for form component * @param {SyntheticEvent} event change event to handle */ executeOnChange: function (inputProps, event) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.requestChange(event.target.value); } else if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.requestChange(event.target.checked); } else if (inputProps.onChange) { return inputProps.onChange.call(undefined, event); } } }; module.exports = LinkedValueUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 116 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var React = __webpack_require__(8); var ReactDOMComponentTree = __webpack_require__(40); var ReactDOMSelect = __webpack_require__(118); var warning = __webpack_require__(17); var didWarnInvalidOptionChildren = false; function flattenChildren(children) { var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. React.Children.forEach(children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else if (!didWarnInvalidOptionChildren) { didWarnInvalidOptionChildren = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : void 0; } }); return content; } /** * Implements an <option> host component that warns when `selected` is set. */ var ReactDOMOption = { mountWrapper: function (inst, props, hostParent) { // TODO (yungsters): Remove support for `selected` in <option>. if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : void 0; } // Look up whether this option is 'selected' var selectValue = null; if (hostParent != null) { var selectParent = hostParent; if (selectParent._tag === 'optgroup') { selectParent = selectParent._hostParent; } if (selectParent != null && selectParent._tag === 'select') { selectValue = ReactDOMSelect.getSelectValueContext(selectParent); } } // If the value is null (e.g., no specified value or after initial mount) // or missing (e.g., for <datalist>), we don't change props.selected var selected = null; if (selectValue != null) { var value; if (props.value != null) { value = props.value + ''; } else { value = flattenChildren(props.children); } selected = false; if (Array.isArray(selectValue)) { // multiple for (var i = 0; i < selectValue.length; i++) { if ('' + selectValue[i] === value) { selected = true; break; } } } else { selected = '' + selectValue === value; } } inst._wrapperState = { selected: selected }; }, postMountWrapper: function (inst) { // value="" should make a value attribute (#6219) var props = inst._currentElement.props; if (props.value != null) { var node = ReactDOMComponentTree.getNodeFromInstance(inst); node.setAttribute('value', props.value); } }, getHostProps: function (inst, props) { var hostProps = _assign({ selected: undefined, children: undefined }, props); // Read state only from initial mount because <select> updates value // manually; we need the initial state only for server rendering if (inst._wrapperState.selected != null) { hostProps.selected = inst._wrapperState.selected; } var content = flattenChildren(props.children); if (content) { hostProps.children = content; } return hostProps; } }; module.exports = ReactDOMOption; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var LinkedValueUtils = __webpack_require__(115); var ReactDOMComponentTree = __webpack_require__(40); var ReactUpdates = __webpack_require__(62); var warning = __webpack_require__(17); var didWarnValueLink = false; var didWarnValueDefaultValue = false; function updateOptionsIfPendingUpdateAndMounted() { if (this._rootNodeID && this._wrapperState.pendingUpdate) { this._wrapperState.pendingUpdate = false; var props = this._currentElement.props; var value = LinkedValueUtils.getValue(props); if (value != null) { updateOptions(this, Boolean(props.multiple), value); } } } function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } var valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. * @private */ function checkSelectPropTypes(inst, props) { var owner = inst._currentElement._owner; LinkedValueUtils.checkPropTypes('select', props, owner); if (props.valueLink !== undefined && !didWarnValueLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `select` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } var isArray = Array.isArray(props[propName]); if (props.multiple && !isArray) { process.env.NODE_ENV !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } else if (!props.multiple && isArray) { process.env.NODE_ENV !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } } } /** * @param {ReactDOMComponent} inst * @param {boolean} multiple * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(inst, multiple, propValue) { var selectedValue, i; var options = ReactDOMComponentTree.getNodeFromInstance(inst).options; if (multiple) { selectedValue = {}; for (i = 0; i < propValue.length; i++) { selectedValue['' + propValue[i]] = true; } for (i = 0; i < options.length; i++) { var selected = selectedValue.hasOwnProperty(options[i].value); if (options[i].selected !== selected) { options[i].selected = selected; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. selectedValue = '' + propValue; for (i = 0; i < options.length; i++) { if (options[i].value === selectedValue) { options[i].selected = true; return; } } if (options.length) { options[0].selected = true; } } } /** * Implements a <select> host component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = { getHostProps: function (inst, props) { return _assign({}, props, { onChange: inst._wrapperState.onChange, value: undefined }); }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { checkSelectPropTypes(inst, props); } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { pendingUpdate: false, initialValue: value != null ? value : props.defaultValue, listeners: null, onChange: _handleChange.bind(inst), wasMultiple: Boolean(props.multiple) }; if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { process.env.NODE_ENV !== 'production' ? warning(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValueDefaultValue = true; } }, getSelectValueContext: function (inst) { // ReactDOMOption looks at this initial value so the initial generated // markup has correct `selected` attributes return inst._wrapperState.initialValue; }, postUpdateWrapper: function (inst) { var props = inst._currentElement.props; // After the initial mount, we control selected-ness manually so don't pass // this value down inst._wrapperState.initialValue = undefined; var wasMultiple = inst._wrapperState.wasMultiple; inst._wrapperState.wasMultiple = Boolean(props.multiple); var value = LinkedValueUtils.getValue(props); if (value != null) { inst._wrapperState.pendingUpdate = false; updateOptions(inst, Boolean(props.multiple), value); } else if (wasMultiple !== Boolean(props.multiple)) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (props.defaultValue != null) { updateOptions(inst, Boolean(props.multiple), props.defaultValue); } else { // Revert the select back to its default unselected state. updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : ''); } } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); if (this._rootNodeID) { this._wrapperState.pendingUpdate = true; } ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); return returnValue; } module.exports = ReactDOMSelect; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41), _assign = __webpack_require__(10); var LinkedValueUtils = __webpack_require__(115); var ReactDOMComponentTree = __webpack_require__(40); var ReactUpdates = __webpack_require__(62); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); var didWarnValueLink = false; var didWarnValDefaultVal = false; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMTextarea.updateWrapper(this); } } /** * Implements a <textarea> host component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = { getHostProps: function (inst, props) { !(props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : _prodInvariant('91') : void 0; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. We could add a check in setTextContent // to only set the value if/when the value differs from the node value (which would // completely solve this IE9 bug), but Sebastian+Ben seemed to like this solution. // The value can be a boolean or object so that's why it's forced to be a string. var hostProps = _assign({}, props, { value: undefined, defaultValue: undefined, children: '' + inst._wrapperState.initialValue, onChange: inst._wrapperState.onChange }); return hostProps; }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner); if (props.valueLink !== undefined && !didWarnValueLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `textarea` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) { process.env.NODE_ENV !== 'production' ? warning(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValDefaultVal = true; } } var value = LinkedValueUtils.getValue(props); var initialValue = value; // Only bother fetching default value if we're going to use it if (value == null) { var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = props.children; if (children != null) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : void 0; } !(defaultValue == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : _prodInvariant('92') : void 0; if (Array.isArray(children)) { !(children.length <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : _prodInvariant('93') : void 0; children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } initialValue = defaultValue; } inst._wrapperState = { initialValue: '' + initialValue, listeners: null, onChange: _handleChange.bind(inst) }; }, updateWrapper: function (inst) { var props = inst._currentElement.props; var node = ReactDOMComponentTree.getNodeFromInstance(inst); var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. var newValue = '' + value; // To avoid side effects (such as losing text selection), only set value if changed if (newValue !== node.value) { node.value = newValue; } if (props.defaultValue == null) { node.defaultValue = newValue; } } if (props.defaultValue != null) { node.defaultValue = props.defaultValue; } }, postMountWrapper: function (inst) { // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. var node = ReactDOMComponentTree.getNodeFromInstance(inst); var textContent = node.textContent; // Only set node.value if textContent is equal to the expected // initial value. In IE10/IE11 there is a bug where the placeholder attribute // will populate textContent as well. // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/ if (textContent === inst._wrapperState.initialValue) { node.value = textContent; } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); ReactUpdates.asap(forceUpdateIfMounted, this); return returnValue; } module.exports = ReactDOMTextarea; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var ReactComponentEnvironment = __webpack_require__(121); var ReactInstanceMap = __webpack_require__(122); var ReactInstrumentation = __webpack_require__(68); var ReactCurrentOwner = __webpack_require__(16); var ReactReconciler = __webpack_require__(65); var ReactChildReconciler = __webpack_require__(123); var emptyFunction = __webpack_require__(18); var flattenChildren = __webpack_require__(138); var invariant = __webpack_require__(14); /** * Make an update for markup to be rendered and inserted at a supplied index. * * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function makeInsertMarkup(markup, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: 'INSERT_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for moving an existing element to another index. * * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function makeMove(child, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: 'MOVE_EXISTING', content: null, fromIndex: child._mountIndex, fromNode: ReactReconciler.getHostNode(child), toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for removing an element at an index. * * @param {number} fromIndex Index of the element to remove. * @private */ function makeRemove(child, node) { // NOTE: Null values reduce hidden classes. return { type: 'REMOVE_NODE', content: null, fromIndex: child._mountIndex, fromNode: node, toIndex: null, afterNode: null }; } /** * Make an update for setting the markup of a node. * * @param {string} markup Markup that renders into an element. * @private */ function makeSetMarkup(markup) { // NOTE: Null values reduce hidden classes. return { type: 'SET_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Make an update for setting the text content. * * @param {string} textContent Text content to set. * @private */ function makeTextContent(textContent) { // NOTE: Null values reduce hidden classes. return { type: 'TEXT_CONTENT', content: textContent, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Push an update, if any, onto the queue. Creates a new queue if none is * passed and always returns the queue. Mutative. */ function enqueue(queue, update) { if (update) { queue = queue || []; queue.push(update); } return queue; } /** * Processes any enqueued updates. * * @private */ function processQueue(inst, updateQueue) { ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue); } var setChildrenForInstrumentation = emptyFunction; if (process.env.NODE_ENV !== 'production') { var getDebugID = function (inst) { if (!inst._debugID) { // Check for ART-like instances. TODO: This is silly/gross. var internal; if (internal = ReactInstanceMap.get(inst)) { inst = internal; } } return inst._debugID; }; setChildrenForInstrumentation = function (children) { var debugID = getDebugID(this); // TODO: React Native empty components are also multichild. // This means they still get into this method but don't have _debugID. if (debugID !== 0) { ReactInstrumentation.debugTool.onSetChildren(debugID, children ? Object.keys(children).map(function (key) { return children[key]._debugID; }) : []); } }; } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { _reconcilerInstantiateChildren: function (nestedChildren, transaction, context) { if (process.env.NODE_ENV !== 'production') { var selfDebugID = getDebugID(this); if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context, selfDebugID); } finally { ReactCurrentOwner.current = null; } } } return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); }, _reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context) { var nextChildren; var selfDebugID = 0; if (process.env.NODE_ENV !== 'production') { selfDebugID = getDebugID(this); if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID); } finally { ReactCurrentOwner.current = null; } ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID); return nextChildren; } } nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID); ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID); return nextChildren; }, /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function (nestedChildren, transaction, context) { var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); this._renderedChildren = children; var mountImages = []; var index = 0; for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; var selfDebugID = 0; if (process.env.NODE_ENV !== 'production') { selfDebugID = getDebugID(this); } var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._hostContainerInfo, context, selfDebugID); child._mountIndex = index++; mountImages.push(mountImage); } } if (process.env.NODE_ENV !== 'production') { setChildrenForInstrumentation.call(this, children); } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function (nextContent) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } // Set new text content. var updates = [makeTextContent(nextContent)]; processQueue(this, updates); }, /** * Replaces any rendered children with a markup string. * * @param {string} nextMarkup String of markup. * @internal */ updateMarkup: function (nextMarkup) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } var updates = [makeSetMarkup(nextMarkup)]; processQueue(this, updates); }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function (nextNestedChildrenElements, transaction, context) { // Hook used by React ART this._updateChildren(nextNestedChildrenElements, transaction, context); }, /** * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function (nextNestedChildrenElements, transaction, context) { var prevChildren = this._renderedChildren; var removedNodes = {}; var mountImages = []; var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context); if (!nextChildren && !prevChildren) { return; } var updates = null; var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var nextIndex = 0; var lastIndex = 0; // `nextMountIndex` will increment for each newly mounted child. var nextMountIndex = 0; var lastPlacedNode = null; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (prevChild === nextChild) { updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); // The `removedNodes` loop below will actually remove the child. } // The child must be instantiated before it's mounted. updates = enqueue(updates, this._mountChildAtIndex(nextChild, mountImages[nextMountIndex], lastPlacedNode, nextIndex, transaction, context)); nextMountIndex++; } nextIndex++; lastPlacedNode = ReactReconciler.getHostNode(nextChild); } // Remove children that are no longer present. for (name in removedNodes) { if (removedNodes.hasOwnProperty(name)) { updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name])); } } if (updates) { processQueue(this, updates); } this._renderedChildren = nextChildren; if (process.env.NODE_ENV !== 'production') { setChildrenForInstrumentation.call(this, nextChildren); } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. It does not actually perform any * backend operations. * * @internal */ unmountChildren: function (safely) { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren, safely); this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function (child, afterNode, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { return makeMove(child, afterNode, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function (child, afterNode, mountImage) { return makeInsertMarkup(mountImage, afterNode, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function (child, node) { return makeRemove(child, node); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildAtIndex: function (child, mountImage, afterNode, index, transaction, context) { child._mountIndex = index; return this.createChild(child, afterNode, mountImage); }, /** * Unmounts a rendered child. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @private */ _unmountChild: function (child, node) { var update = this.removeChild(child, node); child._mountIndex = null; return update; } } }; module.exports = ReactMultiChild; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); var injected = false; var ReactComponentEnvironment = { /** * Optionally injectable hook for swapping out mount images in the middle of * the tree. */ replaceNodeWithMarkup: null, /** * Optionally injectable hook for processing a queue of child updates. Will * later move into MultiChildComponents. */ processChildrenUpdates: null, injection: { injectEnvironment: function (environment) { !!injected ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : _prodInvariant('104') : void 0; ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; module.exports = ReactComponentEnvironment; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 122 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. */ // TODO: Replace this with ES6: var ReactInstanceMap = new Map(); var ReactInstanceMap = { /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ remove: function (key) { key._reactInternalInstance = undefined; }, get: function (key) { return key._reactInternalInstance; }, has: function (key) { return key._reactInternalInstance !== undefined; }, set: function (key, value) { key._reactInternalInstance = value; } }; module.exports = ReactInstanceMap; /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactReconciler = __webpack_require__(65); var instantiateReactComponent = __webpack_require__(124); var KeyEscapeUtils = __webpack_require__(134); var shouldUpdateReactComponent = __webpack_require__(130); var traverseAllChildren = __webpack_require__(135); var warning = __webpack_require__(17); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = __webpack_require__(32); } function instantiateChild(childInstances, child, name, selfDebugID) { // We found a component instance. var keyUnique = childInstances[name] === undefined; if (process.env.NODE_ENV !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = __webpack_require__(32); } if (!keyUnique) { process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0; } } if (child != null && keyUnique) { childInstances[name] = instantiateReactComponent(child, true); } } /** * ReactChildReconciler provides helpers for initializing or updating a set of * children. Its output is suitable for passing it onto ReactMultiChild which * does diffed reordering and insertion. */ var ReactChildReconciler = { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildNodes Nested child maps. * @return {?object} A set of child instances. * @internal */ instantiateChildren: function (nestedChildNodes, transaction, context, selfDebugID // 0 in production and for roots ) { if (nestedChildNodes == null) { return null; } var childInstances = {}; if (process.env.NODE_ENV !== 'production') { traverseAllChildren(nestedChildNodes, function (childInsts, child, name) { return instantiateChild(childInsts, child, name, selfDebugID); }, childInstances); } else { traverseAllChildren(nestedChildNodes, instantiateChild, childInstances); } return childInstances; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextChildren Flat child element maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function (prevChildren, nextChildren, mountImages, removedNodes, transaction, hostParent, hostContainerInfo, context, selfDebugID // 0 in production and for roots ) { // We currently don't have a way to track moves here but if we use iterators // instead of for..in we can zip the iterators and check if an item has // moved. // TODO: If nothing has changed, return the prevChildren object so that we // can quickly bailout if nothing has changed. if (!nextChildren && !prevChildren) { return; } var name; var prevChild; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) { ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context); nextChildren[name] = prevChild; } else { if (prevChild) { removedNodes[name] = ReactReconciler.getHostNode(prevChild); ReactReconciler.unmountComponent(prevChild, false); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent(nextElement, true); nextChildren[name] = nextChildInstance; // Creating mount image now ensures refs are resolved in right order // (see https://github.com/facebook/react/pull/7101 for explanation). var nextChildMountImage = ReactReconciler.mountComponent(nextChildInstance, transaction, hostParent, hostContainerInfo, context, selfDebugID); mountImages.push(nextChildMountImage); } } // Unmount children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { prevChild = prevChildren[name]; removedNodes[name] = ReactReconciler.getHostNode(prevChild); ReactReconciler.unmountComponent(prevChild, false); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function (renderedChildren, safely) { for (var name in renderedChildren) { if (renderedChildren.hasOwnProperty(name)) { var renderedChild = renderedChildren[name]; ReactReconciler.unmountComponent(renderedChild, safely); } } } }; module.exports = ReactChildReconciler; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41), _assign = __webpack_require__(10); var ReactCompositeComponent = __webpack_require__(125); var ReactEmptyComponent = __webpack_require__(131); var ReactHostComponent = __webpack_require__(132); var getNextDebugID = __webpack_require__(133); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function (element) { this.construct(element); }; _assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent, { _instantiateReactComponent: instantiateReactComponent }); function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; } /** * Given a ReactNode, create an instance that will actually be mounted. * * @param {ReactNode} node * @param {boolean} shouldHaveDebugID * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(node, shouldHaveDebugID) { var instance; if (node === null || node === false) { instance = ReactEmptyComponent.create(instantiateReactComponent); } else if (typeof node === 'object') { var element = node; var type = element.type; if (typeof type !== 'function' && typeof type !== 'string') { var info = ''; if (process.env.NODE_ENV !== 'production') { if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + 'it\'s defined in.'; } } info += getDeclarationErrorAddendum(element._owner); true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', type == null ? type : typeof type, info) : _prodInvariant('130', type == null ? type : typeof type, info) : void 0; } // Special case string values if (typeof element.type === 'string') { instance = ReactHostComponent.createInternalComponent(element); } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // representations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); // We renamed this. Allow the old name for compat. :( if (!instance.getHostNode) { instance.getHostNode = instance.getNativeNode; } } else { instance = new ReactCompositeComponentWrapper(element); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactHostComponent.createInstanceForText(node); } else { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : _prodInvariant('131', typeof node) : void 0; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.getHostNode === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : void 0; } // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; if (process.env.NODE_ENV !== 'production') { instance._debugID = shouldHaveDebugID ? getNextDebugID() : 0; } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if (process.env.NODE_ENV !== 'production') { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; } module.exports = instantiateReactComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41), _assign = __webpack_require__(10); var React = __webpack_require__(8); var ReactComponentEnvironment = __webpack_require__(121); var ReactCurrentOwner = __webpack_require__(16); var ReactErrorUtils = __webpack_require__(51); var ReactInstanceMap = __webpack_require__(122); var ReactInstrumentation = __webpack_require__(68); var ReactNodeTypes = __webpack_require__(126); var ReactReconciler = __webpack_require__(65); if (process.env.NODE_ENV !== 'production') { var checkReactTypeSpec = __webpack_require__(127); } var emptyObject = __webpack_require__(26); var invariant = __webpack_require__(14); var shallowEqual = __webpack_require__(129); var shouldUpdateReactComponent = __webpack_require__(130); var warning = __webpack_require__(17); var CompositeTypes = { ImpureClass: 0, PureClass: 1, StatelessFunctional: 2 }; function StatelessComponent(Component) {} StatelessComponent.prototype.render = function () { var Component = ReactInstanceMap.get(this)._currentElement.type; var element = Component(this.props, this.context, this.updater); warnIfInvalidElement(Component, element); return element; }; function warnIfInvalidElement(Component, element) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(element === null || element === false || React.isValidElement(element), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!Component.childContextTypes, '%s(...): childContextTypes cannot be defined on a functional component.', Component.displayName || Component.name || 'Component') : void 0; } } function shouldConstruct(Component) { return !!(Component.prototype && Component.prototype.isReactComponent); } function isPureComponent(Component) { return !!(Component.prototype && Component.prototype.isPureReactComponent); } // Separated into a function to contain deoptimizations caused by try/finally. function measureLifeCyclePerf(fn, debugID, timerType) { if (debugID === 0) { // Top-level wrappers (see ReactMount) and empty components (see // ReactDOMEmptyComponent) are invisible to hooks and devtools. // Both are implementation details that should go away in the future. return fn(); } ReactInstrumentation.debugTool.onBeginLifeCycleTimer(debugID, timerType); try { return fn(); } finally { ReactInstrumentation.debugTool.onEndLifeCycleTimer(debugID, timerType); } } /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponent = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function (element) { this._currentElement = element; this._rootNodeID = 0; this._compositeType = null; this._instance = null; this._hostParent = null; this._hostContainerInfo = null; // See ReactUpdateQueue this._updateBatchNumber = null; this._pendingElement = null; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._renderedNodeType = null; this._renderedComponent = null; this._context = null; this._mountOrder = 0; this._topLevelWrapper = null; // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null; // ComponentWillUnmount shall only be called once this._calledComponentWillUnmount = false; if (process.env.NODE_ENV !== 'production') { this._warnedAboutRefsInRender = false; } }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} hostParent * @param {?object} hostContainerInfo * @param {?object} context * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { var _this = this; this._context = context; this._mountOrder = nextMountID++; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var publicProps = this._currentElement.props; var publicContext = this._processContext(context); var Component = this._currentElement.type; var updateQueue = transaction.getUpdateQueue(); // Initialize the public class var doConstruct = shouldConstruct(Component); var inst = this._constructComponent(doConstruct, publicProps, publicContext, updateQueue); var renderedElement; // Support functional components if (!doConstruct && (inst == null || inst.render == null)) { renderedElement = inst; warnIfInvalidElement(Component, renderedElement); !(inst === null || inst === false || React.isValidElement(inst)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : _prodInvariant('105', Component.displayName || Component.name || 'Component') : void 0; inst = new StatelessComponent(Component); this._compositeType = CompositeTypes.StatelessFunctional; } else { if (isPureComponent(Component)) { this._compositeType = CompositeTypes.PureClass; } else { this._compositeType = CompositeTypes.ImpureClass; } } if (process.env.NODE_ENV !== 'production') { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging if (inst.render == null) { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', Component.displayName || Component.name || 'Component') : void 0; } var propsMutated = inst.props !== publicProps; var componentName = Component.displayName || Component.name || 'Component'; process.env.NODE_ENV !== 'production' ? warning(inst.props === undefined || !propsMutated, '%s(...): When calling super() in `%s`, make sure to pass ' + 'up the same props that your component\'s constructor was passed.', componentName, componentName) : void 0; } // These should be set up in the constructor, but as a convenience for // simpler class abstractions, we set them up after the fact. inst.props = publicProps; inst.context = publicContext; inst.refs = emptyObject; inst.updater = updateQueue; this._instance = inst; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); if (process.env.NODE_ENV !== 'production') { // Since plain JS classes are defined without any special initialization // logic, we can not catch common errors early. Therefore, we have to // catch them here, at initialization time, instead. process.env.NODE_ENV !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved || inst.state, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : void 0; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : void 0; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : void 0; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : void 0; } var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : _prodInvariant('106', this.getName() || 'ReactCompositeComponent') : void 0; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; var markup; if (inst.unstable_handleError) { markup = this.performInitialMountWithErrorHandling(renderedElement, hostParent, hostContainerInfo, transaction, context); } else { markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } if (inst.componentDidMount) { if (process.env.NODE_ENV !== 'production') { transaction.getReactMountReady().enqueue(function () { measureLifeCyclePerf(function () { return inst.componentDidMount(); }, _this._debugID, 'componentDidMount'); }); } else { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } } return markup; }, _constructComponent: function (doConstruct, publicProps, publicContext, updateQueue) { if (process.env.NODE_ENV !== 'production') { ReactCurrentOwner.current = this; try { return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); } finally { ReactCurrentOwner.current = null; } } else { return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); } }, _constructComponentWithoutOwner: function (doConstruct, publicProps, publicContext, updateQueue) { var Component = this._currentElement.type; if (doConstruct) { if (process.env.NODE_ENV !== 'production') { return measureLifeCyclePerf(function () { return new Component(publicProps, publicContext, updateQueue); }, this._debugID, 'ctor'); } else { return new Component(publicProps, publicContext, updateQueue); } } // This can still be an instance in case of factory components // but we'll count this as time spent rendering as the more common case. if (process.env.NODE_ENV !== 'production') { return measureLifeCyclePerf(function () { return Component(publicProps, publicContext, updateQueue); }, this._debugID, 'render'); } else { return Component(publicProps, publicContext, updateQueue); } }, performInitialMountWithErrorHandling: function (renderedElement, hostParent, hostContainerInfo, transaction, context) { var markup; var checkpoint = transaction.checkpoint(); try { markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } catch (e) { // Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint transaction.rollback(checkpoint); this._instance.unstable_handleError(e); if (this._pendingStateQueue) { this._instance.state = this._processPendingState(this._instance.props, this._instance.context); } checkpoint = transaction.checkpoint(); this._renderedComponent.unmountComponent(true); transaction.rollback(checkpoint); // Try again - we've informed the component about the error, so they can render an error message this time. // If this throws again, the error will bubble up (and can be caught by a higher error boundary). markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } return markup; }, performInitialMount: function (renderedElement, hostParent, hostContainerInfo, transaction, context) { var inst = this._instance; var debugID = 0; if (process.env.NODE_ENV !== 'production') { debugID = this._debugID; } if (inst.componentWillMount) { if (process.env.NODE_ENV !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillMount(); }, debugID, 'componentWillMount'); } else { inst.componentWillMount(); } // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingStateQueue` without triggering a re-render. if (this._pendingStateQueue) { inst.state = this._processPendingState(inst.props, inst.context); } } // If not a stateless component, we now render if (renderedElement === undefined) { renderedElement = this._renderValidatedComponent(); } var nodeType = ReactNodeTypes.getType(renderedElement); this._renderedNodeType = nodeType; var child = this._instantiateReactComponent(renderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */ ); this._renderedComponent = child; var markup = ReactReconciler.mountComponent(child, transaction, hostParent, hostContainerInfo, this._processChildContext(context), debugID); if (process.env.NODE_ENV !== 'production') { if (debugID !== 0) { var childDebugIDs = child._debugID !== 0 ? [child._debugID] : []; ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs); } } return markup; }, getHostNode: function () { return ReactReconciler.getHostNode(this._renderedComponent); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (safely) { if (!this._renderedComponent) { return; } var inst = this._instance; if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) { inst._calledComponentWillUnmount = true; if (safely) { var name = this.getName() + '.componentWillUnmount()'; ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst)); } else { if (process.env.NODE_ENV !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillUnmount(); }, this._debugID, 'componentWillUnmount'); } else { inst.componentWillUnmount(); } } } if (this._renderedComponent) { ReactReconciler.unmountComponent(this._renderedComponent, safely); this._renderedNodeType = null; this._renderedComponent = null; this._instance = null; } // Reset pending fields // Even if this component is scheduled for another update in ReactUpdates, // it would still be ignored because these fields are reset. this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._pendingCallbacks = null; this._pendingElement = null; // These fields do not really need to be reset since this object is no // longer accessible. this._context = null; this._rootNodeID = 0; this._topLevelWrapper = null; // Delete the reference from the instance to this internal representation // which allow the internals to be properly cleaned up even if the user // leaks a reference to the public instance. ReactInstanceMap.remove(inst); // Some existing components rely on inst.props even after they've been // destroyed (in event handlers). // TODO: inst.props = null; // TODO: inst.state = null; // TODO: inst.context = null; }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function (context) { var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject; } var maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function (context) { var maskedContext = this._maskContext(context); if (process.env.NODE_ENV !== 'production') { var Component = this._currentElement.type; if (Component.contextTypes) { this._checkContextTypes(Component.contextTypes, maskedContext, 'context'); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function (currentContext) { var Component = this._currentElement.type; var inst = this._instance; var childContext; if (inst.getChildContext) { if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onBeginProcessingChildContext(); try { childContext = inst.getChildContext(); } finally { ReactInstrumentation.debugTool.onEndProcessingChildContext(); } } else { childContext = inst.getChildContext(); } } if (childContext) { !(typeof Component.childContextTypes === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().', this.getName() || 'ReactCompositeComponent') : _prodInvariant('107', this.getName() || 'ReactCompositeComponent') : void 0; if (process.env.NODE_ENV !== 'production') { this._checkContextTypes(Component.childContextTypes, childContext, 'childContext'); } for (var name in childContext) { !(name in Component.childContextTypes) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : _prodInvariant('108', this.getName() || 'ReactCompositeComponent', name) : void 0; } return _assign({}, currentContext, childContext); } return currentContext; }, /** * Assert that the context types are valid * * @param {object} typeSpecs Map of context field to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkContextTypes: function (typeSpecs, values, location) { if (process.env.NODE_ENV !== 'production') { checkReactTypeSpec(typeSpecs, values, location, this.getName(), null, this._debugID); } }, receiveComponent: function (nextElement, transaction, nextContext) { var prevElement = this._currentElement; var prevContext = this._context; this._pendingElement = null; this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context); } else if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } else { this._updateBatchNumber = null; } }, /** * Perform an update to a mounted component. The componentWillReceiveProps and * shouldComponentUpdate methods are called, then (assuming the update isn't * skipped) the remaining update lifecycle methods are called and the DOM * representation is updated. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevParentElement * @param {ReactElement} nextParentElement * @internal * @overridable */ updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { var inst = this._instance; !(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Attempted to update component `%s` that has already been unmounted (or failed to mount).', this.getName() || 'ReactCompositeComponent') : _prodInvariant('136', this.getName() || 'ReactCompositeComponent') : void 0; var willReceive = false; var nextContext; // Determine if the context has changed or not if (this._context === nextUnmaskedContext) { nextContext = inst.context; } else { nextContext = this._processContext(nextUnmaskedContext); willReceive = true; } var prevProps = prevParentElement.props; var nextProps = nextParentElement.props; // Not a simple state update but a props update if (prevParentElement !== nextParentElement) { willReceive = true; } // An update here will schedule an update but immediately set // _pendingStateQueue which will ensure that any state updates gets // immediately reconciled instead of waiting for the next batch. if (willReceive && inst.componentWillReceiveProps) { if (process.env.NODE_ENV !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillReceiveProps(nextProps, nextContext); }, this._debugID, 'componentWillReceiveProps'); } else { inst.componentWillReceiveProps(nextProps, nextContext); } } var nextState = this._processPendingState(nextProps, nextContext); var shouldUpdate = true; if (!this._pendingForceUpdate) { if (inst.shouldComponentUpdate) { if (process.env.NODE_ENV !== 'production') { shouldUpdate = measureLifeCyclePerf(function () { return inst.shouldComponentUpdate(nextProps, nextState, nextContext); }, this._debugID, 'shouldComponentUpdate'); } else { shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext); } } else { if (this._compositeType === CompositeTypes.PureClass) { shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState); } } } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(shouldUpdate !== undefined, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : void 0; } this._updateBatchNumber = null; if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext); } else { // If it's determined that a component should not update, we still want // to set props and state but we shortcut the rest of the update. this._currentElement = nextParentElement; this._context = nextUnmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; } }, _processPendingState: function (props, context) { var inst = this._instance; var queue = this._pendingStateQueue; var replace = this._pendingReplaceState; this._pendingReplaceState = false; this._pendingStateQueue = null; if (!queue) { return inst.state; } if (replace && queue.length === 1) { return queue[0]; } var nextState = _assign({}, replace ? queue[0] : inst.state); for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; _assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial); } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { var _this2 = this; var inst = this._instance; var hasComponentDidUpdate = Boolean(inst.componentDidUpdate); var prevProps; var prevState; var prevContext; if (hasComponentDidUpdate) { prevProps = inst.props; prevState = inst.state; prevContext = inst.context; } if (inst.componentWillUpdate) { if (process.env.NODE_ENV !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillUpdate(nextProps, nextState, nextContext); }, this._debugID, 'componentWillUpdate'); } else { inst.componentWillUpdate(nextProps, nextState, nextContext); } } this._currentElement = nextElement; this._context = unmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; this._updateRenderedComponent(transaction, unmaskedContext); if (hasComponentDidUpdate) { if (process.env.NODE_ENV !== 'production') { transaction.getReactMountReady().enqueue(function () { measureLifeCyclePerf(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), _this2._debugID, 'componentDidUpdate'); }); } else { transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst); } } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function (transaction, context) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; var nextRenderedElement = this._renderValidatedComponent(); var debugID = 0; if (process.env.NODE_ENV !== 'production') { debugID = this._debugID; } if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); } else { var oldHostNode = ReactReconciler.getHostNode(prevComponentInstance); ReactReconciler.unmountComponent(prevComponentInstance, false); var nodeType = ReactNodeTypes.getType(nextRenderedElement); this._renderedNodeType = nodeType; var child = this._instantiateReactComponent(nextRenderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */ ); this._renderedComponent = child; var nextMarkup = ReactReconciler.mountComponent(child, transaction, this._hostParent, this._hostContainerInfo, this._processChildContext(context), debugID); if (process.env.NODE_ENV !== 'production') { if (debugID !== 0) { var childDebugIDs = child._debugID !== 0 ? [child._debugID] : []; ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs); } } this._replaceNodeWithMarkup(oldHostNode, nextMarkup, prevComponentInstance); } }, /** * Overridden in shallow rendering. * * @protected */ _replaceNodeWithMarkup: function (oldHostNode, nextMarkup, prevInstance) { ReactComponentEnvironment.replaceNodeWithMarkup(oldHostNode, nextMarkup, prevInstance); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function () { var inst = this._instance; var renderedElement; if (process.env.NODE_ENV !== 'production') { renderedElement = measureLifeCyclePerf(function () { return inst.render(); }, this._debugID, 'render'); } else { renderedElement = inst.render(); } if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (renderedElement === undefined && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedElement = null; } } return renderedElement; }, /** * @private */ _renderValidatedComponent: function () { var renderedElement; if (process.env.NODE_ENV !== 'production' || this._compositeType !== CompositeTypes.StatelessFunctional) { ReactCurrentOwner.current = this; try { renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactCurrentOwner.current = null; } } else { renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); } !( // TODO: An `isValidNode` function would probably be more appropriate renderedElement === null || renderedElement === false || React.isValidElement(renderedElement)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : _prodInvariant('109', this.getName() || 'ReactCompositeComponent') : void 0; return renderedElement; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function (ref, component) { var inst = this.getPublicInstance(); !(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : _prodInvariant('110') : void 0; var publicComponentInstance = component.getPublicInstance(); if (process.env.NODE_ENV !== 'production') { var componentName = component && component.getName ? component.getName() : 'a component'; process.env.NODE_ENV !== 'production' ? warning(publicComponentInstance != null || component._compositeType !== CompositeTypes.StatelessFunctional, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : void 0; } var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; refs[ref] = publicComponentInstance; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function (ref) { var refs = this.getPublicInstance().refs; delete refs[ref]; }, /** * Get a text description of the component that can be used to identify it * in error messages. * @return {string} The name or null. * @internal */ getName: function () { var type = this._currentElement.type; var constructor = this._instance && this._instance.constructor; return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; }, /** * Get the publicly accessible representation of this component - i.e. what * is exposed by refs and returned by render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function () { var inst = this._instance; if (this._compositeType === CompositeTypes.StatelessFunctional) { return null; } return inst; }, // Stub _instantiateReactComponent: null }; module.exports = ReactCompositeComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var React = __webpack_require__(8); var invariant = __webpack_require__(14); var ReactNodeTypes = { HOST: 0, COMPOSITE: 1, EMPTY: 2, getType: function (node) { if (node === null || node === false) { return ReactNodeTypes.EMPTY; } else if (React.isValidElement(node)) { if (typeof node.type === 'function') { return ReactNodeTypes.COMPOSITE; } else { return ReactNodeTypes.HOST; } } true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unexpected node: %s', node) : _prodInvariant('26', node) : void 0; } }; module.exports = ReactNodeTypes; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var ReactPropTypeLocationNames = __webpack_require__(128); var ReactPropTypesSecret = __webpack_require__(116); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = __webpack_require__(32); } var loggedTypeFailures = {}; /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?object} element The React element that is being type-checked * @param {?number} debugID The React component instance that is being type-checked * @private */ function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof typeSpecs[typeSpecName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0; error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var componentStackInfo = ''; if (process.env.NODE_ENV !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = __webpack_require__(32); } if (debugID !== null) { componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID); } else if (element !== null) { componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element); } } process.env.NODE_ENV !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0; } } } } module.exports = checkReactTypeSpec; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypeLocationNames = {}; if (process.env.NODE_ENV !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 129 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * */ /*eslint-disable no-self-compare */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 // Added the nonzero y check to make Flow happy, but it is redundant return x !== 0 || y !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (is(objA, objB)) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } module.exports = shallowEqual; /***/ }, /* 130 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; if (prevEmpty || nextEmpty) { return prevEmpty === nextEmpty; } var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return nextType === 'string' || nextType === 'number'; } else { return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; } } module.exports = shouldUpdateReactComponent; /***/ }, /* 131 */ /***/ function(module, exports) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyComponentFactory; var ReactEmptyComponentInjection = { injectEmptyComponentFactory: function (factory) { emptyComponentFactory = factory; } }; var ReactEmptyComponent = { create: function (instantiate) { return emptyComponentFactory(instantiate); } }; ReactEmptyComponent.injection = ReactEmptyComponentInjection; module.exports = ReactEmptyComponent; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); var genericComponentClass = null; var textComponentClass = null; var ReactHostComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function (componentClass) { genericComponentClass = componentClass; }, // This accepts a text component class that takes the text string to be // rendered as props. injectTextComponentClass: function (componentClass) { textComponentClass = componentClass; } }; /** * Get a host internal component class for a specific tag. * * @param {ReactElement} element The element to create. * @return {function} The internal class constructor function. */ function createInternalComponent(element) { !genericComponentClass ? process.env.NODE_ENV !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : _prodInvariant('111', element.type) : void 0; return new genericComponentClass(element); } /** * @param {ReactText} text * @return {ReactComponent} */ function createInstanceForText(text) { return new textComponentClass(text); } /** * @param {ReactComponent} component * @return {boolean} */ function isTextComponent(component) { return component instanceof textComponentClass; } var ReactHostComponent = { createInternalComponent: createInternalComponent, createInstanceForText: createInstanceForText, isTextComponent: isTextComponent, injection: ReactHostComponentInjection }; module.exports = ReactHostComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 133 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var nextDebugID = 1; function getNextDebugID() { return nextDebugID++; } module.exports = getNextDebugID; /***/ }, /* 134 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; module.exports = KeyEscapeUtils; /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var ReactCurrentOwner = __webpack_require__(16); var REACT_ELEMENT_TYPE = __webpack_require__(136); var getIteratorFn = __webpack_require__(137); var invariant = __webpack_require__(14); var KeyEscapeUtils = __webpack_require__(134); var warning = __webpack_require__(17); var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * This is inlined from ReactElement since this file is shared between * isomorphic and renderers. We could extract this to a * */ /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || // The following is inlined from ReactElement. This means we can optimize // some checks. React Fiber also inlines this logic for similar purposes. type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if (process.env.NODE_ENV !== 'production') { var mapsAsChildrenAddendum = ''; if (ReactCurrentOwner.current) { var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName(); if (mapsAsChildrenOwnerName) { mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.'; } } process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if (process.env.NODE_ENV !== 'production') { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 136 */ /***/ function(module, exports) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; module.exports = REACT_ELEMENT_TYPE; /***/ }, /* 137 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var KeyEscapeUtils = __webpack_require__(134); var traverseAllChildren = __webpack_require__(135); var warning = __webpack_require__(17); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = __webpack_require__(32); } /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. * @param {number=} selfDebugID Optional debugID of the current internal instance. */ function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) { // We found a component instance. if (traverseContext && typeof traverseContext === 'object') { var result = traverseContext; var keyUnique = result[name] === undefined; if (process.env.NODE_ENV !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = __webpack_require__(32); } if (!keyUnique) { process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0; } } if (keyUnique && child != null) { result[name] = child; } } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children, selfDebugID) { if (children == null) { return children; } var result = {}; if (process.env.NODE_ENV !== 'production') { traverseAllChildren(children, function (traverseContext, child, name) { return flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID); }, result); } else { traverseAllChildren(children, flattenSingleChildIntoContext, result); } return result; } module.exports = flattenChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var PooledClass = __webpack_require__(56); var Transaction = __webpack_require__(74); var ReactInstrumentation = __webpack_require__(68); var ReactServerUpdateQueue = __webpack_require__(140); /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = []; if (process.env.NODE_ENV !== 'production') { TRANSACTION_WRAPPERS.push({ initialize: ReactInstrumentation.debugTool.onBeginFlush, close: ReactInstrumentation.debugTool.onEndFlush }); } var noopCallbackQueue = { enqueue: function () {} }; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.useCreateElement = false; this.updateQueue = new ReactServerUpdateQueue(this); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap procedures. */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return noopCallbackQueue; }, /** * @return {object} The queue to collect React async events. */ getUpdateQueue: function () { return this.updateQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () {}, checkpoint: function () {}, rollback: function () {} }; _assign(ReactServerRenderingTransaction.prototype, Transaction, Mixin); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ReactUpdateQueue = __webpack_require__(141); var warning = __webpack_require__(17); function warnNoop(publicInstance, callerName) { if (process.env.NODE_ENV !== 'production') { var constructor = publicInstance.constructor; process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0; } } /** * This is the update queue used for server rendering. * It delegates to ReactUpdateQueue while server rendering is in progress and * switches to ReactNoopUpdateQueue after the transaction has completed. * @class ReactServerUpdateQueue * @param {Transaction} transaction */ var ReactServerUpdateQueue = function () { function ReactServerUpdateQueue(transaction) { _classCallCheck(this, ReactServerUpdateQueue); this.transaction = transaction; } /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ ReactServerUpdateQueue.prototype.isMounted = function isMounted(publicInstance) { return false; }; /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ ReactServerUpdateQueue.prototype.enqueueCallback = function enqueueCallback(publicInstance, callback, callerName) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueCallback(publicInstance, callback, callerName); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ ReactServerUpdateQueue.prototype.enqueueForceUpdate = function enqueueForceUpdate(publicInstance) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueForceUpdate(publicInstance); } else { warnNoop(publicInstance, 'forceUpdate'); } }; /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object|function} completeState Next state. * @internal */ ReactServerUpdateQueue.prototype.enqueueReplaceState = function enqueueReplaceState(publicInstance, completeState) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueReplaceState(publicInstance, completeState); } else { warnNoop(publicInstance, 'replaceState'); } }; /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object|function} partialState Next partial state to be merged with state. * @internal */ ReactServerUpdateQueue.prototype.enqueueSetState = function enqueueSetState(publicInstance, partialState) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueSetState(publicInstance, partialState); } else { warnNoop(publicInstance, 'setState'); } }; return ReactServerUpdateQueue; }(); module.exports = ReactServerUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var ReactCurrentOwner = __webpack_require__(16); var ReactInstanceMap = __webpack_require__(122); var ReactInstrumentation = __webpack_require__(68); var ReactUpdates = __webpack_require__(62); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); function enqueueUpdate(internalInstance) { ReactUpdates.enqueueUpdate(internalInstance); } function formatUnexpectedArgument(arg) { var type = typeof arg; if (type !== 'object') { return type; } var displayName = arg.constructor && arg.constructor.name || type; var keys = Object.keys(arg); if (keys.length > 0 && keys.length < 20) { return displayName + ' (keys: ' + keys.join(', ') + ')'; } return displayName; } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { var internalInstance = ReactInstanceMap.get(publicInstance); if (!internalInstance) { if (process.env.NODE_ENV !== 'production') { var ctor = publicInstance.constructor; // Only warn when we have a callerName. Otherwise we should be silent. // We're probably calling from enqueueCallback. We don't want to warn // there because we already warned for the corresponding lifecycle method. process.env.NODE_ENV !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, ctor && (ctor.displayName || ctor.name) || 'ReactClass') : void 0; } return null; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition (such as ' + 'within `render` or another component\'s constructor). Render methods ' + 'should be a pure function of props and state; constructor ' + 'side-effects are an anti-pattern, but can be moved to ' + '`componentWillMount`.', callerName) : void 0; } return internalInstance; } /** * ReactUpdateQueue allows for state updates to be scheduled into a later * reconciliation step. */ var ReactUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } var internalInstance = ReactInstanceMap.get(publicInstance); if (internalInstance) { // During componentWillMount and render this will still be null but after // that will always render to something. At least for now. So we can use // this hack. return !!internalInstance._renderedComponent; } else { return false; } }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @param {string} callerName Name of the calling function in the public API. * @internal */ enqueueCallback: function (publicInstance, callback, callerName) { ReactUpdateQueue.validateCallback(callback, callerName); var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); // Previously we would throw an error if we didn't have an internal // instance. Since we want to make it a no-op instead, we mirror the same // behavior we have in other enqueue* methods. // We also need to ignore callbacks in componentWillMount. See // enqueueUpdates. if (!internalInstance) { return null; } if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. Alternatively, we can disallow // componentWillMount during server-side rendering. enqueueUpdate(internalInstance); }, enqueueCallbackInternal: function (internalInstance, callback) { if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } enqueueUpdate(internalInstance); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate'); if (!internalInstance) { return; } internalInstance._pendingForceUpdate = true; enqueueUpdate(internalInstance); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; enqueueUpdate(internalInstance); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onSetState(); process.env.NODE_ENV !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : void 0; } var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState'); if (!internalInstance) { return; } var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState); enqueueUpdate(internalInstance); }, enqueueElementInternal: function (internalInstance, nextElement, nextContext) { internalInstance._pendingElement = nextElement; // TODO: introduce _pendingContext instead of setting it directly. internalInstance._context = nextContext; enqueueUpdate(internalInstance); }, validateCallback: function (callback, callerName) { !(!callback || typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.', callerName, formatUnexpectedArgument(callback)) : _prodInvariant('122', callerName, formatUnexpectedArgument(callback)) : void 0; } }; module.exports = ReactUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 142 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var emptyFunction = __webpack_require__(18); var warning = __webpack_require__(17); var validateDOMNesting = emptyFunction; if (process.env.NODE_ENV !== 'production') { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; var emptyAncestorInfo = { current: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }; var updatedAncestorInfo = function (oldInfo, tag, instance) { var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo); var info = { tag: tag, instance: instance }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.current = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body'; case '#document': return tag === 'html'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'body': case 'caption': case 'col': case 'colgroup': case 'frame': case 'head': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ var findInvalidAncestorForTag = function (tag, ancestorInfo) { switch (tag) { case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dialog': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'main': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': case 'pre': case 'listing': case 'table': case 'hr': case 'xmp': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; /** * Given a ReactCompositeComponent instance, return a list of its recursive * owners, starting at the root and ending with the instance itself. */ var findOwnerStack = function (instance) { if (!instance) { return []; } var stack = []; do { stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }; var didWarn = {}; validateDOMNesting = function (childTag, childText, childInstance, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; if (childText != null) { process.env.NODE_ENV !== 'production' ? warning(childTag == null, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0; childTag = '#text'; } var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var problematic = invalidParent || invalidAncestor; if (problematic) { var ancestorTag = problematic.tag; var ancestorInstance = problematic.instance; var childOwner = childInstance && childInstance._currentElement._owner; var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner; var childOwners = findOwnerStack(childOwner); var ancestorOwners = findOwnerStack(ancestorOwner); var minStackLen = Math.min(childOwners.length, ancestorOwners.length); var i; var deepestCommon = -1; for (i = 0; i < minStackLen; i++) { if (childOwners[i] === ancestorOwners[i]) { deepestCommon = i; } else { break; } } var UNKNOWN = '(unknown)'; var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ownerInfo = [].concat( // If the parent and child instances have a common owner ancestor, start // with that -- otherwise we just start with the parent's owners. deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag, // If we're warning about an invalid (non-parent) ancestry, add '...' invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > '); var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; var tagDisplayName = childTag; var whitespaceInfo = ''; if (childTag === '#text') { if (/\S/.test(childText)) { tagDisplayName = 'Text nodes'; } else { tagDisplayName = 'Whitespace text nodes'; whitespaceInfo = ' Make sure you don\'t have any extra whitespace between tags on ' + 'each line of your source code.'; } } else { tagDisplayName = '<' + childTag + '>'; } if (invalidParent) { var info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.'; } process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s ' + 'See %s.%s', tagDisplayName, ancestorTag, whitespaceInfo, ownerInfo, info) : void 0; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>. See %s.', tagDisplayName, ancestorTag, ownerInfo) : void 0; } } }; validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; // For testing validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); }; } module.exports = validateDOMNesting; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var DOMLazyTree = __webpack_require__(87); var ReactDOMComponentTree = __webpack_require__(40); var ReactDOMEmptyComponent = function (instantiate) { // ReactCompositeComponent uses this: this._currentElement = null; // ReactDOMComponentTree uses these: this._hostNode = null; this._hostParent = null; this._hostContainerInfo = null; this._domID = 0; }; _assign(ReactDOMEmptyComponent.prototype, { mountComponent: function (transaction, hostParent, hostContainerInfo, context) { var domID = hostContainerInfo._idCounter++; this._domID = domID; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var nodeValue = ' react-empty: ' + this._domID + ' '; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var node = ownerDocument.createComment(nodeValue); ReactDOMComponentTree.precacheNode(this, node); return DOMLazyTree(node); } else { if (transaction.renderToStaticMarkup) { // Normally we'd insert a comment node, but since this is a situation // where React won't take over (static pages), we can simply return // nothing. return ''; } return '<!--' + nodeValue + '-->'; } }, receiveComponent: function () {}, getHostNode: function () { return ReactDOMComponentTree.getNodeFromInstance(this); }, unmountComponent: function () { ReactDOMComponentTree.uncacheNode(this); } }); module.exports = ReactDOMEmptyComponent; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var invariant = __webpack_require__(14); /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA, instB) { !('_hostNode' in instA) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; !('_hostNode' in instB) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; var depthA = 0; for (var tempA = instA; tempA; tempA = tempA._hostParent) { depthA++; } var depthB = 0; for (var tempB = instB; tempB; tempB = tempB._hostParent) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = instA._hostParent; depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = instB._hostParent; depthB--; } // Walk in lockstep until we find a match. var depth = depthA; while (depth--) { if (instA === instB) { return instA; } instA = instA._hostParent; instB = instB._hostParent; } return null; } /** * Return if A is an ancestor of B. */ function isAncestor(instA, instB) { !('_hostNode' in instA) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0; !('_hostNode' in instB) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0; while (instB) { if (instB === instA) { return true; } instB = instB._hostParent; } return false; } /** * Return the parent instance of the passed-in instance. */ function getParentInstance(inst) { !('_hostNode' in inst) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : _prodInvariant('36') : void 0; return inst._hostParent; } /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ function traverseTwoPhase(inst, fn, arg) { var path = []; while (inst) { path.push(inst); inst = inst._hostParent; } var i; for (i = path.length; i-- > 0;) { fn(path[i], 'captured', arg); } for (i = 0; i < path.length; i++) { fn(path[i], 'bubbled', arg); } } /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * Does not invoke the callback on the nearest common ancestor because nothing * "entered" or "left" that element. */ function traverseEnterLeave(from, to, fn, argFrom, argTo) { var common = from && to ? getLowestCommonAncestor(from, to) : null; var pathFrom = []; while (from && from !== common) { pathFrom.push(from); from = from._hostParent; } var pathTo = []; while (to && to !== common) { pathTo.push(to); to = to._hostParent; } var i; for (i = 0; i < pathFrom.length; i++) { fn(pathFrom[i], 'bubbled', argFrom); } for (i = pathTo.length; i-- > 0;) { fn(pathTo[i], 'captured', argTo); } } module.exports = { isAncestor: isAncestor, getLowestCommonAncestor: getLowestCommonAncestor, getParentInstance: getParentInstance, traverseTwoPhase: traverseTwoPhase, traverseEnterLeave: traverseEnterLeave }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41), _assign = __webpack_require__(10); var DOMChildrenOperations = __webpack_require__(86); var DOMLazyTree = __webpack_require__(87); var ReactDOMComponentTree = __webpack_require__(40); var escapeTextContentForBrowser = __webpack_require__(92); var invariant = __webpack_require__(14); var validateDOMNesting = __webpack_require__(142); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings between comment nodes so that they * can undergo the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactDOMTextComponent * @extends ReactComponent * @internal */ var ReactDOMTextComponent = function (text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text; this._stringText = '' + text; // ReactDOMComponentTree uses these: this._hostNode = null; this._hostParent = null; // Properties this._domID = 0; this._mountIndex = 0; this._closingComment = null; this._commentNodes = null; }; _assign(ReactDOMTextComponent.prototype, { /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { if (process.env.NODE_ENV !== 'production') { var parentInfo; if (hostParent != null) { parentInfo = hostParent._ancestorInfo; } else if (hostContainerInfo != null) { parentInfo = hostContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting(null, this._stringText, this, parentInfo); } } var domID = hostContainerInfo._idCounter++; var openingValue = ' react-text: ' + domID + ' '; var closingValue = ' /react-text '; this._domID = domID; this._hostParent = hostParent; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var openingComment = ownerDocument.createComment(openingValue); var closingComment = ownerDocument.createComment(closingValue); var lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment()); DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment)); if (this._stringText) { DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText))); } DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment)); ReactDOMComponentTree.precacheNode(this, openingComment); this._closingComment = closingComment; return lazyTree; } else { var escapedText = escapeTextContentForBrowser(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this between comment nodes for the reasons stated // above, but since this is a situation where React won't take over // (static pages), we can simply return the text as it is. return escapedText; } return '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->'; } }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function (nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; var commentNodes = this.getHostNode(); DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText); } } }, getHostNode: function () { var hostNode = this._commentNodes; if (hostNode) { return hostNode; } if (!this._closingComment) { var openingComment = ReactDOMComponentTree.getNodeFromInstance(this); var node = openingComment.nextSibling; while (true) { !(node != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing closing comment for text component %s', this._domID) : _prodInvariant('67', this._domID) : void 0; if (node.nodeType === 8 && node.nodeValue === ' /react-text ') { this._closingComment = node; break; } node = node.nextSibling; } } hostNode = [this._hostNode, this._closingComment]; this._commentNodes = hostNode; return hostNode; }, unmountComponent: function () { this._closingComment = null; this._commentNodes = null; ReactDOMComponentTree.uncacheNode(this); } }); module.exports = ReactDOMTextComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var ReactUpdates = __webpack_require__(62); var Transaction = __webpack_require__(74); var emptyFunction = __webpack_require__(18); var RESET_BATCHED_UPDATES = { initialize: emptyFunction, close: function () { ReactDefaultBatchingStrategy.isBatchingUpdates = false; } }; var FLUSH_BATCHED_UPDATES = { initialize: emptyFunction, close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) }; var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } _assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; } }); var transaction = new ReactDefaultBatchingStrategyTransaction(); var ReactDefaultBatchingStrategy = { isBatchingUpdates: false, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function (callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { return callback(a, b, c, d, e); } else { return transaction.perform(callback, null, a, b, c, d, e); } } }; module.exports = ReactDefaultBatchingStrategy; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var EventListener = __webpack_require__(148); var ExecutionEnvironment = __webpack_require__(54); var PooledClass = __webpack_require__(56); var ReactDOMComponentTree = __webpack_require__(40); var ReactUpdates = __webpack_require__(62); var getEventTarget = __webpack_require__(75); var getUnboundedScrollPosition = __webpack_require__(149); /** * Find the deepest React component completely containing the root of the * passed-in instance (for use when entire React trees are nested within each * other). If React trees are not nested, returns null. */ function findParent(inst) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. while (inst._hostParent) { inst = inst._hostParent; } var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst); var container = rootNode.parentNode; return ReactDOMComponentTree.getClosestInstanceFromNode(container); } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.ancestors = []; } _assign(TopLevelCallbackBookKeeping.prototype, { destructor: function () { this.topLevelType = null; this.nativeEvent = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler); function handleTopLevelImpl(bookKeeping) { var nativeEventTarget = getEventTarget(bookKeeping.nativeEvent); var targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(nativeEventTarget); // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = targetInst; do { bookKeeping.ancestors.push(ancestor); ancestor = ancestor && findParent(ancestor); } while (ancestor); for (var i = 0; i < bookKeeping.ancestors.length; i++) { targetInst = bookKeeping.ancestors[i]; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function (handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function (enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function () { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} element Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function (topLevelType, handlerBaseName, element) { if (!element) { return null; } return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} element Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function (topLevelType, handlerBaseName, element) { if (!element) { return null; } return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, monitorScrollValue: function (refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, 'scroll', callback); }, dispatchEvent: function (topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; module.exports = ReactEventListener; /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * * 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. * * @typechecks */ var emptyFunction = __webpack_require__(18); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function listen(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function remove() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function remove() { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function capture(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, true); return { remove: function remove() { target.removeEventListener(eventType, callback, true); } }; } else { if (process.env.NODE_ENV !== 'production') { console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); } return { remove: emptyFunction }; } }, registerDefault: function registerDefault() {} }; module.exports = EventListener; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 149 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(42); var EventPluginHub = __webpack_require__(48); var EventPluginUtils = __webpack_require__(50); var ReactComponentEnvironment = __webpack_require__(121); var ReactEmptyComponent = __webpack_require__(131); var ReactBrowserEventEmitter = __webpack_require__(111); var ReactHostComponent = __webpack_require__(132); var ReactUpdates = __webpack_require__(62); var ReactInjection = { Component: ReactComponentEnvironment.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventPluginUtils: EventPluginUtils.injection, EventEmitter: ReactBrowserEventEmitter.injection, HostComponent: ReactHostComponent.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(10); var CallbackQueue = __webpack_require__(63); var PooledClass = __webpack_require__(56); var ReactBrowserEventEmitter = __webpack_require__(111); var ReactInputSelection = __webpack_require__(152); var ReactInstrumentation = __webpack_require__(68); var Transaction = __webpack_require__(74); var ReactUpdateQueue = __webpack_require__(141); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function () { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); ReactBrowserEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` * restores the previous value. */ close: function (previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function () { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function () { this.reactMountReady.notifyAll(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING]; if (process.env.NODE_ENV !== 'production') { TRANSACTION_WRAPPERS.push({ initialize: ReactInstrumentation.debugTool.onBeginFlush, close: ReactInstrumentation.debugTool.onEndFlush }); } /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction(useCreateElement) { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactDOMTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = useCreateElement; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap procedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * @return {object} The queue to collect React async events. */ getUpdateQueue: function () { return ReactUpdateQueue; }, /** * Save current transaction state -- if the return value from this method is * passed to `rollback`, the transaction will be reset to that state. */ checkpoint: function () { // reactMountReady is the our only stateful wrapper return this.reactMountReady.checkpoint(); }, rollback: function (checkpoint) { this.reactMountReady.rollback(checkpoint); }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; } }; _assign(ReactReconcileTransaction.prototype, Transaction, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMSelection = __webpack_require__(153); var containsNode = __webpack_require__(155); var focusNode = __webpack_require__(100); var getActiveElement = __webpack_require__(158); function isInDocument(node) { return containsNode(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function (elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); }, getSelectionInformation: function () { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function (priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); } focusNode(priorFocusedElem); } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function (input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || { start: 0, end: 0 }; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function (input, offsets) { var start = offsets.start; var end = offsets.end; if (end === undefined) { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection; /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(54); var getNodeForCharacterOffset = __webpack_require__(154); var getTextContentAccessor = __webpack_require__(57); /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * Get the appropriate anchor and focus node/offset pairs for IE. * * The catch here is that IE's selection API doesn't provide information * about whether the selection is forward or backward, so we have to * behave as though it's always forward. * * IE text differs from modern selection in that it behaves as though * block elements end with a new line. This means character offsets will * differ between the two APIs. * * @param {DOMElement} node * @return {object} */ function getIEOffsets(node) { var selection = document.selection; var selectedRange = selection.createRange(); var selectedLength = selectedRange.text.length; // Duplicate selection so we can move range without breaking user selection. var fromStart = selectedRange.duplicate(); fromStart.moveToElementText(node); fromStart.setEndPoint('EndToStart', selectedRange); var startOffset = fromStart.text.length; var endOffset = startOffset + selectedLength; return { start: startOffset, end: endOffset }; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection && window.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode; var anchorOffset = selection.anchorOffset; var focusNode = selection.focusNode; var focusOffset = selection.focusOffset; var currentRange = selection.getRangeAt(0); // In Firefox, range.startContainer and range.endContainer can be "anonymous // divs", e.g. the up/down buttons on an <input type="number">. Anonymous // divs do not seem to expose properties, triggering a "Permission denied // error" if any of its properties are accessed. The only seemingly possible // way to avoid erroring is to access a property that typically works for // non-anonymous divs and catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ currentRange.startContainer.nodeType; currentRange.endContainer.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (offsets.end === undefined) { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programmatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window); var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; /***/ }, /* 154 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var isTextNode = __webpack_require__(156); /*eslint-disable no-bitwise */ /** * Checks if a given DOM node contains or is another DOM node. */ function containsNode(outerNode, innerNode) { if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { return containsNode(outerNode, innerNode.parentNode); } else if ('contains' in outerNode) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } module.exports = containsNode; /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var isNode = __webpack_require__(157); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode; /***/ }, /* 157 */ /***/ function(module, exports) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } module.exports = isNode; /***/ }, /* 158 */ /***/ function(module, exports) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /* eslint-disable fb-www/typeof-undefined */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document or document body is not * yet defined. */ function getActiveElement() /*?DOMElement*/{ if (typeof document === 'undefined') { return null; } try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; /***/ }, /* 159 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var NS = { xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; // We use attributes for everything SVG so let's avoid some duplication and run // code instead. // The following are all specified in the HTML config already so we exclude here. // - class (as className) // - color // - height // - id // - lang // - max // - media // - method // - min // - name // - style // - target // - type // - width var ATTRS = { accentHeight: 'accent-height', accumulate: 0, additive: 0, alignmentBaseline: 'alignment-baseline', allowReorder: 'allowReorder', alphabetic: 0, amplitude: 0, arabicForm: 'arabic-form', ascent: 0, attributeName: 'attributeName', attributeType: 'attributeType', autoReverse: 'autoReverse', azimuth: 0, baseFrequency: 'baseFrequency', baseProfile: 'baseProfile', baselineShift: 'baseline-shift', bbox: 0, begin: 0, bias: 0, by: 0, calcMode: 'calcMode', capHeight: 'cap-height', clip: 0, clipPath: 'clip-path', clipRule: 'clip-rule', clipPathUnits: 'clipPathUnits', colorInterpolation: 'color-interpolation', colorInterpolationFilters: 'color-interpolation-filters', colorProfile: 'color-profile', colorRendering: 'color-rendering', contentScriptType: 'contentScriptType', contentStyleType: 'contentStyleType', cursor: 0, cx: 0, cy: 0, d: 0, decelerate: 0, descent: 0, diffuseConstant: 'diffuseConstant', direction: 0, display: 0, divisor: 0, dominantBaseline: 'dominant-baseline', dur: 0, dx: 0, dy: 0, edgeMode: 'edgeMode', elevation: 0, enableBackground: 'enable-background', end: 0, exponent: 0, externalResourcesRequired: 'externalResourcesRequired', fill: 0, fillOpacity: 'fill-opacity', fillRule: 'fill-rule', filter: 0, filterRes: 'filterRes', filterUnits: 'filterUnits', floodColor: 'flood-color', floodOpacity: 'flood-opacity', focusable: 0, fontFamily: 'font-family', fontSize: 'font-size', fontSizeAdjust: 'font-size-adjust', fontStretch: 'font-stretch', fontStyle: 'font-style', fontVariant: 'font-variant', fontWeight: 'font-weight', format: 0, from: 0, fx: 0, fy: 0, g1: 0, g2: 0, glyphName: 'glyph-name', glyphOrientationHorizontal: 'glyph-orientation-horizontal', glyphOrientationVertical: 'glyph-orientation-vertical', glyphRef: 'glyphRef', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', hanging: 0, horizAdvX: 'horiz-adv-x', horizOriginX: 'horiz-origin-x', ideographic: 0, imageRendering: 'image-rendering', 'in': 0, in2: 0, intercept: 0, k: 0, k1: 0, k2: 0, k3: 0, k4: 0, kernelMatrix: 'kernelMatrix', kernelUnitLength: 'kernelUnitLength', kerning: 0, keyPoints: 'keyPoints', keySplines: 'keySplines', keyTimes: 'keyTimes', lengthAdjust: 'lengthAdjust', letterSpacing: 'letter-spacing', lightingColor: 'lighting-color', limitingConeAngle: 'limitingConeAngle', local: 0, markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', markerHeight: 'markerHeight', markerUnits: 'markerUnits', markerWidth: 'markerWidth', mask: 0, maskContentUnits: 'maskContentUnits', maskUnits: 'maskUnits', mathematical: 0, mode: 0, numOctaves: 'numOctaves', offset: 0, opacity: 0, operator: 0, order: 0, orient: 0, orientation: 0, origin: 0, overflow: 0, overlinePosition: 'overline-position', overlineThickness: 'overline-thickness', paintOrder: 'paint-order', panose1: 'panose-1', pathLength: 'pathLength', patternContentUnits: 'patternContentUnits', patternTransform: 'patternTransform', patternUnits: 'patternUnits', pointerEvents: 'pointer-events', points: 0, pointsAtX: 'pointsAtX', pointsAtY: 'pointsAtY', pointsAtZ: 'pointsAtZ', preserveAlpha: 'preserveAlpha', preserveAspectRatio: 'preserveAspectRatio', primitiveUnits: 'primitiveUnits', r: 0, radius: 0, refX: 'refX', refY: 'refY', renderingIntent: 'rendering-intent', repeatCount: 'repeatCount', repeatDur: 'repeatDur', requiredExtensions: 'requiredExtensions', requiredFeatures: 'requiredFeatures', restart: 0, result: 0, rotate: 0, rx: 0, ry: 0, scale: 0, seed: 0, shapeRendering: 'shape-rendering', slope: 0, spacing: 0, specularConstant: 'specularConstant', specularExponent: 'specularExponent', speed: 0, spreadMethod: 'spreadMethod', startOffset: 'startOffset', stdDeviation: 'stdDeviation', stemh: 0, stemv: 0, stitchTiles: 'stitchTiles', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strikethroughPosition: 'strikethrough-position', strikethroughThickness: 'strikethrough-thickness', string: 0, stroke: 0, strokeDasharray: 'stroke-dasharray', strokeDashoffset: 'stroke-dashoffset', strokeLinecap: 'stroke-linecap', strokeLinejoin: 'stroke-linejoin', strokeMiterlimit: 'stroke-miterlimit', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', surfaceScale: 'surfaceScale', systemLanguage: 'systemLanguage', tableValues: 'tableValues', targetX: 'targetX', targetY: 'targetY', textAnchor: 'text-anchor', textDecoration: 'text-decoration', textRendering: 'text-rendering', textLength: 'textLength', to: 0, transform: 0, u1: 0, u2: 0, underlinePosition: 'underline-position', underlineThickness: 'underline-thickness', unicode: 0, unicodeBidi: 'unicode-bidi', unicodeRange: 'unicode-range', unitsPerEm: 'units-per-em', vAlphabetic: 'v-alphabetic', vHanging: 'v-hanging', vIdeographic: 'v-ideographic', vMathematical: 'v-mathematical', values: 0, vectorEffect: 'vector-effect', version: 0, vertAdvY: 'vert-adv-y', vertOriginX: 'vert-origin-x', vertOriginY: 'vert-origin-y', viewBox: 'viewBox', viewTarget: 'viewTarget', visibility: 0, widths: 0, wordSpacing: 'word-spacing', writingMode: 'writing-mode', x: 0, xHeight: 'x-height', x1: 0, x2: 0, xChannelSelector: 'xChannelSelector', xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', xmlns: 0, xmlnsXlink: 'xmlns:xlink', xmlLang: 'xml:lang', xmlSpace: 'xml:space', y: 0, y1: 0, y2: 0, yChannelSelector: 'yChannelSelector', z: 0, zoomAndPan: 'zoomAndPan' }; var SVGDOMPropertyConfig = { Properties: {}, DOMAttributeNamespaces: { xlinkActuate: NS.xlink, xlinkArcrole: NS.xlink, xlinkHref: NS.xlink, xlinkRole: NS.xlink, xlinkShow: NS.xlink, xlinkTitle: NS.xlink, xlinkType: NS.xlink, xmlBase: NS.xml, xmlLang: NS.xml, xmlSpace: NS.xml }, DOMAttributeNames: {} }; Object.keys(ATTRS).forEach(function (key) { SVGDOMPropertyConfig.Properties[key] = 0; if (ATTRS[key]) { SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key]; } }); module.exports = SVGDOMPropertyConfig; /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPropagators = __webpack_require__(47); var ExecutionEnvironment = __webpack_require__(54); var ReactDOMComponentTree = __webpack_require__(40); var ReactInputSelection = __webpack_require__(152); var SyntheticEvent = __webpack_require__(59); var getActiveElement = __webpack_require__(158); var isTextInputElement = __webpack_require__(77); var shallowEqual = __webpack_require__(129); var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; var eventTypes = { select: { phasedRegistrationNames: { bubbled: 'onSelect', captured: 'onSelectCapture' }, dependencies: ['topBlur', 'topContextMenu', 'topFocus', 'topKeyDown', 'topKeyUp', 'topMouseDown', 'topMouseUp', 'topSelectionChange'] } }; var activeElement = null; var activeElementInst = null; var lastSelection = null; var mouseDown = false; // Track whether a listener exists for this plugin. If none exist, we do // not extract events. See #3639. var hasListener = false; /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @return {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (!hasListener) { return null; } var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; switch (topLevelType) { // Track the input node that has focus. case 'topFocus': if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') { activeElement = targetNode; activeElementInst = targetInst; lastSelection = null; } break; case 'topBlur': activeElement = null; activeElementInst = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case 'topMouseDown': mouseDown = true; break; case 'topContextMenu': case 'topMouseUp': mouseDown = false; return constructSelectEvent(nativeEvent, nativeEventTarget); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case 'topSelectionChange': if (skipSelectionChangeEvent) { break; } // falls through case 'topKeyDown': case 'topKeyUp': return constructSelectEvent(nativeEvent, nativeEventTarget); } return null; }, didPutListener: function (inst, registrationName, listener) { if (registrationName === 'onSelect') { hasListener = true; } } }; module.exports = SelectEventPlugin; /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var EventListener = __webpack_require__(148); var EventPropagators = __webpack_require__(47); var ReactDOMComponentTree = __webpack_require__(40); var SyntheticAnimationEvent = __webpack_require__(162); var SyntheticClipboardEvent = __webpack_require__(163); var SyntheticEvent = __webpack_require__(59); var SyntheticFocusEvent = __webpack_require__(164); var SyntheticKeyboardEvent = __webpack_require__(165); var SyntheticMouseEvent = __webpack_require__(80); var SyntheticDragEvent = __webpack_require__(168); var SyntheticTouchEvent = __webpack_require__(169); var SyntheticTransitionEvent = __webpack_require__(170); var SyntheticUIEvent = __webpack_require__(81); var SyntheticWheelEvent = __webpack_require__(171); var emptyFunction = __webpack_require__(18); var getEventCharCode = __webpack_require__(166); var invariant = __webpack_require__(14); /** * Turns * ['abort', ...] * into * eventTypes = { * 'abort': { * phasedRegistrationNames: { * bubbled: 'onAbort', * captured: 'onAbortCapture', * }, * dependencies: ['topAbort'], * }, * ... * }; * topLevelEventsToDispatchConfig = { * 'topAbort': { sameConfig } * }; */ var eventTypes = {}; var topLevelEventsToDispatchConfig = {}; ['abort', 'animationEnd', 'animationIteration', 'animationStart', 'blur', 'canPlay', 'canPlayThrough', 'click', 'contextMenu', 'copy', 'cut', 'doubleClick', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'focus', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'mouseDown', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp', 'paste', 'pause', 'play', 'playing', 'progress', 'rateChange', 'reset', 'scroll', 'seeked', 'seeking', 'stalled', 'submit', 'suspend', 'timeUpdate', 'touchCancel', 'touchEnd', 'touchMove', 'touchStart', 'transitionEnd', 'volumeChange', 'waiting', 'wheel'].forEach(function (event) { var capitalizedEvent = event[0].toUpperCase() + event.slice(1); var onEvent = 'on' + capitalizedEvent; var topEvent = 'top' + capitalizedEvent; var type = { phasedRegistrationNames: { bubbled: onEvent, captured: onEvent + 'Capture' }, dependencies: [topEvent] }; eventTypes[event] = type; topLevelEventsToDispatchConfig[topEvent] = type; }); var onClickListeners = {}; function getDictionaryKey(inst) { // Prevents V8 performance issue: // https://github.com/facebook/react/pull/7232 return '.' + inst._rootNodeID; } function isInteractive(tag) { return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea'; } var SimpleEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case 'topAbort': case 'topCanPlay': case 'topCanPlayThrough': case 'topDurationChange': case 'topEmptied': case 'topEncrypted': case 'topEnded': case 'topError': case 'topInput': case 'topInvalid': case 'topLoad': case 'topLoadedData': case 'topLoadedMetadata': case 'topLoadStart': case 'topPause': case 'topPlay': case 'topPlaying': case 'topProgress': case 'topRateChange': case 'topReset': case 'topSeeked': case 'topSeeking': case 'topStalled': case 'topSubmit': case 'topSuspend': case 'topTimeUpdate': case 'topVolumeChange': case 'topWaiting': // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case 'topKeyPress': // Firefox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case 'topKeyDown': case 'topKeyUp': EventConstructor = SyntheticKeyboardEvent; break; case 'topBlur': case 'topFocus': EventConstructor = SyntheticFocusEvent; break; case 'topClick': // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case 'topDoubleClick': case 'topMouseDown': case 'topMouseMove': case 'topMouseUp': // TODO: Disabled elements should not respond to mouse events /* falls through */ case 'topMouseOut': case 'topMouseOver': case 'topContextMenu': EventConstructor = SyntheticMouseEvent; break; case 'topDrag': case 'topDragEnd': case 'topDragEnter': case 'topDragExit': case 'topDragLeave': case 'topDragOver': case 'topDragStart': case 'topDrop': EventConstructor = SyntheticDragEvent; break; case 'topTouchCancel': case 'topTouchEnd': case 'topTouchMove': case 'topTouchStart': EventConstructor = SyntheticTouchEvent; break; case 'topAnimationEnd': case 'topAnimationIteration': case 'topAnimationStart': EventConstructor = SyntheticAnimationEvent; break; case 'topTransitionEnd': EventConstructor = SyntheticTransitionEvent; break; case 'topScroll': EventConstructor = SyntheticUIEvent; break; case 'topWheel': EventConstructor = SyntheticWheelEvent; break; case 'topCopy': case 'topCut': case 'topPaste': EventConstructor = SyntheticClipboardEvent; break; } !EventConstructor ? process.env.NODE_ENV !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : _prodInvariant('86', topLevelType) : void 0; var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget); EventPropagators.accumulateTwoPhaseDispatches(event); return event; }, didPutListener: function (inst, registrationName, listener) { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html if (registrationName === 'onClick' && !isInteractive(inst._tag)) { var key = getDictionaryKey(inst); var node = ReactDOMComponentTree.getNodeFromInstance(inst); if (!onClickListeners[key]) { onClickListeners[key] = EventListener.listen(node, 'click', emptyFunction); } } }, willDeleteListener: function (inst, registrationName) { if (registrationName === 'onClick' && !isInteractive(inst._tag)) { var key = getDictionaryKey(inst); onClickListeners[key].remove(); delete onClickListeners[key]; } } }; module.exports = SimpleEventPlugin; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(59); /** * @interface Event * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent */ var AnimationEventInterface = { animationName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface); module.exports = SyntheticAnimationEvent; /***/ }, /* 163 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(59); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = { clipboardData: function (event) { return 'clipboardData' in event ? event.clipboardData : window.clipboardData; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticUIEvent = __webpack_require__(81); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = { relatedTarget: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; /***/ }, /* 165 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticUIEvent = __webpack_require__(81); var getEventCharCode = __webpack_require__(166); var getEventKey = __webpack_require__(167); var getEventModifierState = __webpack_require__(83); /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = { key: getEventKey, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, getModifierState: getEventModifierState, // Legacy Interface charCode: function (event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function (event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function (event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; /***/ }, /* 166 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } module.exports = getEventCharCode; /***/ }, /* 167 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var getEventCharCode = __webpack_require__(166); /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { 'Esc': 'Escape', 'Spacebar': ' ', 'Left': 'ArrowLeft', 'Up': 'ArrowUp', 'Right': 'ArrowRight', 'Down': 'ArrowDown', 'Del': 'Delete', 'Win': 'OS', 'Menu': 'ContextMenu', 'Apps': 'ContextMenu', 'Scroll': 'ScrollLock', 'MozPrintableKey': 'Unidentified' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { 8: 'Backspace', 9: 'Tab', 12: 'Clear', 13: 'Enter', 16: 'Shift', 17: 'Control', 18: 'Alt', 19: 'Pause', 20: 'CapsLock', 27: 'Escape', 32: ' ', 33: 'PageUp', 34: 'PageDown', 35: 'End', 36: 'Home', 37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown', 45: 'Insert', 46: 'Delete', 112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6', 118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12', 144: 'NumLock', 145: 'ScrollLock', 224: 'Meta' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } module.exports = getEventKey; /***/ }, /* 168 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticMouseEvent = __webpack_require__(80); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = { dataTransfer: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; /***/ }, /* 169 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticUIEvent = __webpack_require__(81); var getEventModifierState = __webpack_require__(83); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null, getModifierState: getEventModifierState }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; /***/ }, /* 170 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(59); /** * @interface Event * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events- * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent */ var TransitionEventInterface = { propertyName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface); module.exports = SyntheticTransitionEvent; /***/ }, /* 171 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticMouseEvent = __webpack_require__(80); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function (event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY: function (event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0; }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; /***/ }, /* 172 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var DOMLazyTree = __webpack_require__(87); var DOMProperty = __webpack_require__(42); var React = __webpack_require__(8); var ReactBrowserEventEmitter = __webpack_require__(111); var ReactCurrentOwner = __webpack_require__(16); var ReactDOMComponentTree = __webpack_require__(40); var ReactDOMContainerInfo = __webpack_require__(173); var ReactDOMFeatureFlags = __webpack_require__(174); var ReactFeatureFlags = __webpack_require__(64); var ReactInstanceMap = __webpack_require__(122); var ReactInstrumentation = __webpack_require__(68); var ReactMarkupChecksum = __webpack_require__(175); var ReactReconciler = __webpack_require__(65); var ReactUpdateQueue = __webpack_require__(141); var ReactUpdates = __webpack_require__(62); var emptyObject = __webpack_require__(26); var instantiateReactComponent = __webpack_require__(124); var invariant = __webpack_require__(14); var setInnerHTML = __webpack_require__(89); var shouldUpdateReactComponent = __webpack_require__(130); var warning = __webpack_require__(17); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var ROOT_ATTR_NAME = DOMProperty.ROOT_ATTRIBUTE_NAME; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; var instancesByReactRootID = {}; /** * Finds the index of the first character * that's not common between the two given strings. * * @return {number} the index of the character where the strings diverge */ function firstDifferenceIndex(string1, string2) { var minLen = Math.min(string1.length, string2.length); for (var i = 0; i < minLen; i++) { if (string1.charAt(i) !== string2.charAt(i)) { return i; } } return string1.length === string2.length ? -1 : minLen; } /** * @param {DOMElement|DOMDocument} container DOM element that may contain * a React component * @return {?*} DOM element that may have the reactRoot ID, or null. */ function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOC_NODE_TYPE) { return container.documentElement; } else { return container.firstChild; } } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Mounts this component and inserts it into the DOM. * * @param {ReactComponent} componentInstance The instance to mount. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function mountComponentIntoNode(wrapperInstance, container, transaction, shouldReuseMarkup, context) { var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var wrappedElement = wrapperInstance._currentElement.props.child; var type = wrappedElement.type; markerName = 'React mount: ' + (typeof type === 'string' ? type : type.displayName || type.name); console.time(markerName); } var markup = ReactReconciler.mountComponent(wrapperInstance, transaction, null, ReactDOMContainerInfo(wrapperInstance, container), context, 0 /* parentDebugID */ ); if (markerName) { console.timeEnd(markerName); } wrapperInstance._renderedComponent._topLevelWrapper = wrapperInstance; ReactMount._mountImageIntoNode(markup, container, wrapperInstance, shouldReuseMarkup, transaction); } /** * Batched mount. * * @param {ReactComponent} componentInstance The instance to mount. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */ !shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement); transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context); ReactUpdates.ReactReconcileTransaction.release(transaction); } /** * Unmounts a component and removes it from the DOM. * * @param {ReactComponent} instance React component instance. * @param {DOMElement} container DOM element to unmount from. * @final * @internal * @see {ReactMount.unmountComponentAtNode} */ function unmountComponentFromNode(instance, container, safely) { if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onBeginFlush(); } ReactReconciler.unmountComponent(instance, safely); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onEndFlush(); } if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } } /** * True if the supplied DOM node has a direct React-rendered child that is * not a React root element. Useful for warning in `render`, * `unmountComponentAtNode`, etc. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM element contains a direct child that was * rendered by React but is not a root element. * @internal */ function hasNonRootReactChild(container) { var rootEl = getReactRootElementInContainer(container); if (rootEl) { var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl); return !!(inst && inst._hostParent); } } /** * True if the supplied DOM node is a React DOM element and * it has been rendered by another copy of React. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM has been rendered by another copy of React * @internal */ function nodeIsRenderedByOtherInstance(container) { var rootEl = getReactRootElementInContainer(container); return !!(rootEl && isReactNode(rootEl) && !ReactDOMComponentTree.getInstanceFromNode(rootEl)); } /** * True if the supplied DOM node is a valid node element. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM is a valid DOM node. * @internal */ function isValidContainer(node) { return !!(node && (node.nodeType === ELEMENT_NODE_TYPE || node.nodeType === DOC_NODE_TYPE || node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)); } /** * True if the supplied DOM node is a valid React node element. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM is a valid React DOM node. * @internal */ function isReactNode(node) { return isValidContainer(node) && (node.hasAttribute(ROOT_ATTR_NAME) || node.hasAttribute(ATTR_NAME)); } function getHostRootInstanceInContainer(container) { var rootEl = getReactRootElementInContainer(container); var prevHostInstance = rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl); return prevHostInstance && !prevHostInstance._hostParent ? prevHostInstance : null; } function getTopLevelWrapperInContainer(container) { var root = getHostRootInstanceInContainer(container); return root ? root._hostContainerInfo._topLevelWrapper : null; } /** * Temporary (?) hack so that we can store all top-level pending updates on * composites instead of having to worry about different types of components * here. */ var topLevelRootCounter = 1; var TopLevelWrapper = function () { this.rootID = topLevelRootCounter++; }; TopLevelWrapper.prototype.isReactComponent = {}; if (process.env.NODE_ENV !== 'production') { TopLevelWrapper.displayName = 'TopLevelWrapper'; } TopLevelWrapper.prototype.render = function () { return this.props.child; }; TopLevelWrapper.isReactTopLevelWrapper = true; /** * Mounting is the process of initializing a React component by creating its * representative DOM elements and inserting them into a supplied `container`. * Any prior content inside `container` is destroyed in the process. * * ReactMount.render( * component, * document.getElementById('container') * ); * * <div id="container"> <-- Supplied `container`. * <div data-reactid=".3"> <-- Rendered reactRoot of React * // ... component. * </div> * </div> * * Inside of `container`, the first element rendered is the "reactRoot". */ var ReactMount = { TopLevelWrapper: TopLevelWrapper, /** * Used by devtools. The keys are not important. */ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function (container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactElement} nextElement component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function (prevComponent, nextElement, nextContext, container, callback) { ReactMount.scrollMonitor(container, function () { ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement, nextContext); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); } }); return prevComponent; }, /** * Render a new component into the DOM. Hooked by hooks! * * @param {ReactElement} nextElement element to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : _prodInvariant('37') : void 0; ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var componentInstance = instantiateReactComponent(nextElement, false); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context); var wrapperID = componentInstance._instance.rootID; instancesByReactRootID[wrapperID] = componentInstance; return componentInstance; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactComponent} parentComponent The conceptual parent of this render tree. * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { !(parentComponent != null && ReactInstanceMap.has(parentComponent)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : _prodInvariant('38') : void 0; return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback); }, _renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { ReactUpdateQueue.validateCallback(callback, 'ReactDOM.render'); !React.isValidElement(nextElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : // Check if it quacks like an element nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : _prodInvariant('39', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : void 0; process.env.NODE_ENV !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : void 0; var nextWrappedElement = React.createElement(TopLevelWrapper, { child: nextElement }); var nextContext; if (parentComponent) { var parentInst = ReactInstanceMap.get(parentComponent); nextContext = parentInst._processChildContext(parentInst._context); } else { nextContext = emptyObject; } var prevComponent = getTopLevelWrapperInContainer(container); if (prevComponent) { var prevWrappedElement = prevComponent._currentElement; var prevElement = prevWrappedElement.props.child; if (shouldUpdateReactComponent(prevElement, nextElement)) { var publicInst = prevComponent._renderedComponent.getPublicInstance(); var updatedCallback = callback && function () { callback.call(publicInst); }; ReactMount._updateRootComponent(prevComponent, nextWrappedElement, nextContext, container, updatedCallback); return publicInst; } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement); var containerHasNonRootReactChild = hasNonRootReactChild(container); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : void 0; if (!containerHasReactMarkup || reactRootElement.nextSibling) { var rootElementSibling = reactRootElement; while (rootElementSibling) { if (internalGetID(rootElementSibling)) { process.env.NODE_ENV !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : void 0; break; } rootElementSibling = rootElementSibling.nextSibling; } } } var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild; var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, nextContext)._renderedComponent.getPublicInstance(); if (callback) { callback.call(component); } return component; }, /** * Renders a React component into the DOM in the supplied `container`. * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.render * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ render: function (nextElement, container, callback) { return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback); }, /** * Unmounts and destroys the React component rendered in the `container`. * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.unmountcomponentatnode * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function (container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : _prodInvariant('40') : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!nodeIsRenderedByOtherInstance(container), 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by another copy of React.') : void 0; } var prevComponent = getTopLevelWrapperInContainer(container); if (!prevComponent) { // Check if the node being unmounted was rendered by React, but isn't a // root node. var containerHasNonRootReactChild = hasNonRootReactChild(container); // Check if the container itself is a React root node. var isContainerReactRoot = container.nodeType === 1 && container.hasAttribute(ROOT_ATTR_NAME); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : void 0; } return false; } delete instancesByReactRootID[prevComponent._instance.rootID]; ReactUpdates.batchedUpdates(unmountComponentFromNode, prevComponent, container, false); return true; }, _mountImageIntoNode: function (markup, container, instance, shouldReuseMarkup, transaction) { !isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : _prodInvariant('41') : void 0; if (shouldReuseMarkup) { var rootElement = getReactRootElementInContainer(container); if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) { ReactDOMComponentTree.precacheNode(instance, rootElement); return; } else { var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); var rootMarkup = rootElement.outerHTML; rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum); var normalizedMarkup = markup; if (process.env.NODE_ENV !== 'production') { // because rootMarkup is retrieved from the DOM, various normalizations // will have occurred which will not be present in `markup`. Here, // insert markup into a <div> or <iframe> depending on the container // type to perform the same normalizations before comparing. var normalizer; if (container.nodeType === ELEMENT_NODE_TYPE) { normalizer = document.createElement('div'); normalizer.innerHTML = markup; normalizedMarkup = normalizer.innerHTML; } else { normalizer = document.createElement('iframe'); document.body.appendChild(normalizer); normalizer.contentDocument.write(markup); normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML; document.body.removeChild(normalizer); } } var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup); var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20); !(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using server rendering but the checksum was invalid. This usually means you rendered a different component type or props on the client from the one on the server, or your render() methods are impure. React cannot handle this case due to cross-browser quirks by rendering at the document root. You should look for environment dependent code in your components and ensure the props are the same client and server side:\n%s', difference) : _prodInvariant('42', difference) : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : void 0; } } } !(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but you didn\'t use server rendering. We can\'t do this without using server rendering due to cross-browser quirks. See ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('43') : void 0; if (transaction.useCreateElement) { while (container.lastChild) { container.removeChild(container.lastChild); } DOMLazyTree.insertTreeBefore(container, markup, null); } else { setInnerHTML(container, markup); ReactDOMComponentTree.precacheNode(instance, container.firstChild); } if (process.env.NODE_ENV !== 'production') { var hostNode = ReactDOMComponentTree.getInstanceFromNode(container.firstChild); if (hostNode._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: hostNode._debugID, type: 'mount', payload: markup.toString() }); } } } }; module.exports = ReactMount; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var validateDOMNesting = __webpack_require__(142); var DOC_NODE_TYPE = 9; function ReactDOMContainerInfo(topLevelWrapper, node) { var info = { _topLevelWrapper: topLevelWrapper, _idCounter: 1, _ownerDocument: node ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument : null, _node: node, _tag: node ? node.nodeName.toLowerCase() : null, _namespaceURI: node ? node.namespaceURI : null }; if (process.env.NODE_ENV !== 'production') { info._ancestorInfo = node ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null; } return info; } module.exports = ReactDOMContainerInfo; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 174 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMFeatureFlags = { useCreateElement: true, useFiber: false }; module.exports = ReactDOMFeatureFlags; /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var adler32 = __webpack_require__(176); var TAG_END = /\/?>/; var COMMENT_START = /^<\!\-\-/; var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function (markup) { var checksum = adler32(markup); // Add checksum (handle both parent tags, comments and self-closing tags) if (COMMENT_START.test(markup)) { return markup; } else { return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); } }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function (markup, element) { var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; /***/ }, /* 176 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var MOD = 65521; // adler32 is not cryptographically strong, and is only used to sanity check that // markup generated on the server matches the markup generated on the client. // This implementation (a modified version of the SheetJS version) has been optimized // for our use case, at the expense of conforming to the adler32 specification // for non-ascii inputs. function adler32(data) { var a = 1; var b = 0; var i = 0; var l = data.length; var m = l & ~0x3; while (i < m) { var n = Math.min(i + 4096, m); for (; i < n; i += 4) { b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); } a %= MOD; b %= MOD; } for (; i < l; i++) { b += a += data.charCodeAt(i); } a %= MOD; b %= MOD; return a | b << 16; } module.exports = adler32; /***/ }, /* 177 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; module.exports = '15.4.2'; /***/ }, /* 178 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(41); var ReactCurrentOwner = __webpack_require__(16); var ReactDOMComponentTree = __webpack_require__(40); var ReactInstanceMap = __webpack_require__(122); var getHostComponentFromComposite = __webpack_require__(179); var invariant = __webpack_require__(14); var warning = __webpack_require__(17); /** * Returns the DOM node rendered by this element. * * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode * * @param {ReactComponent|DOMElement} componentOrElement * @return {?DOMElement} The root node of this element. */ function findDOMNode(componentOrElement) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } var inst = ReactInstanceMap.get(componentOrElement); if (inst) { inst = getHostComponentFromComposite(inst); return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null; } if (typeof componentOrElement.render === 'function') { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : _prodInvariant('44') : void 0; } else { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement)) : void 0; } } module.exports = findDOMNode; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactNodeTypes = __webpack_require__(126); function getHostComponentFromComposite(inst) { var type; while ((type = inst._renderedNodeType) === ReactNodeTypes.COMPOSITE) { inst = inst._renderedComponent; } if (type === ReactNodeTypes.HOST) { return inst._renderedComponent; } else if (type === ReactNodeTypes.EMPTY) { return null; } } module.exports = getHostComponentFromComposite; /***/ }, /* 180 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactMount = __webpack_require__(172); module.exports = ReactMount.renderSubtreeIntoContainer; /***/ }, /* 181 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(42); var EventPluginRegistry = __webpack_require__(49); var ReactComponentTreeHook = __webpack_require__(32); var warning = __webpack_require__(17); if (process.env.NODE_ENV !== 'production') { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true, autoFocus: true, defaultValue: true, valueLink: true, defaultChecked: true, checkedLink: true, innerHTML: true, suppressContentEditableWarning: true, onFocusIn: true, onFocusOut: true }; var warnedProperties = {}; var validateProperty = function (tagName, name, debugID) { if (DOMProperty.properties.hasOwnProperty(name) || DOMProperty.isCustomAttribute(name)) { return true; } if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return true; } if (EventPluginRegistry.registrationNameModules.hasOwnProperty(name)) { return true; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; var registrationName = EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? EventPluginRegistry.possibleRegistrationNames[lowerCasedName] : null; if (standardName != null) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown DOM property %s. Did you mean %s?%s', name, standardName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; return true; } else if (registrationName != null) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown event handler property %s. Did you mean `%s`?%s', name, registrationName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; return true; } else { // We were unable to guess which prop the user intended. // It is likely that the user was just blindly spreading/forwarding props // Components should be careful to only render valid props/attributes. // Warning will be invoked in warnUnknownProperties to allow grouping. return false; } }; } var warnUnknownProperties = function (debugID, element) { var unknownProps = []; for (var key in element.props) { var isValid = validateProperty(element.type, key, debugID); if (!isValid) { unknownProps.push(key); } } var unknownPropString = unknownProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (unknownProps.length === 1) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown prop %s on <%s> tag. Remove this prop from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } else if (unknownProps.length > 1) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown props %s on <%s> tag. Remove these props from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } }; function handleElement(debugID, element) { if (element == null || typeof element.type !== 'string') { return; } if (element.type.indexOf('-') >= 0 || element.props.is) { return; } warnUnknownProperties(debugID, element); } var ReactDOMUnknownPropertyHook = { onBeforeMountComponent: function (debugID, element) { handleElement(debugID, element); }, onBeforeUpdateComponent: function (debugID, element) { handleElement(debugID, element); } }; module.exports = ReactDOMUnknownPropertyHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 182 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactComponentTreeHook = __webpack_require__(32); var warning = __webpack_require__(17); var didWarnValueNull = false; function handleElement(debugID, element) { if (element == null) { return; } if (element.type !== 'input' && element.type !== 'textarea' && element.type !== 'select') { return; } if (element.props != null && element.props.value === null && !didWarnValueNull) { process.env.NODE_ENV !== 'production' ? warning(false, '`value` prop on `%s` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.%s', element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; didWarnValueNull = true; } } var ReactDOMNullInputValuePropHook = { onBeforeMountComponent: function (debugID, element) { handleElement(debugID, element); }, onBeforeUpdateComponent: function (debugID, element) { handleElement(debugID, element); } }; module.exports = ReactDOMNullInputValuePropHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 183 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(42); var ReactComponentTreeHook = __webpack_require__(32); var warning = __webpack_require__(17); var warnedProperties = {}; var rARIA = new RegExp('^(aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$'); function validateProperty(tagName, name, debugID) { if (warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return true; } if (rARIA.test(name)) { var lowerCasedName = name.toLowerCase(); var standardName = DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; // If this is an aria-* attribute, but is not listed in the known DOM // DOM properties, then it is an invalid aria-* attribute. if (standardName == null) { warnedProperties[name] = true; return false; } // aria-* attributes should be lowercase; suggest the lowercase version. if (name !== standardName) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown ARIA attribute %s. Did you mean %s?%s', name, standardName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; warnedProperties[name] = true; return true; } } return true; } function warnInvalidARIAProps(debugID, element) { var invalidProps = []; for (var key in element.props) { var isValid = validateProperty(element.type, key, debugID); if (!isValid) { invalidProps.push(key); } } var unknownPropString = invalidProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (invalidProps.length === 1) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } else if (invalidProps.length > 1) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } } function handleElement(debugID, element) { if (element == null || typeof element.type !== 'string') { return; } if (element.type.indexOf('-') >= 0 || element.props.is) { return; } warnInvalidARIAProps(debugID, element); } var ReactDOMInvalidARIAHook = { onBeforeMountComponent: function (debugID, element) { if (process.env.NODE_ENV !== 'production') { handleElement(debugID, element); } }, onBeforeUpdateComponent: function (debugID, element) { if (process.env.NODE_ENV !== 'production') { handleElement(debugID, element); } } }; module.exports = ReactDOMInvalidARIAHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(7); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(38); var _reactDom2 = _interopRequireDefault(_reactDom); var _utilities = __webpack_require__(185); var _utilities2 = _interopRequireDefault(_utilities); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Riverine = _react2.default.createClass({ displayName: 'Riverine', propTypes: { hover: _react2.default.PropTypes.bool.isRequired, source: _react2.default.PropTypes.string.isRequired }, scrubberClicked: false, duration: '', audioNode: '', playButton: '', playHead: '', timeline: '', timelineWidth: '', sourceDuration: '', componentDidMount: function componentDidMount() { var that = _reactDom2.default.findDOMNode(this).children[0].children[0].children[0]; this.audioNode = that.children[0]; this.duration = that.children[3]; this.hover = that.children[2].children[0]; this.playButton = that.children[1].children[0].children[0]; this.playHead = that.children[2].children[0].children[0]; this.timeline = that.children[2]; console.log(this.timeline); this.timelineWidth = this.timeline.offsetWidth - this.playHead.offsetWidth; window.addEventListener('mouseup', this.mouseUp, false); window.addEventListener('resize', this.handleResize, false); this.audioNode.addEventListener('timeupdate', this.handlePlayhead, false); this.timeline.addEventListener('mouseover', this.handleHover, false); }, addHover: function addHover(e) { var positionOffset = _utilities2.default.handleOffsetParent(this.timeline); var newMargLeft = e.pageX - positionOffset; if (newMargLeft >= 0 && newMargLeft <= this.timelineWidth) { this.hover.style.width = newMargLeft + 'px'; }; if (newMargLeft < 0) { this.hover.style.width = '0px'; }; if (newMargLeft > this.timelineWidth) { this.hover.style.width = this.timelineWidth + 'px'; }; }, clickPercent: function clickPercent(e) { var positionOffset = _utilities2.default.handleOffsetParent(this.timeline); return (e.pageX - positionOffset) / this.timelineWidth; }, returnDuration: function returnDuration() { this.sourceDuration = this.audioNode.duration; this.duration.innerHTML = _utilities2.default.handleTime(this.audioNode.duration); this.updateTime(); }, play: function play() { if (this.audioNode.paused) { this.audioNode.play(); this.playButton.children[0].classList = ''; this.playButton.children[0].classList = 'fa fa-pause'; } else { this.audioNode.pause(); this.playButton.children[0].classList = ''; this.playButton.children[0].classList = 'fa fa-play'; }; }, updateTime: function updateTime() { this.duration.innerHTML = _utilities2.default.handleTime(this.audioNode.currentTime) + ' / ' + _utilities2.default.handleTime(this.audioNode.duration); if (this.audioNode.currentTime === this.sourceDuration) { this.playButton.children[0].classList = ''; this.playButton.children[0].classList = 'fa fa-play'; }; }, handleHover: function handleHover() { if (this.props.hover) { this.timeline.addEventListener('mousemove', this.addHover, false); this.timeline.addEventListener('mouseout', this.removeHover, false); }; }, handlePlayhead: function handlePlayhead() { var playPercent = this.timelineWidth * (this.audioNode.currentTime / this.audioNode.duration); if (this.props.margin) { this.playHead.style.marginLeft = playPercent + 'px'; } else { this.playHead.style.paddingLeft = playPercent + 'px'; }; }, handleResize: function handleResize() { var padding = this.playHead.style.paddingLeft; var p = void 0; padding === '' ? p = 0 : p = parseInt(padding.substring(0, padding.length - 2)); this.timelineWidth = this.timeline.offsetWidth - this.playHead.offsetWidth + p; this.handlePlayhead(); }, mouseDown: function mouseDown() { this.scrubberClicked = true; window.addEventListener('mousemove', this.moveplayhead, true); this.audioNode.removeEventListener('timeupdate', this.handlePlayhead, false); }, mouseUp: function mouseUp(e) { if (this.scrubberClicked === false) { return; }; this.moveplayhead(e); window.removeEventListener('mousemove', this.moveplayhead, true); this.audioNode.currentTime = this.audioNode.duration * this.clickPercent(e); this.audioNode.addEventListener('timeupdate', this.handlePlayhead, false); this.scrubberClicked = false; }, moveplayhead: function moveplayhead(e) { var positionOffset = _utilities2.default.handleOffsetParent(this.timeline); var newMargLeft = e.pageX - positionOffset; var n = this.playHead.style.width; if (newMargLeft >= 0 && newMargLeft <= this.timelineWidth) { n = newMargLeft + 'px'; }; if (newMargLeft < 0) { n = '0px'; }; if (newMargLeft > this.timelineWidth) { n = this.timelineWidth + 'px'; }; }, removeHover: function removeHover() { this.hover.style.width = '0px'; }, render: function render() { return _react2.default.createElement( 'div', null, _react2.default.createElement( 'div', { className: 'riverine-player' }, _react2.default.createElement( 'div', { className: 'riverine-type-single' }, _react2.default.createElement( 'div', { className: 'riverine-gui riverine-interface riverine-player' }, _react2.default.createElement( 'audio', { id: _utilities2.default.newId('audio-'), preload: 'auto', onDurationChange: this.returnDuration, onTimeUpdate: this.updateTime, loop: this.props.loop }, _react2.default.createElement('source', { src: this.props.source }) ), _react2.default.createElement( 'ul', { className: 'riverine-controls' }, _react2.default.createElement( 'li', { className: 'play-button-container' }, _react2.default.createElement( 'a', { className: 'riverine-play', onClick: this.play }, _react2.default.createElement('i', { className: 'fa fa-play' }) ) ) ), _react2.default.createElement( 'div', { className: 'riverine-progress', onMouseDown: this.mouseDown }, _react2.default.createElement( 'div', { className: 'riverine-seek-bar' }, _react2.default.createElement('div', { className: 'riverine-play-bar', onMouseDown: this.mouseDown }) ) ), _react2.default.createElement( 'div', { className: 'riverine-time-holder' }, _react2.default.createElement('span', null) ) ) ) ) ); } }); exports.default = Riverine; /***/ }, /* 185 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var utilities = { handleTime: function handleTime(duration) { var sec_num = parseInt(duration, 10); var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - hours * 3600) / 60); var seconds = sec_num - hours * 3600 - minutes * 60; if (hours < 10 && hours > 0) { hours = '0' + hours + ':'; } else { hours = ''; } if (minutes < 10) { minutes = '0' + minutes; } if (seconds < 10) { seconds = '0' + seconds; } return hours + minutes + ':' + seconds; }, handleOffsetParent: function handleOffsetParent(node) { var n = node; var o = 0; while (n.offsetParent !== null) { o = o + n.offsetLeft; n = n.offsetParent; }; return o; }, newId: function newId(prefix) { return '' + prefix + new Date().getTime(); } }; exports.default = utilities; /***/ } /******/ ]);
update bundle
public/bundle.js
update bundle
<ide><path>ublic/bundle.js <ide> this.playButton = that.children[1].children[0].children[0]; <ide> this.playHead = that.children[2].children[0].children[0]; <ide> this.timeline = that.children[2]; <del> console.log(this.timeline); <ide> this.timelineWidth = this.timeline.offsetWidth - this.playHead.offsetWidth; <ide> <ide> window.addEventListener('mouseup', this.mouseUp, false);
Java
apache-2.0
16e030c0637c700711025124a32bf2238fb5f27d
0
tensorflow/java,tensorflow/java,tensorflow/java,tensorflow/java
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. 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. ==============================================================================*/ package org.tensorflow.op; import org.tensorflow.ExecutionEnvironment; import org.tensorflow.Operand; import org.tensorflow.OperationBuilder; import java.util.ArrayList; /** * Manages groups of related properties when creating Tensorflow Operations, such as a common name * prefix. * * <p>A {@code Scope} is a container for common properties applied to TensorFlow Ops. Normal user * code initializes a {@code Scope} and provides it to Operation building classes. For example: * * <pre>{@code * Scope scope = new Scope(graph); * Constant c = Constant.create(scope, 42); * }</pre> * * <p>An Operation building class acquires a Scope, and uses it to set properties on the underlying * Tensorflow ops. For example: * * <pre>{@code * // An operator class that adds a constant. * public class Constant { * public static Constant create(Scope scope, ...) { * scope.graph().opBuilder( * "Const", scope.makeOpName("Const")) * .setAttr(...) * .build() * ... * } * } * }</pre> * * <p><b>Scope hierarchy:</b> * * <p>A {@code Scope} provides various {@code with()} methods that create a new scope. The new scope * typically has one property changed while other properties are inherited from the parent scope. * * <p>An example using {@code Constant} implemented as before: * * <pre>{@code * Scope root = new Scope(graph); * * // The linear subscope will generate names like linear/... * Scope linear = Scope.withSubScope("linear"); * * // This op name will be "linear/W" * Constant.create(linear.withName("W"), ...); * * // This op will be "linear/Const", using the default * // name provided by Constant * Constant.create(linear, ...); * * // This op will be "linear/Const_1", using the default * // name provided by Constant and making it unique within * // this scope * Constant.create(linear, ...); * }</pre> * * <p>Scope objects are <b>not</b> thread-safe. */ public final class Scope { /** * Create a new top-level scope. * * @param env The execution environment used by the scope. */ public Scope(ExecutionEnvironment env) { this(env, new NameScope(), new ArrayList<Operand<?>>()); } /** Returns the execution environment used by this scope. */ public ExecutionEnvironment env() { return env; } /** * Returns a new scope where added operations will have the provided name prefix. * * <p>Ops created with this scope will have {@code name/childScopeName/} as the prefix. The actual * name will be unique in the returned scope. All other properties are inherited from the current * scope. * * <p>The child scope name must match the regular expression {@code [A-Za-z0-9.][A-Za-z0-9_.\-]*} * * @param childScopeName name for the new child scope * @return a new subscope * @throws IllegalArgumentException if the name is invalid */ public Scope withSubScope(String childScopeName) { return new Scope(env, nameScope.withSubScope(childScopeName), controlDependencies); } /** * Return a new scope that uses the provided name for an op. * * <p>Operations created within this scope will have a name of the form {@code * name/opName[_suffix]}. This lets you name a specific operator more meaningfully. * * <p>Names must match the regular expression {@code [A-Za-z0-9.][A-Za-z0-9_.\-]*} * * @param opName name for an operator in the returned scope * @return a new Scope that uses opName for operations. * @throws IllegalArgumentException if the name is invalid */ public Scope withName(String opName) { return new Scope(env, nameScope.withName(opName), controlDependencies); } /** * Create a unique name for an operator, using a provided default if necessary. * * <p>This is normally called only by operator building classes. * * <p>This method generates a unique name, appropriate for the name scope controlled by this * instance. Typical operator building code might look like * * <pre>{@code * scope.env().opBuilder("Const", scope.makeOpName("Const"))... * }</pre> * * <p><b>Note:</b> if you provide a composite operator building class (i.e, a class that creates a * set of related operations by calling other operator building code), the provided name will act * as a subscope to all underlying operators. * * @param defaultName name for the underlying operator. * @return unique name for the operator. * @throws IllegalArgumentException if the default name is invalid. */ public String makeOpName(String defaultName) { return nameScope.makeOpName(defaultName); } private Scope(ExecutionEnvironment env, NameScope nameScope, Iterable<Operand<?>> controlDependencies) { this.env = env; this.nameScope = nameScope; this.controlDependencies = controlDependencies; } /** * Returns a new scope where added operations will have the provided control dependencies. * * <p>Ops created with this scope will have a control edge from each of the provided controls. * All other properties are inherited from the current scope. * * @param controls control dependencies for ops created with the returned scope * @return a new scope with the provided control dependencies */ public Scope withControlDependencies(Iterable<Operand<?>> controls) { return new Scope(env, nameScope, controls); } /** * Adds each Operand in controlDependencies as a control input to the provided builder. * * @param builder OperationBuilder to add control inputs to */ public OperationBuilder applyControlDependencies(OperationBuilder builder) { for (Operand<?> control : controlDependencies) { builder = builder.addControlInput(control.asOutput().op()); } return builder; } private final ExecutionEnvironment env; private final Iterable<Operand<?>> controlDependencies; private final NameScope nameScope; }
tensorflow-core/tensorflow-core-api/src/main/java/org/tensorflow/op/Scope.java
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. 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. ==============================================================================*/ package org.tensorflow.op; import org.tensorflow.ExecutionEnvironment; /** * Manages groups of related properties when creating Tensorflow Operations, such as a common name * prefix. * * <p>A {@code Scope} is a container for common properties applied to TensorFlow Ops. Normal user * code initializes a {@code Scope} and provides it to Operation building classes. For example: * * <pre>{@code * Scope scope = new Scope(graph); * Constant c = Constant.create(scope, 42); * }</pre> * * <p>An Operation building class acquires a Scope, and uses it to set properties on the underlying * Tensorflow ops. For example: * * <pre>{@code * // An operator class that adds a constant. * public class Constant { * public static Constant create(Scope scope, ...) { * scope.graph().opBuilder( * "Const", scope.makeOpName("Const")) * .setAttr(...) * .build() * ... * } * } * }</pre> * * <p><b>Scope hierarchy:</b> * * <p>A {@code Scope} provides various {@code with()} methods that create a new scope. The new scope * typically has one property changed while other properties are inherited from the parent scope. * * <p>An example using {@code Constant} implemented as before: * * <pre>{@code * Scope root = new Scope(graph); * * // The linear subscope will generate names like linear/... * Scope linear = Scope.withSubScope("linear"); * * // This op name will be "linear/W" * Constant.create(linear.withName("W"), ...); * * // This op will be "linear/Const", using the default * // name provided by Constant * Constant.create(linear, ...); * * // This op will be "linear/Const_1", using the default * // name provided by Constant and making it unique within * // this scope * Constant.create(linear, ...); * }</pre> * * <p>Scope objects are <b>not</b> thread-safe. */ public final class Scope { /** * Create a new top-level scope. * * @param env The execution environment used by the scope. */ public Scope(ExecutionEnvironment env) { this(env, new NameScope()); } /** Returns the execution environment used by this scope. */ public ExecutionEnvironment env() { return env; } /** * Returns a new scope where added operations will have the provided name prefix. * * <p>Ops created with this scope will have {@code name/childScopeName/} as the prefix. The actual * name will be unique in the returned scope. All other properties are inherited from the current * scope. * * <p>The child scope name must match the regular expression {@code [A-Za-z0-9.][A-Za-z0-9_.\-]*} * * @param childScopeName name for the new child scope * @return a new subscope * @throws IllegalArgumentException if the name is invalid */ public Scope withSubScope(String childScopeName) { return new Scope(env, nameScope.withSubScope(childScopeName)); } /** * Return a new scope that uses the provided name for an op. * * <p>Operations created within this scope will have a name of the form {@code * name/opName[_suffix]}. This lets you name a specific operator more meaningfully. * * <p>Names must match the regular expression {@code [A-Za-z0-9.][A-Za-z0-9_.\-]*} * * @param opName name for an operator in the returned scope * @return a new Scope that uses opName for operations. * @throws IllegalArgumentException if the name is invalid */ public Scope withName(String opName) { return new Scope(env, nameScope.withName(opName)); } /** * Create a unique name for an operator, using a provided default if necessary. * * <p>This is normally called only by operator building classes. * * <p>This method generates a unique name, appropriate for the name scope controlled by this * instance. Typical operator building code might look like * * <pre>{@code * scope.env().opBuilder("Const", scope.makeOpName("Const"))... * }</pre> * * <p><b>Note:</b> if you provide a composite operator building class (i.e, a class that creates a * set of related operations by calling other operator building code), the provided name will act * as a subscope to all underlying operators. * * @param defaultName name for the underlying operator. * @return unique name for the operator. * @throws IllegalArgumentException if the default name is invalid. */ public String makeOpName(String defaultName) { return nameScope.makeOpName(defaultName); } private Scope(ExecutionEnvironment env, NameScope nameScope) { this.env = env; this.nameScope = nameScope; } private final ExecutionEnvironment env; private final NameScope nameScope; }
[TF Java] Adds withcontrolDependencies to org.tensorflow.op.Ops Co-authored-by: Melissa Grueter <[email protected]> Co-authored-by: Samantha Andow <[email protected]>
tensorflow-core/tensorflow-core-api/src/main/java/org/tensorflow/op/Scope.java
[TF Java] Adds withcontrolDependencies to org.tensorflow.op.Ops
<ide><path>ensorflow-core/tensorflow-core-api/src/main/java/org/tensorflow/op/Scope.java <ide> package org.tensorflow.op; <ide> <ide> import org.tensorflow.ExecutionEnvironment; <add>import org.tensorflow.Operand; <add>import org.tensorflow.OperationBuilder; <add> <add>import java.util.ArrayList; <ide> <ide> /** <ide> * Manages groups of related properties when creating Tensorflow Operations, such as a common name <ide> * @param env The execution environment used by the scope. <ide> */ <ide> public Scope(ExecutionEnvironment env) { <del> this(env, new NameScope()); <add> this(env, new NameScope(), new ArrayList<Operand<?>>()); <ide> } <ide> <ide> /** Returns the execution environment used by this scope. */ <ide> * @throws IllegalArgumentException if the name is invalid <ide> */ <ide> public Scope withSubScope(String childScopeName) { <del> return new Scope(env, nameScope.withSubScope(childScopeName)); <add> return new Scope(env, nameScope.withSubScope(childScopeName), controlDependencies); <ide> } <ide> <ide> /** <ide> * @throws IllegalArgumentException if the name is invalid <ide> */ <ide> public Scope withName(String opName) { <del> return new Scope(env, nameScope.withName(opName)); <add> return new Scope(env, nameScope.withName(opName), controlDependencies); <ide> } <ide> <ide> /** <ide> return nameScope.makeOpName(defaultName); <ide> } <ide> <del> private Scope(ExecutionEnvironment env, NameScope nameScope) { <add> private Scope(ExecutionEnvironment env, NameScope nameScope, Iterable<Operand<?>> controlDependencies) { <ide> this.env = env; <ide> this.nameScope = nameScope; <add> this.controlDependencies = controlDependencies; <add> } <add> <add> /** <add> * Returns a new scope where added operations will have the provided control dependencies. <add> * <add> * <p>Ops created with this scope will have a control edge from each of the provided controls. <add> * All other properties are inherited from the current scope. <add> * <add> * @param controls control dependencies for ops created with the returned scope <add> * @return a new scope with the provided control dependencies <add> */ <add> public Scope withControlDependencies(Iterable<Operand<?>> controls) { <add> return new Scope(env, nameScope, controls); <add> } <add> <add> /** <add> * Adds each Operand in controlDependencies as a control input to the provided builder. <add> * <add> * @param builder OperationBuilder to add control inputs to <add> */ <add> public OperationBuilder applyControlDependencies(OperationBuilder builder) { <add> for (Operand<?> control : controlDependencies) { <add> builder = builder.addControlInput(control.asOutput().op()); <add> } <add> return builder; <ide> } <ide> <ide> private final ExecutionEnvironment env; <add> private final Iterable<Operand<?>> controlDependencies; <ide> private final NameScope nameScope; <ide> }
Java
apache-2.0
9cc7344fdc1d20c3ac6a30a070e49ca924ca272c
0
nssales/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,DevStreet/FinanceAnalytics,DevStreet/FinanceAnalytics,jeorme/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.timeseries; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.threeten.bp.LocalDate; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.analytics.financial.schedule.HolidayDateRemovalFunction; import com.opengamma.analytics.financial.schedule.Schedule; import com.opengamma.analytics.financial.schedule.ScheduleCalculatorFactory; import com.opengamma.analytics.financial.schedule.TimeSeriesSamplingFunction; import com.opengamma.analytics.financial.schedule.TimeSeriesSamplingFunctionFactory; import com.opengamma.analytics.financial.timeseries.util.TimeSeriesDifferenceOperator; import com.opengamma.core.config.ConfigSource; import com.opengamma.core.historicaltimeseries.HistoricalTimeSeries; import com.opengamma.core.value.MarketDataRequirementNames; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.OpenGammaCompilationContext; import com.opengamma.financial.analytics.TenorLabelledLocalDateDoubleTimeSeriesMatrix1D; import com.opengamma.financial.analytics.fxforwardcurve.FXForwardCurveDefinition; import com.opengamma.financial.analytics.ircurve.FixedIncomeStripWithSecurity; import com.opengamma.financial.analytics.ircurve.InterpolatedYieldCurveSpecificationWithSecurities; import com.opengamma.financial.analytics.ircurve.StripInstrumentType; import com.opengamma.financial.analytics.ircurve.calcconfig.ConfigDBCurveCalculationConfigSource; import com.opengamma.financial.analytics.ircurve.calcconfig.MultiCurveCalculationConfig; import com.opengamma.financial.analytics.model.curve.interestrate.FXImpliedYieldCurveFunction; import com.opengamma.financial.convention.calendar.Calendar; import com.opengamma.financial.convention.calendar.MondayToFridayCalendar; import com.opengamma.timeseries.date.localdate.LocalDateDoubleTimeSeries; import com.opengamma.util.async.AsynchronousExecution; import com.opengamma.util.money.Currency; import com.opengamma.util.money.UnorderedCurrencyPair; import com.opengamma.util.time.Tenor; /** * Calculates return series for the market instruments at the nodal points of a yield curve. */ public class YieldCurveNodeReturnSeriesFunction extends AbstractFunction.NonCompiledInvoker { private static final Logger s_logger = LoggerFactory.getLogger(YieldCurveNodeReturnSeriesFunction.class); private static final TimeSeriesDifferenceOperator DIFFERENCE = new TimeSeriesDifferenceOperator(); private static final HolidayDateRemovalFunction HOLIDAY_REMOVER = HolidayDateRemovalFunction.getInstance(); private static final Calendar WEEKEND_CALENDAR = new MondayToFridayCalendar("Weekend"); @Override public void init(final FunctionCompilationContext context) { ConfigDBCurveCalculationConfigSource.reinitOnChanges(context, this); } @Override public ComputationTargetType getTargetType() { // NOTE jonathan 2013-04-23 -- should be ComputationTargetType.NULL return ComputationTargetType.CURRENCY; } protected ValueProperties getResultProperties(final ComputationTarget target) { final ValueProperties properties = createValueProperties() .withAny(ValuePropertyNames.CURVE) .withAny(ValuePropertyNames.CURVE_CALCULATION_CONFIG) .withAny(ValuePropertyNames.SAMPLING_FUNCTION) .withAny(ValuePropertyNames.SCHEDULE_CALCULATOR) .withAny(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY) .with(HistoricalTimeSeriesFunctionUtils.INCLUDE_START_PROPERTY, HistoricalTimeSeriesFunctionUtils.YES_VALUE, HistoricalTimeSeriesFunctionUtils.NO_VALUE) .withAny(HistoricalTimeSeriesFunctionUtils.END_DATE_PROPERTY) .with(HistoricalTimeSeriesFunctionUtils.INCLUDE_END_PROPERTY, HistoricalTimeSeriesFunctionUtils.YES_VALUE, HistoricalTimeSeriesFunctionUtils.NO_VALUE) .with(ValuePropertyNames.CURRENCY, ((Currency) target.getValue()).getCode()) .with(ValuePropertyNames.TRANSFORMATION_METHOD, "None") .get(); return properties; } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { final ValueProperties properties = getResultProperties(target); return ImmutableSet.of(new ValueSpecification(ValueRequirementNames.YIELD_CURVE_RETURN_SERIES, target.toSpecification(), properties)); } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final Currency currency = (Currency) target.getValue(); final ValueProperties constraints = desiredValue.getConstraints(); final Set<String> curveNames = constraints.getValues(ValuePropertyNames.CURVE); if (curveNames == null || curveNames.size() != 1) { return null; } final String curveName = Iterables.getOnlyElement(curveNames); final Set<String> curveCalculationConfigNames = constraints.getValues(ValuePropertyNames.CURVE_CALCULATION_CONFIG); if (curveCalculationConfigNames == null || curveCalculationConfigNames.size() != 1) { return null; } final String curveCalculationConfigName = Iterables.getOnlyElement(curveCalculationConfigNames); final String ychtsStart = getYCHTSStart(constraints); if (ychtsStart == null) { return null; } final DateConstraint start = DateConstraint.parse(ychtsStart); final String returnSeriesEnd = getReturnSeriesEnd(constraints); if (returnSeriesEnd == null) { return null; } final DateConstraint end = DateConstraint.parse(returnSeriesEnd); if (start == null || end == null) { return null; } final Set<String> includeStarts = constraints.getValues(HistoricalTimeSeriesFunctionUtils.INCLUDE_START_PROPERTY); if (includeStarts != null && includeStarts.size() != 1) { return null; } final boolean includeStart = includeStarts == null ? true : HistoricalTimeSeriesFunctionUtils.YES_VALUE.equals(Iterables.getOnlyElement(includeStarts)); final Set<String> includeEnds = constraints.getValues(HistoricalTimeSeriesFunctionUtils.INCLUDE_END_PROPERTY); if (includeEnds != null && includeEnds.size() != 1) { return null; } final boolean includeEnd = includeEnds == null ? false : HistoricalTimeSeriesFunctionUtils.YES_VALUE.equals(Iterables.getOnlyElement(includeEnds)); final Set<String> samplingMethod = constraints.getValues(ValuePropertyNames.SAMPLING_FUNCTION); if (samplingMethod == null || samplingMethod.size() != 1) { return null; } final Set<String> scheduleMethod = constraints.getValues(ValuePropertyNames.SCHEDULE_CALCULATOR); if (scheduleMethod == null || scheduleMethod.size() != 1) { return null; } final Set<ValueRequirement> requirements = new HashSet<>(); requirements.add(HistoricalTimeSeriesFunctionUtils.createYCHTSRequirement(currency, curveName, MarketDataRequirementNames.MARKET_VALUE, null, start, includeStart, end, includeEnd)); final ConfigSource configSource = OpenGammaCompilationContext.getConfigSource(context); final ConfigDBCurveCalculationConfigSource curveCalculationConfigSource = new ConfigDBCurveCalculationConfigSource(configSource); final MultiCurveCalculationConfig curveCalculationConfig = curveCalculationConfigSource.getConfig(curveCalculationConfigName); if (curveCalculationConfig == null) { s_logger.error("Could not get curve calculation config called " + curveCalculationConfigName); return null; } if (FXImpliedYieldCurveFunction.FX_IMPLIED.equals(curveCalculationConfig.getCalculationMethod())) { final Currency impliedCcy = ComputationTargetType.CURRENCY.resolve(curveCalculationConfig.getTarget().getUniqueId()); final String baseCalculationConfigName = Iterables.getOnlyElement(curveCalculationConfig.getExogenousConfigData().entrySet()).getKey(); final MultiCurveCalculationConfig baseCurveCalculationConfig = curveCalculationConfigSource.getConfig(baseCalculationConfigName); final Currency baseCcy = ComputationTargetType.CURRENCY.resolve(baseCurveCalculationConfig.getTarget().getUniqueId()); requirements.add(getFXForwardCurveDefinitionRequirement(UnorderedCurrencyPair.of(impliedCcy, baseCcy), curveName)); } else { requirements.add(getCurveSpecRequirement(currency, curveName)); } return requirements; } @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) throws AsynchronousExecution { final ValueRequirement desiredValue = desiredValues.iterator().next(); final LocalDate tsStart = DateConstraint.evaluate(executionContext, getYCHTSStart(desiredValue.getConstraints())); final LocalDate returnSeriesStart = DateConstraint.evaluate(executionContext, getReturnSeriesStart(desiredValue.getConstraints())); if (tsStart.isAfter(returnSeriesStart)) { throw new OpenGammaRuntimeException("Return series start date cannot be before time-series start date"); } final LocalDate returnSeriesEnd = DateConstraint.evaluate(executionContext, getReturnSeriesEnd(desiredValue.getConstraints())); final String scheduleCalculatorName = desiredValue.getConstraint(ValuePropertyNames.SCHEDULE_CALCULATOR); final Schedule scheduleCalculator = getScheduleCalculator(scheduleCalculatorName); final String samplingFunctionName = desiredValue.getConstraint(ValuePropertyNames.SAMPLING_FUNCTION); final TimeSeriesSamplingFunction samplingFunction = getSamplingFunction(samplingFunctionName); //REVIEW emcleod should "fromEnd" be hard-coded? final LocalDate[] schedule = HOLIDAY_REMOVER.getStrippedSchedule(scheduleCalculator.getSchedule(tsStart, returnSeriesEnd, true, false), WEEKEND_CALENDAR); final ComputedValue bundleValue = inputs.getComputedValue(ValueRequirementNames.YIELD_CURVE_HISTORICAL_TIME_SERIES); final HistoricalTimeSeriesBundle bundle = (HistoricalTimeSeriesBundle) bundleValue.getValue(); final boolean includeStart = HistoricalTimeSeriesFunctionUtils.parseBoolean(bundleValue.getSpecification().getProperty(HistoricalTimeSeriesFunctionUtils.INCLUDE_START_PROPERTY)); final InterpolatedYieldCurveSpecificationWithSecurities curveSpec = (InterpolatedYieldCurveSpecificationWithSecurities) inputs.getValue(ValueRequirementNames.YIELD_CURVE_SPEC); final FXForwardCurveDefinition fxForwardCurveDefinition = (FXForwardCurveDefinition) inputs.getValue(ValueRequirementNames.FX_FORWARD_CURVE_DEFINITION); Tenor[] tenors; boolean[] sensitivityToRate; if (curveSpec != null) { final Set<FixedIncomeStripWithSecurity> strips = curveSpec.getStrips(); final int n = strips.size(); tenors = new Tenor[n]; sensitivityToRate = new boolean[n]; int i = 0; for (final FixedIncomeStripWithSecurity strip : strips) { tenors[i] = strip.getTenor(); // TODO Temporary fix as sensitivity is to rate, but historical time series is to price (= 1 - rate) sensitivityToRate[i] = strip.getInstrumentType() == StripInstrumentType.FUTURE; i++; } } else if (fxForwardCurveDefinition != null) { tenors = fxForwardCurveDefinition.getTenorsArray(); sensitivityToRate = new boolean[tenors.length]; } else { throw new OpenGammaRuntimeException("Yield curve specification and FX forward curve definition both missing. Expected one."); } final TenorLabelledLocalDateDoubleTimeSeriesMatrix1D returnSeriesVector = getReturnSeriesVector(bundle, tenors, sensitivityToRate, schedule, samplingFunction, returnSeriesStart, includeStart, desiredValue); final ValueSpecification resultSpec = new ValueSpecification(ValueRequirementNames.YIELD_CURVE_RETURN_SERIES, target.toSpecification(), desiredValue.getConstraints()); return ImmutableSet.of(new ComputedValue(resultSpec, returnSeriesVector)); } protected String getYCHTSStart(final ValueProperties constraints) { return getReturnSeriesStart(constraints); } protected String getReturnSeriesStart(final ValueProperties constraints) { final Set<String> startDates = constraints.getValues(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY); if (startDates == null || startDates.size() != 1) { return null; } return Iterables.getOnlyElement(startDates); } protected String getReturnSeriesEnd(final ValueProperties constraints) { final Set<String> endDates = constraints.getValues(HistoricalTimeSeriesFunctionUtils.END_DATE_PROPERTY); if (endDates == null || endDates.size() != 1) { return null; } return Iterables.getOnlyElement(endDates); } protected LocalDateDoubleTimeSeries getReturnSeries(final LocalDateDoubleTimeSeries ts, final ValueRequirement desiredValue) { return (LocalDateDoubleTimeSeries) DIFFERENCE.evaluate(ts); } private TenorLabelledLocalDateDoubleTimeSeriesMatrix1D getReturnSeriesVector(final HistoricalTimeSeriesBundle timeSeriesBundle, final Tenor[] tenors, final boolean[] sensitivityToRates, final LocalDate[] schedule, final TimeSeriesSamplingFunction samplingFunction, final LocalDate startDate, final boolean includeStart, final ValueRequirement desiredValue) { final LocalDateDoubleTimeSeries[] returnSeriesArray = new LocalDateDoubleTimeSeries[tenors.length]; if (tenors.length != timeSeriesBundle.size(MarketDataRequirementNames.MARKET_VALUE)) { throw new OpenGammaRuntimeException("Expected " + tenors.length + " nodal market data time-series but have " + timeSeriesBundle.size(MarketDataRequirementNames.MARKET_VALUE)); } final Iterator<HistoricalTimeSeries> tsIterator = timeSeriesBundle.iterator(MarketDataRequirementNames.MARKET_VALUE); if (tsIterator == null) { throw new OpenGammaRuntimeException("No nodal market data time-series available"); } for (int t = 0; t < tenors.length; t++) { final Tenor tenor = tenors[t]; final HistoricalTimeSeries dbNodeTimeSeries = tsIterator.next(); final boolean sensitivityToRate = sensitivityToRates[t]; if (dbNodeTimeSeries == null) { throw new OpenGammaRuntimeException("No time-series for strip with tenor " + tenor); } final LocalDateDoubleTimeSeries nodeTimeSeries = samplingFunction.getSampledTimeSeries(dbNodeTimeSeries.getTimeSeries(), schedule); LocalDateDoubleTimeSeries returnSeries = getReturnSeries(nodeTimeSeries, desiredValue); if (sensitivityToRate) { returnSeries = returnSeries.multiply(-1); } // Clip the time-series to the range originally asked for returnSeries = returnSeries.subSeries(startDate, includeStart, returnSeries.getLatestTime(), true); returnSeriesArray[t] = returnSeries; } return new TenorLabelledLocalDateDoubleTimeSeriesMatrix1D(tenors, returnSeriesArray); } //------------------------------------------------------------------------- private ValueRequirement getCurveSpecRequirement(final Currency currency, final String yieldCurveName) { final ValueProperties properties = ValueProperties.builder() .with(ValuePropertyNames.CURVE, yieldCurveName).get(); return new ValueRequirement(ValueRequirementNames.YIELD_CURVE_SPEC, ComputationTargetType.CURRENCY.specification(currency), properties); } private ValueRequirement getFXForwardCurveDefinitionRequirement(final UnorderedCurrencyPair currencies, final String curveName) { final ValueProperties properties = ValueProperties.builder() .with(ValuePropertyNames.CURVE, curveName).get(); return new ValueRequirement(ValueRequirementNames.FX_FORWARD_CURVE_DEFINITION, ComputationTargetType.UNORDERED_CURRENCY_PAIR.specification(currencies), properties); } private Schedule getScheduleCalculator(final String scheduleCalculatorName) { return ScheduleCalculatorFactory.getScheduleCalculator(scheduleCalculatorName); } private TimeSeriesSamplingFunction getSamplingFunction(final String samplingFunctionName) { return TimeSeriesSamplingFunctionFactory.getFunction(samplingFunctionName); } }
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/timeseries/YieldCurveNodeReturnSeriesFunction.java
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.timeseries; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.threeten.bp.LocalDate; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.analytics.financial.schedule.HolidayDateRemovalFunction; import com.opengamma.analytics.financial.schedule.Schedule; import com.opengamma.analytics.financial.schedule.ScheduleCalculatorFactory; import com.opengamma.analytics.financial.schedule.TimeSeriesSamplingFunction; import com.opengamma.analytics.financial.schedule.TimeSeriesSamplingFunctionFactory; import com.opengamma.analytics.financial.timeseries.util.TimeSeriesDifferenceOperator; import com.opengamma.core.config.ConfigSource; import com.opengamma.core.historicaltimeseries.HistoricalTimeSeries; import com.opengamma.core.value.MarketDataRequirementNames; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.OpenGammaCompilationContext; import com.opengamma.financial.analytics.TenorLabelledLocalDateDoubleTimeSeriesMatrix1D; import com.opengamma.financial.analytics.fxforwardcurve.FXForwardCurveDefinition; import com.opengamma.financial.analytics.ircurve.FixedIncomeStripWithSecurity; import com.opengamma.financial.analytics.ircurve.InterpolatedYieldCurveSpecificationWithSecurities; import com.opengamma.financial.analytics.ircurve.StripInstrumentType; import com.opengamma.financial.analytics.ircurve.calcconfig.ConfigDBCurveCalculationConfigSource; import com.opengamma.financial.analytics.ircurve.calcconfig.MultiCurveCalculationConfig; import com.opengamma.financial.analytics.model.curve.interestrate.FXImpliedYieldCurveFunction; import com.opengamma.financial.convention.calendar.Calendar; import com.opengamma.financial.convention.calendar.MondayToFridayCalendar; import com.opengamma.timeseries.date.localdate.LocalDateDoubleTimeSeries; import com.opengamma.util.async.AsynchronousExecution; import com.opengamma.util.money.Currency; import com.opengamma.util.money.UnorderedCurrencyPair; import com.opengamma.util.time.Tenor; /** * Calculates return series for the market instruments at the nodal points of a yield curve. */ public class YieldCurveNodeReturnSeriesFunction extends AbstractFunction.NonCompiledInvoker { private static final Logger s_logger = LoggerFactory.getLogger(YieldCurveNodeReturnSeriesFunction.class); private static final TimeSeriesDifferenceOperator DIFFERENCE = new TimeSeriesDifferenceOperator(); private static final HolidayDateRemovalFunction HOLIDAY_REMOVER = HolidayDateRemovalFunction.getInstance(); private static final Calendar WEEKEND_CALENDAR = new MondayToFridayCalendar("Weekend"); @Override public void init(final FunctionCompilationContext context) { ConfigDBCurveCalculationConfigSource.reinitOnChanges(context, this); } @Override public ComputationTargetType getTargetType() { // NOTE jonathan 2013-04-23 -- should be ComputationTargetType.NULL return ComputationTargetType.CURRENCY; } protected ValueProperties getResultProperties(final ComputationTarget target) { final ValueProperties properties = createValueProperties() .withAny(ValuePropertyNames.CURVE) .withAny(ValuePropertyNames.CURVE_CALCULATION_CONFIG) .withAny(ValuePropertyNames.SAMPLING_FUNCTION) .withAny(ValuePropertyNames.SCHEDULE_CALCULATOR) .withAny(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY) .with(HistoricalTimeSeriesFunctionUtils.INCLUDE_START_PROPERTY, HistoricalTimeSeriesFunctionUtils.YES_VALUE, HistoricalTimeSeriesFunctionUtils.NO_VALUE) .withAny(HistoricalTimeSeriesFunctionUtils.END_DATE_PROPERTY) .with(HistoricalTimeSeriesFunctionUtils.INCLUDE_END_PROPERTY, HistoricalTimeSeriesFunctionUtils.YES_VALUE, HistoricalTimeSeriesFunctionUtils.NO_VALUE) .with(ValuePropertyNames.CURRENCY, ((Currency) target.getValue()).getCode()) .with(ValuePropertyNames.TRANSFORMATION_METHOD, "None") .get(); return properties; } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { final ValueProperties properties = getResultProperties(target); return ImmutableSet.of(new ValueSpecification(ValueRequirementNames.YIELD_CURVE_RETURN_SERIES, target.toSpecification(), properties)); } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final Currency currency = (Currency) target.getValue(); final ValueProperties constraints = desiredValue.getConstraints(); final Set<String> curveNames = constraints.getValues(ValuePropertyNames.CURVE); if (curveNames == null || curveNames.size() != 1) { return null; } final String curveName = Iterables.getOnlyElement(curveNames); final Set<String> curveCalculationConfigNames = constraints.getValues(ValuePropertyNames.CURVE_CALCULATION_CONFIG); if (curveCalculationConfigNames == null || curveCalculationConfigNames.size() != 1) { return null; } final String curveCalculationConfigName = Iterables.getOnlyElement(curveCalculationConfigNames); final String ychtsStart = getYCHTSStart(constraints); if (ychtsStart == null) { return null; } final DateConstraint start = DateConstraint.parse(ychtsStart); final String returnSeriesEnd = getReturnSeriesEnd(constraints); if (returnSeriesEnd == null) { return null; } final DateConstraint end = DateConstraint.parse(returnSeriesEnd); if (start == null || end == null) { return null; } final Set<String> includeStarts = constraints.getValues(HistoricalTimeSeriesFunctionUtils.INCLUDE_START_PROPERTY); if (includeStarts != null && includeStarts.size() != 1) { return null; } final boolean includeStart = includeStarts == null ? true : HistoricalTimeSeriesFunctionUtils.YES_VALUE.equals(Iterables.getOnlyElement(includeStarts)); final Set<String> includeEnds = constraints.getValues(HistoricalTimeSeriesFunctionUtils.INCLUDE_END_PROPERTY); if (includeEnds != null && includeEnds.size() != 1) { return null; } final boolean includeEnd = includeEnds == null ? false : HistoricalTimeSeriesFunctionUtils.YES_VALUE.equals(Iterables.getOnlyElement(includeEnds)); final Set<String> samplingMethod = constraints.getValues(ValuePropertyNames.SAMPLING_FUNCTION); if (samplingMethod == null || samplingMethod.size() != 1) { return null; } final Set<String> scheduleMethod = constraints.getValues(ValuePropertyNames.SCHEDULE_CALCULATOR); if (scheduleMethod == null || scheduleMethod.size() != 1) { return null; } final Set<ValueRequirement> requirements = new HashSet<>(); requirements.add(HistoricalTimeSeriesFunctionUtils.createYCHTSRequirement(currency, curveName, MarketDataRequirementNames.MARKET_VALUE, null, start, includeStart, end, includeEnd)); final ConfigSource configSource = OpenGammaCompilationContext.getConfigSource(context); final ConfigDBCurveCalculationConfigSource curveCalculationConfigSource = new ConfigDBCurveCalculationConfigSource(configSource); final MultiCurveCalculationConfig curveCalculationConfig = curveCalculationConfigSource.getConfig(curveCalculationConfigName); if (curveCalculationConfig == null) { s_logger.error("Could not get curve calculation config called " + curveCalculationConfigName); return null; } if (FXImpliedYieldCurveFunction.FX_IMPLIED.equals(curveCalculationConfig.getCalculationMethod())) { final Currency impliedCcy = ComputationTargetType.CURRENCY.resolve(curveCalculationConfig.getTarget().getUniqueId()); final String baseCalculationConfigName = Iterables.getOnlyElement(curveCalculationConfig.getExogenousConfigData().entrySet()).getKey(); final MultiCurveCalculationConfig baseCurveCalculationConfig = curveCalculationConfigSource.getConfig(baseCalculationConfigName); final Currency baseCcy = ComputationTargetType.CURRENCY.resolve(baseCurveCalculationConfig.getTarget().getUniqueId()); requirements.add(getFXForwardCurveDefinitionRequirement(UnorderedCurrencyPair.of(impliedCcy, baseCcy), curveName)); } else { requirements.add(getCurveSpecRequirement(currency, curveName)); } return requirements; } @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) throws AsynchronousExecution { final ValueRequirement desiredValue = desiredValues.iterator().next(); final LocalDate tsStart = DateConstraint.evaluate(executionContext, getYCHTSStart(desiredValue.getConstraints())); final LocalDate returnSeriesStart = DateConstraint.evaluate(executionContext, getReturnSeriesStart(desiredValue.getConstraints())); if (tsStart.isAfter(returnSeriesStart)) { throw new OpenGammaRuntimeException("Return series start date cannot be before time-series start date"); } final LocalDate returnSeriesEnd = DateConstraint.evaluate(executionContext, getReturnSeriesEnd(desiredValue.getConstraints())); final String scheduleCalculatorName = desiredValue.getConstraint(ValuePropertyNames.SCHEDULE_CALCULATOR); final Schedule scheduleCalculator = getScheduleCalculator(scheduleCalculatorName); final String samplingFunctionName = desiredValue.getConstraint(ValuePropertyNames.SAMPLING_FUNCTION); final TimeSeriesSamplingFunction samplingFunction = getSamplingFunction(samplingFunctionName); //REVIEW emcleod should "fromEnd" be hard-coded? final LocalDate[] schedule = HOLIDAY_REMOVER.getStrippedSchedule(scheduleCalculator.getSchedule(tsStart, returnSeriesEnd, true, false), WEEKEND_CALENDAR); final ComputedValue bundleValue = inputs.getComputedValue(ValueRequirementNames.YIELD_CURVE_HISTORICAL_TIME_SERIES); final HistoricalTimeSeriesBundle bundle = (HistoricalTimeSeriesBundle) bundleValue.getValue(); final boolean includeStart = HistoricalTimeSeriesFunctionUtils.parseBoolean(bundleValue.getSpecification().getProperty(HistoricalTimeSeriesFunctionUtils.INCLUDE_START_PROPERTY)); final InterpolatedYieldCurveSpecificationWithSecurities curveSpec = (InterpolatedYieldCurveSpecificationWithSecurities) inputs.getValue(ValueRequirementNames.YIELD_CURVE_SPEC); final FXForwardCurveDefinition fxForwardCurveDefinition = (FXForwardCurveDefinition) inputs.getValue(ValueRequirementNames.FX_FORWARD_CURVE_DEFINITION); Tenor[] tenors; boolean[] sensitivityToRate; if (curveSpec != null) { final Set<FixedIncomeStripWithSecurity> strips = curveSpec.getStrips(); final int n = strips.size(); tenors = new Tenor[n]; sensitivityToRate = new boolean[n]; int i = 0; for (final FixedIncomeStripWithSecurity strip : strips) { tenors[i] = strip.getResolvedTenor(); // TODO Temporary fix as sensitivity is to rate, but historical time series is to price (= 1 - rate) sensitivityToRate[i] = strip.getInstrumentType() == StripInstrumentType.FUTURE; i++; } } else if (fxForwardCurveDefinition != null) { tenors = fxForwardCurveDefinition.getTenorsArray(); sensitivityToRate = new boolean[tenors.length]; } else { throw new OpenGammaRuntimeException("Yield curve specification and FX forward curve definition both missing. Expected one."); } final TenorLabelledLocalDateDoubleTimeSeriesMatrix1D returnSeriesVector = getReturnSeriesVector(bundle, tenors, sensitivityToRate, schedule, samplingFunction, returnSeriesStart, includeStart, desiredValue); final ValueSpecification resultSpec = new ValueSpecification(ValueRequirementNames.YIELD_CURVE_RETURN_SERIES, target.toSpecification(), desiredValue.getConstraints()); return ImmutableSet.of(new ComputedValue(resultSpec, returnSeriesVector)); } protected String getYCHTSStart(final ValueProperties constraints) { return getReturnSeriesStart(constraints); } protected String getReturnSeriesStart(final ValueProperties constraints) { final Set<String> startDates = constraints.getValues(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY); if (startDates == null || startDates.size() != 1) { return null; } return Iterables.getOnlyElement(startDates); } protected String getReturnSeriesEnd(final ValueProperties constraints) { final Set<String> endDates = constraints.getValues(HistoricalTimeSeriesFunctionUtils.END_DATE_PROPERTY); if (endDates == null || endDates.size() != 1) { return null; } return Iterables.getOnlyElement(endDates); } protected LocalDateDoubleTimeSeries getReturnSeries(final LocalDateDoubleTimeSeries ts, final ValueRequirement desiredValue) { return (LocalDateDoubleTimeSeries) DIFFERENCE.evaluate(ts); } private TenorLabelledLocalDateDoubleTimeSeriesMatrix1D getReturnSeriesVector(final HistoricalTimeSeriesBundle timeSeriesBundle, final Tenor[] tenors, final boolean[] sensitivityToRates, final LocalDate[] schedule, final TimeSeriesSamplingFunction samplingFunction, final LocalDate startDate, final boolean includeStart, final ValueRequirement desiredValue) { final LocalDateDoubleTimeSeries[] returnSeriesArray = new LocalDateDoubleTimeSeries[tenors.length]; if (tenors.length != timeSeriesBundle.size(MarketDataRequirementNames.MARKET_VALUE)) { throw new OpenGammaRuntimeException("Expected " + tenors.length + " nodal market data time-series but have " + timeSeriesBundle.size(MarketDataRequirementNames.MARKET_VALUE)); } final Iterator<HistoricalTimeSeries> tsIterator = timeSeriesBundle.iterator(MarketDataRequirementNames.MARKET_VALUE); if (tsIterator == null) { throw new OpenGammaRuntimeException("No nodal market data time-series available"); } for (int t = 0; t < tenors.length; t++) { final Tenor tenor = tenors[t]; final HistoricalTimeSeries dbNodeTimeSeries = tsIterator.next(); final boolean sensitivityToRate = sensitivityToRates[t]; if (dbNodeTimeSeries == null) { throw new OpenGammaRuntimeException("No time-series for strip with tenor " + tenor); } final LocalDateDoubleTimeSeries nodeTimeSeries = samplingFunction.getSampledTimeSeries(dbNodeTimeSeries.getTimeSeries(), schedule); LocalDateDoubleTimeSeries returnSeries = getReturnSeries(nodeTimeSeries, desiredValue); if (sensitivityToRate) { returnSeries = returnSeries.multiply(-1); } // Clip the time-series to the range originally asked for returnSeries = returnSeries.subSeries(startDate, includeStart, returnSeries.getLatestTime(), true); returnSeriesArray[t] = returnSeries; } return new TenorLabelledLocalDateDoubleTimeSeriesMatrix1D(tenors, returnSeriesArray); } //------------------------------------------------------------------------- private ValueRequirement getCurveSpecRequirement(final Currency currency, final String yieldCurveName) { final ValueProperties properties = ValueProperties.builder() .with(ValuePropertyNames.CURVE, yieldCurveName).get(); return new ValueRequirement(ValueRequirementNames.YIELD_CURVE_SPEC, ComputationTargetType.CURRENCY.specification(currency), properties); } private ValueRequirement getFXForwardCurveDefinitionRequirement(final UnorderedCurrencyPair currencies, final String curveName) { final ValueProperties properties = ValueProperties.builder() .with(ValuePropertyNames.CURVE, curveName).get(); return new ValueRequirement(ValueRequirementNames.FX_FORWARD_CURVE_DEFINITION, ComputationTargetType.UNORDERED_CURRENCY_PAIR.specification(currencies), properties); } private Schedule getScheduleCalculator(final String scheduleCalculatorName) { return ScheduleCalculatorFactory.getScheduleCalculator(scheduleCalculatorName); } private TimeSeriesSamplingFunction getSamplingFunction(final String samplingFunctionName) { return TimeSeriesSamplingFunctionFactory.getFunction(samplingFunctionName); } }
[PLAT-5331] Switched to use user-specified tenors rather than resolved tenors in result.
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/timeseries/YieldCurveNodeReturnSeriesFunction.java
[PLAT-5331] Switched to use user-specified tenors rather than resolved tenors in result.
<ide><path>rojects/OG-Financial/src/main/java/com/opengamma/financial/analytics/timeseries/YieldCurveNodeReturnSeriesFunction.java <ide> sensitivityToRate = new boolean[n]; <ide> int i = 0; <ide> for (final FixedIncomeStripWithSecurity strip : strips) { <del> tenors[i] = strip.getResolvedTenor(); <add> tenors[i] = strip.getTenor(); <ide> // TODO Temporary fix as sensitivity is to rate, but historical time series is to price (= 1 - rate) <ide> sensitivityToRate[i] = strip.getInstrumentType() == StripInstrumentType.FUTURE; <ide> i++;
JavaScript
mit
798886e14b20b8ac6a0fe3b9cd00352c62e3facd
0
contactless/homeui,contactless/homeui
'use strict'; angular.module('homeuiApp.commonServiceModule', []) .factory('CommonCode', ['$rootScope', '$location', '$window', '$routeParams', 'mqttClient', 'HomeUIData', function ($rootScope, $location, $window, $routeParams, mqttClient, HomeUIData){ var commonCode = {}; var globalPrefix = ''; commonCode.tryConnect = commonCode.tryConnect; commonCode.disconnect = commonCode.disconnect; commonCode.data = HomeUIData.list(); $rootScope._mqttTopicCache = {}; commonCode.isConnected = function () { return mqttClient.isConnected(); }; commonCode.tryConnect = function() { if ($window.localStorage['port'] == undefined) { $window.localStorage['port'] = 18883; } if ($window.localStorage['host'] == undefined) { $window.localStorage['host'] = $window.location.hostname; } commonCode.loginData = {}; commonCode.loginData.host = $window.localStorage['host']; commonCode.loginData.port = $window.localStorage['port']; commonCode.loginData.user = $window.localStorage['user']; commonCode.loginData.password = $window.localStorage['password']; commonCode.loginData.prefix = $window.localStorage['prefix']; if(commonCode.loginData.host && commonCode.loginData.port){ var userID = 'contactless-' + randomString(10); console.log('Try to connect as ' + userID); mqttClient.connect(commonCode.loginData.host, commonCode.loginData.port, userID, commonCode.loginData.password); console.log('Successfully logged in ' + userID); }else{ console.log('Вам нужно перейти в настройки и заполнить данные для входа'); }; }; commonCode.deleteWidget = function(widget){ console.log("click_delete widget"); console.log(widget); widget.name += "-"; var uid = widget.uid; delete commonCode.data.widgets[uid]; $rootScope.mqttDeleteByPrefix("/config/widgets/" + uid + "/"); for (var dashboard_id in commonCode.data.dashboards) { var dashboard = commonCode.data.dashboards[dashboard_id]; for (var widget_key in dashboard.widgets) { var dashboard_widget = dashboard.widgets[widget_key]; if (dashboard_widget.uid == uid) { delete dashboard.widgets[widget_key]; //fixme: use dashboard.uid instead of dashboard_id ? $rootScope.mqttDeleteByPrefix( '/config/dashboards/' + dashboard_id + '/widgets/' + widget_key + '/'); } } } for (var room_id in commonCode.data.rooms) { var room = commonCode.data.rooms[room_id]; console.log(room); for (var i = 0; i < room.widgets.length; i++) { if (room.widgets[i] == uid) { room.widgets.splice(i, 1); } } } }; $rootScope.change = function(control) { console.log('changed: ' + control.name + ' value: ' + control.value); var payload = control.value; if(control.metaType == 'switch' && (control.value === true || control.value === false)){ payload = control.value ? '1' : '0'; } else if (control.metaType == 'pushbutton') payload = "1"; var topic = control.topic + '/on'; mqttClient.send(topic, payload); }; commonCode.disconnect = function() { mqttClient.disconnect(); }; $rootScope.$watch('$viewContentLoaded', function(){ commonCode.tryConnect(); }); mqttClient.onMessage(function(message) { if($window.localStorage['prefix'] === 'true') globalPrefix = '/client/' + $window.localStorage['user']; $rootScope._mqttTopicCache[message.destinationName.replace(globalPrefix, '')] = message.payloadBytes; HomeUIData.parseMsg(message); $rootScope.$apply(); }); $rootScope.mqttSendCollection = function(topic, collection, backTo){ for (var key in collection) { if (collection.hasOwnProperty(key)) { if(typeof collection[key] === "object") $rootScope.mqttSendCollection(topic + '/' + key ,collection[key]); else{ console.log(topic + "/" + key + " -> " + collection[key]); mqttClient.send(topic + "/" + key, String(collection[key])); } }; }; $rootScope.showCreated = true; if(backTo){ var currentPath = $location.path().split("#").pop(); backTo = backTo.split("#").pop(); if(backTo === currentPath) backTo = '/'; $location.path(backTo); }; }; $rootScope.mqttDeleteByPrefix = function(prefix){ //~ debugger; for (var topic in $rootScope._mqttTopicCache) { if (topic.slice(0, prefix.length) == prefix) { //~ payload = $rootScope._mqttTopicsCache[msg]; console.log("undefined -> " + topic); mqttClient.send(topic, null); } } }; $rootScope.isEmpty = function(collection){ return angular.equals({}, collection); }; $rootScope.switchOff = function(control){ var topic = control.topic + '/on'; mqttClient.send(topic, '0'); }; function randomString(length) { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < length; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } return commonCode; }]);
app/scripts/services/commonService.js
'use strict'; angular.module('homeuiApp.commonServiceModule', []) .factory('CommonCode', ['$rootScope', '$location', '$window', '$routeParams', 'mqttClient', 'HomeUIData', function ($rootScope, $location, $window, $routeParams, mqttClient, HomeUIData){ var commonCode = {}; var globalPrefix = ''; commonCode.tryConnect = commonCode.tryConnect; commonCode.disconnect = commonCode.disconnect; commonCode.data = HomeUIData.list(); $rootScope._mqttTopicCache = {}; commonCode.isConnected = function () { return mqttClient.isConnected(); }; commonCode.tryConnect = function() { commonCode.loginData = {}; commonCode.loginData.host = $window.localStorage['host']; commonCode.loginData.port = $window.localStorage['port']; commonCode.loginData.user = $window.localStorage['user']; commonCode.loginData.password = $window.localStorage['password']; commonCode.loginData.prefix = $window.localStorage['prefix']; if(commonCode.loginData.host && commonCode.loginData.port){ var userID = 'contactless-' + randomString(10); console.log('Try to connect as ' + userID); mqttClient.connect(commonCode.loginData.host, commonCode.loginData.port, userID, commonCode.loginData.password); console.log('Successfully logged in ' + userID); }else{ console.log('Вам нужно перейти в настройки и заполнить данные для входа'); }; }; commonCode.deleteWidget = function(widget){ console.log("click_delete widget"); console.log(widget); widget.name += "-"; var uid = widget.uid; delete commonCode.data.widgets[uid]; $rootScope.mqttDeleteByPrefix("/config/widgets/" + uid + "/"); for (var dashboard_id in commonCode.data.dashboards) { var dashboard = commonCode.data.dashboards[dashboard_id]; for (var widget_key in dashboard.widgets) { var dashboard_widget = dashboard.widgets[widget_key]; if (dashboard_widget.uid == uid) { delete dashboard.widgets[widget_key]; //fixme: use dashboard.uid instead of dashboard_id ? $rootScope.mqttDeleteByPrefix( '/config/dashboards/' + dashboard_id + '/widgets/' + widget_key + '/'); } } } for (var room_id in commonCode.data.rooms) { var room = commonCode.data.rooms[room_id]; console.log(room); for (var i = 0; i < room.widgets.length; i++) { if (room.widgets[i] == uid) { room.widgets.splice(i, 1); } } } }; $rootScope.change = function(control) { console.log('changed: ' + control.name + ' value: ' + control.value); var payload = control.value; if(control.metaType == 'switch' && (control.value === true || control.value === false)){ payload = control.value ? '1' : '0'; } else if (control.metaType == 'pushbutton') payload = "1"; var topic = control.topic + '/on'; mqttClient.send(topic, payload); }; commonCode.disconnect = function() { mqttClient.disconnect(); }; $rootScope.$watch('$viewContentLoaded', function(){ commonCode.tryConnect(); }); mqttClient.onMessage(function(message) { if($window.localStorage['prefix'] === 'true') globalPrefix = '/client/' + $window.localStorage['user']; $rootScope._mqttTopicCache[message.destinationName.replace(globalPrefix, '')] = message.payloadBytes; HomeUIData.parseMsg(message); $rootScope.$apply(); }); $rootScope.mqttSendCollection = function(topic, collection, backTo){ for (var key in collection) { if (collection.hasOwnProperty(key)) { if(typeof collection[key] === "object") $rootScope.mqttSendCollection(topic + '/' + key ,collection[key]); else{ console.log(topic + "/" + key + " -> " + collection[key]); mqttClient.send(topic + "/" + key, String(collection[key])); } }; }; $rootScope.showCreated = true; if(backTo){ var currentPath = $location.path().split("#").pop(); backTo = backTo.split("#").pop(); if(backTo === currentPath) backTo = '/'; $location.path(backTo); }; }; $rootScope.mqttDeleteByPrefix = function(prefix){ //~ debugger; for (var topic in $rootScope._mqttTopicCache) { if (topic.slice(0, prefix.length) == prefix) { //~ payload = $rootScope._mqttTopicsCache[msg]; console.log("undefined -> " + topic); mqttClient.send(topic, null); } } }; $rootScope.isEmpty = function(collection){ return angular.equals({}, collection); }; $rootScope.switchOff = function(control){ var topic = control.topic + '/on'; mqttClient.send(topic, '0'); }; function randomString(length) { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < length; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } return commonCode; }]);
default connection settings
app/scripts/services/commonService.js
default connection settings
<ide><path>pp/scripts/services/commonService.js <ide> commonCode.isConnected = function () { <ide> return mqttClient.isConnected(); <ide> }; <add> <add> <ide> commonCode.tryConnect = function() { <add> <add> if ($window.localStorage['port'] == undefined) { <add> $window.localStorage['port'] = 18883; <add> } <add> <add> if ($window.localStorage['host'] == undefined) { <add> $window.localStorage['host'] = $window.location.hostname; <add> } <add> <add> <ide> commonCode.loginData = {}; <ide> commonCode.loginData.host = $window.localStorage['host']; <ide> commonCode.loginData.port = $window.localStorage['port']; <ide> commonCode.loginData.user = $window.localStorage['user']; <ide> commonCode.loginData.password = $window.localStorage['password']; <ide> commonCode.loginData.prefix = $window.localStorage['prefix']; <add> <add> <add> <add> <add> <ide> if(commonCode.loginData.host && commonCode.loginData.port){ <ide> var userID = 'contactless-' + randomString(10); <ide> console.log('Try to connect as ' + userID);
Java
mpl-2.0
061fed864a7e62b25e688bbf50cefc36344e5835
0
msteinhoff/hello-world
a96bb9d7-cb8e-11e5-8f1e-00264a111016
src/main/java/HelloWorld.java
a9608ed9-cb8e-11e5-8e92-00264a111016
NO CHANGES
src/main/java/HelloWorld.java
NO CHANGES
<ide><path>rc/main/java/HelloWorld.java <del>a9608ed9-cb8e-11e5-8e92-00264a111016 <add>a96bb9d7-cb8e-11e5-8f1e-00264a111016
JavaScript
mit
b4748d86032a8d7107870836be9fd4e4a23be60f
0
SnakeskinTpl/Snakeskin
'use strict'; /*! * Snakeskin * https://github.com/SnakeskinTpl/Snakeskin * * Released under the MIT license * https://github.com/SnakeskinTpl/Snakeskin/blob/master/LICENSE */ import Snakeskin from '../core'; import Parser from './constructor'; import { r } from '../helpers/string'; import { getCommentType } from '../helpers/literals'; import * as rgxp from '../consts/regs'; import { I18N, SHORTS, BASE_SHORTS, CONCAT, CONCAT_END, IGNORE, INLINE, FILTER, ESCAPES, ESCAPES_END, ESCAPES_END_WORD, MULT_COMMENT_START, MULT_COMMENT_END, SINGLE_COMMENT, LEFT_BOUND as lb, RIGHT_BOUND as rb, ADV_LEFT_BOUND as alb } from '../consts/literals'; import { $blockDirs, $textDirs, $dirNameShorthands, $dirChain, $dirEnd, $dirTrim } from '../consts/cache'; const commandRgxp = /([^\s]+).*/, nonBlockCommentRgxp = /([^\\])\/\/\/(\s?)(.*)/, rightPartRgxp = new RegExp(`(?:${r(alb)}?${lb}__&-__${r(rb)}|)\\s*$`), rightWSRgxp = /\s*$/, lastSymbolRgxp = new RegExp(`(${r(alb)}|\\\\)$`); let endDirInit, needSpace, eol; /** * Returns a template description object from a string from the specified position * (Jade-Like to SS native) * * @param {string} str - source string * @param {number} i - start position * @return {{code: string, length: number, error: (?boolean|undefined)}} */ Parser.prototype.toBaseSyntax = function (str, i) { needSpace = !this.tolerateWhitespaces; eol = this.eol; endDirInit = false; let clrL = 0, init = true, spaces = 0, space = ''; let struct, code = ''; let length = 0, tSpace = 0; /** * @param {!Object} struct * @param {!Object} obj */ function end(struct, obj) { if (struct.block) { const isChain = $dirChain[struct.name] && $dirChain[struct.name][obj.name], isEnd = $dirEnd[struct.name] && $dirEnd[struct.name][obj.name]; if (isChain) { obj.block = true; obj.name = struct.name; } if (isEnd) { obj.block = false; } if (!isChain && !isEnd) { code = appendDirEnd(code, struct); } } else { endDirInit = false; } } for (let j = i; j < str.length; j++) { length++; const el = str[j], next = str[j + 1]; const next2str = str.substr(j, 2), diff2str = str.substr(j + 1, 2); if (rgxp.eol.test(el)) { tSpace++; if (next2str === '\r\n') { continue; } if (clrL) { if (clrL === 1 && needSpace) { code += `${alb}${lb}__&-__${rb}`; } code += el; } clrL++; init = true; spaces = 0; space = eol; } else if (init) { if (rgxp.ws.test(el)) { spaces++; space += el; tSpace++; } else { let nextSpace = false, diff; init = false; clrL = 0; if (el === alb) { diff = SHORTS[diff2str] ? 3 : SHORTS[next] ? 2 : 1; } else { diff = SHORTS[next2str] ? 2 : 1; } const chr = str[j + diff]; nextSpace = !chr || rgxp.ws.test(chr); let dir; if (struct && struct.adv || el === alb) { dir = el === alb && next !== lb && nextSpace; } else { dir = Boolean(SHORTS[el] || SHORTS[next2str]) && el !== lb && nextSpace; } const decl = getLineDesc( str, nextSpace && BASE_SHORTS[el] || el === IGNORE ? j + 1 : j, { comment: next2str === MULT_COMMENT_START, dir, i18n: this.localization } ); if (!decl) { this.error('invalid syntax'); return { code: '', error: true, length: 0 }; } let replacer; if (el === alb && next !== lb) { replacer = $dirNameShorthands[diff2str] || $dirNameShorthands[next]; } else if (el !== lb) { replacer = $dirNameShorthands[next2str] || $dirNameShorthands[el]; } if (replacer) { decl.name = replacer(decl.name).replace(commandRgxp, '$1'); } let adv = el === alb ? alb : ''; const obj = { adv, block: dir && $blockDirs[decl.name], dir, name: decl.name, parent: null, space, spaces, text: !dir || $textDirs[decl.name], trim: dir && $dirTrim[decl.name] || {} }; if (struct) { if (struct.spaces < spaces && struct.block) { obj.parent = struct; if (!obj.adv && struct.adv) { if (dir) { decl.command = el + next + decl.command; } dir = obj.dir = obj.block = false; obj.adv = adv = alb; } } else if (struct.spaces === spaces || struct.spaces < spaces && !struct.block) { obj.parent = struct.parent; if (!obj.adv && struct.parent && struct.parent.adv) { if (dir) { decl.command = el + next + decl.command; } dir = obj.dir = obj.block = false; obj.adv = adv = alb; } end(struct, obj); if (!struct.parent) { return { code, length: length - tSpace - 1 }; } } else { while (struct.spaces >= spaces) { end(struct, obj); if (!(struct = struct.parent)) { return { code, length: length - tSpace - 1 }; } } obj.parent = struct; } } const s = dir ? adv + lb : '', e = dir ? rb : ''; let parts, txt; decl.command = decl.command.replace(lastSymbolRgxp, '\\$1'); if (dir) { if (decl.sComment) { parts = [decl.command]; } else { parts = this.replaceDangerBlocks(decl.command).split(INLINE); for (let i = 0; i < parts.length; i++) { parts[i] = this.pasteDangerBlocks(parts[i]); } if (obj.trim.left && !parts[1]) { parts[1] = `${s}__&+__${e}`; } } txt = parts.slice(1).join(INLINE); txt = txt && txt.trim(); } struct = obj; code += space; if (needSpace && (obj.text || !Snakeskin.Directives[obj.name])) { code += `${alb}${lb}__&-__${rb}`; } code += s + (dir ? parts[0] : decl.command).replace(nonBlockCommentRgxp, '$1/*$2$3$2*/') + e; endDirInit = false; const declDiff = decl.length - 1; tSpace = 0; length += declDiff; j += declDiff; if (dir && txt) { const inline = { adv: '', block: false, dir: false, parent: obj, space: '', spaces: spaces + 1 }; inline.parent = obj; struct = inline; code += txt; } } } } while (struct) { code = appendDirEnd(code, struct); struct = struct.parent; } return {code, length}; }; /** * Appends the directive end for a resulting string * and returns a new string * * @param {string} str - resulting string * @param {!Object} struct - structure object * @return {string} */ function appendDirEnd(str, struct) { if (!struct.block) { return str; } const [rightSpace] = rightWSRgxp.exec(str); str = str.replace(rightPartRgxp, ''); const s = struct.adv + lb, e = rb; let tmp; if (needSpace) { tmp = `${struct.trim.right ? '' : eol}${endDirInit ? '' : `${s}__&+__${e}`}${struct.trim.right ? eol : ''}`; } else { tmp = eol + (struct.space).slice(1); } endDirInit = true; str += `${tmp}${s}__end__${e}${s}__cutLine__${e}`; if (rightSpace && needSpace) { str += `${struct.adv}${lb}__&-__${rb}`; } return str + rightSpace; } /** * Returns an object description for a Jade-Like syntax string * * @param {string} str - source string * @param {number} i - start position * @param {{comment: boolean, dir: boolean, i18n: boolean}} params - parameters * @return {{command: string, lastEl: string, length: number, name: string, sComment: boolean}} */ function getLineDesc(str, i, params) { const {dir, i18n} = params; let {comment} = params, command = '', name = ''; let lastEl = '', lastElI = 0, length = -1, skip = 0; let escape = false, sComment = false, inline = false; let bOpen = false, bEnd = true, bEscape = false; let begin = 0, filterStart = false; let part = '', rPart = ''; let concatLine = false, nmBrk = null; for (let j = i; j < str.length; j++) { const el = str[j], cEscape = escape; if (!bOpen && (el === '\\' || escape)) { escape = !escape; } length++; if (rgxp.eol.test(el)) { if (!comment && !bOpen) { rPart = sComment ? '' : part; part = ''; } let prevEl = lastEl, brk = false; lastEl = ''; if (comment || (sComment && concatLine)) { command += el; } else if (!sComment) { if (dir) { const dirStart = rgxp.ws.test(str[j - 2]); let literal; brk = dirStart && prevEl === CONCAT_END; if (dirStart && (prevEl === CONCAT && command !== CONCAT || brk)) { literal = prevEl; command = command.slice(0, lastElI - 1) + command.slice(lastElI + 1); } else if (concatLine && !bOpen) { command += el; } if (concatLine && !brk) { continue; } if (literal === CONCAT || bOpen) { concatLine = literal !== CONCAT ? 1 : true; if (!bOpen) { command += el; } continue; } } else if (begin || bOpen === I18N) { command += el; continue; } } if (comment || concatLine && !brk) { sComment = false; continue; } return { command, lastEl, length, name, sComment: !inline && sComment }; } if (!bOpen && !cEscape) { const commentType = getCommentType(str, j); if (comment) { comment = commentType !== MULT_COMMENT_END; if (!comment) { skip += MULT_COMMENT_END.length; } } else if (!sComment) { comment = commentType === MULT_COMMENT_START; if (!comment) { sComment = commentType === SINGLE_COMMENT; } } } if (!comment && !sComment && !skip) { if (!bOpen) { if (ESCAPES_END[el] || ESCAPES_END_WORD[rPart]) { bEnd = true; } else if (rgxp.bEnd.test(el)) { bEnd = false; } if (rgxp.sysWord.test(el)) { part += el; } else { rPart = part; part = ''; } let skip = false; if (el === FILTER && rgxp.filterStart.test(str[j + 1])) { filterStart = true; bEnd = false; skip = true; } else if (filterStart && rgxp.ws.test(el)) { filterStart = false; bEnd = true; skip = true; } if (!skip) { if (ESCAPES_END[el]) { bEnd = true; } else if (rgxp.bEnd.test(el)) { bEnd = false; } } if (dir) { if (!inline) { inline = str.substr(j, INLINE.length) === INLINE; } } else { if (begin) { if (el === lb) { begin++; } else if (el === rb) { begin--; } } else if (el === lb) { bEnd = false; begin++; } } } if ((ESCAPES[el] || el === I18N && i18n) && (el !== '/' || bEnd) && !bOpen) { bOpen = el; } else if (bOpen && (el === '\\' || bEscape)) { bEscape = !bEscape; } else if ((ESCAPES[el] || el === I18N && i18n) && bOpen === el && !bEscape) { bOpen = false; if (concatLine === 1) { concatLine = false; } bEnd = false; } } if (skip) { skip--; } const needSpace = rgxp.lineWs.test(el); if (needSpace) { if (nmBrk === false) { nmBrk = true; } } else { lastEl = el; lastElI = command.length; } if (!nmBrk && !needSpace) { if (nmBrk === null) { nmBrk = false; } name += el; } if (nmBrk !== null) { command += el; } } if (dir && lastEl === CONCAT_END && rgxp.ws.test(command[lastElI - 1])) { command = command.slice(0, lastElI) + command.slice(lastElI + 1); } return { command, lastEl, length, name, sComment: !inline && sComment }; }
src/parser/jadeLike.js
'use strict'; /*! * Snakeskin * https://github.com/SnakeskinTpl/Snakeskin * * Released under the MIT license * https://github.com/SnakeskinTpl/Snakeskin/blob/master/LICENSE */ import Snakeskin from '../core'; import Parser from './constructor'; import { r } from '../helpers/string'; import { getCommentType } from '../helpers/literals'; import * as rgxp from '../consts/regs'; import { I18N, SHORTS, BASE_SHORTS, CONCAT, CONCAT_END, IGNORE, INLINE, FILTER, ESCAPES, ESCAPES_END, ESCAPES_END_WORD, MULT_COMMENT_START, MULT_COMMENT_END, SINGLE_COMMENT, LEFT_BOUND as lb, RIGHT_BOUND as rb, ADV_LEFT_BOUND as alb } from '../consts/literals'; import { $blockDirs, $textDirs, $dirNameShorthands, $dirChain, $dirEnd, $dirTrim } from '../consts/cache'; const commandRgxp = /([^\s]+).*/, nonBlockCommentRgxp = /([^\\])\/\/\/(\s?)(.*)/, rightPartRgxp = new RegExp(`(?:${r(alb)}?${lb}__&-__${r(rb)}|)\\s*$`), rightWSRgxp = /\s*$/, lastSymbolRgxp = new RegExp(`(${r(alb)}|\\\\)$`); let endDirInit, needSpace, eol; /** * Returns a template description object from a string from the specified position * (Jade-Like to SS native) * * @param {string} str - source string * @param {number} i - start position * @return {{code: string, length: number, error: (?boolean|undefined)}} */ Parser.prototype.toBaseSyntax = function (str, i) { needSpace = !this.tolerateWhitespaces; eol = this.eol; endDirInit = false; let clrL = 0, init = true, spaces = 0, space = ''; let struct, code = ''; let length = 0, tSpace = 0; /** * @param {!Object} struct * @param {!Object} obj */ function end(struct, obj) { if (struct.block) { const isChain = $dirChain[struct.name] && $dirChain[struct.name][obj.name], isEnd = $dirEnd[struct.name] && $dirEnd[struct.name][obj.name]; if (isChain) { obj.block = true; obj.name = struct.name; } if (isEnd) { obj.block = false; } if (!isChain && !isEnd) { code = appendDirEnd(code, struct); } } else { endDirInit = false; } } for (let j = i; j < str.length; j++) { length++; const el = str[j], next = str[j + 1]; const next2str = str.substr(j, 2), diff2str = str.substr(j + 1, 2); if (rgxp.eol.test(el)) { tSpace++; if (next2str === '\r\n') { continue; } if (clrL) { if (clrL === 1 && needSpace) { code += `${alb}${lb}__&-__${rb}`; } code += el; } clrL++; init = true; spaces = 0; space = eol; } else if (init) { if (rgxp.ws.test(el)) { spaces++; space += el; tSpace++; } else { let nextSpace = false, diff; init = false; clrL = 0; if (el === alb) { diff = SHORTS[diff2str] ? 3 : SHORTS[next] ? 2 : 1; } else { diff = SHORTS[next2str] ? 2 : 1; } const chr = str[j + diff]; nextSpace = !chr || rgxp.ws.test(chr); let dir; if (struct && struct.adv) { dir = el === alb && next !== lb && nextSpace; } else { dir = Boolean(SHORTS[el] || SHORTS[next2str]) && el !== lb && nextSpace; } const decl = getLineDesc( str, nextSpace && BASE_SHORTS[el] || el === IGNORE ? j + 1 : j, { comment: next2str === MULT_COMMENT_START, dir, i18n: this.localization } ); if (!decl) { this.error('invalid syntax'); return { code: '', error: true, length: 0 }; } let replacer; if (el === alb && next !== lb) { replacer = $dirNameShorthands[diff2str] || $dirNameShorthands[next]; } else if (el !== lb) { replacer = $dirNameShorthands[next2str] || $dirNameShorthands[el]; } if (replacer) { decl.name = replacer(decl.name).replace(commandRgxp, '$1'); } let adv = el === alb ? alb : ''; const obj = { adv, block: dir && $blockDirs[decl.name], dir, name: decl.name, parent: null, space, spaces, text: !dir || $textDirs[decl.name], trim: dir && $dirTrim[decl.name] || {} }; if (struct) { if (struct.spaces < spaces && struct.block) { obj.parent = struct; if (!obj.adv && struct.adv) { if (dir) { decl.command = el + next + decl.command; } dir = obj.dir = obj.block = false; obj.adv = adv = alb; } } else if (struct.spaces === spaces || struct.spaces < spaces && !struct.block) { obj.parent = struct.parent; if (!obj.adv && struct.parent && struct.parent.adv) { if (dir) { decl.command = el + next + decl.command; } dir = obj.dir = obj.block = false; obj.adv = adv = alb; } end(struct, obj); if (!struct.parent) { return { code, length: length - tSpace - 1 }; } } else { while (struct.spaces >= spaces) { end(struct, obj); if (!(struct = struct.parent)) { return { code, length: length - tSpace - 1 }; } } obj.parent = struct; } } const s = dir ? adv + lb : '', e = dir ? rb : ''; let parts, txt; decl.command = decl.command.replace(lastSymbolRgxp, '\\$1'); if (dir) { if (decl.sComment) { parts = [decl.command]; } else { parts = this.replaceDangerBlocks(decl.command).split(INLINE); for (let i = 0; i < parts.length; i++) { parts[i] = this.pasteDangerBlocks(parts[i]); } if (obj.trim.left) { parts[1] = `${s}__&+__${e}${parts[1] || ''}`; } } txt = parts.slice(1).join(INLINE); txt = txt && txt.trim(); } struct = obj; code += space; if (needSpace && (obj.text || !Snakeskin.Directives[obj.name])) { code += `${alb}${lb}__&-__${rb}`; } code += s + (dir ? parts[0] : decl.command).replace(nonBlockCommentRgxp, '$1/*$2$3$2*/') + e; endDirInit = false; const declDiff = decl.length - 1; tSpace = 0; length += declDiff; j += declDiff; if (dir && txt) { const inline = { adv: '', block: false, dir: false, parent: obj, space: '', spaces: spaces + 1 }; inline.parent = obj; struct = inline; code += txt; } } } } while (struct) { code = appendDirEnd(code, struct); struct = struct.parent; } return {code, length}; }; /** * Appends the directive end for a resulting string * and returns a new string * * @param {string} str - resulting string * @param {!Object} struct - structure object * @return {string} */ function appendDirEnd(str, struct) { if (!struct.block) { return str; } const [rightSpace] = rightWSRgxp.exec(str); str = str.replace(rightPartRgxp, ''); const s = struct.adv + lb, e = rb; let tmp; if (needSpace) { tmp = `${struct.trim.right ? '' : eol}${endDirInit ? '' : `${s}__&+__${e}`}${struct.trim.right ? eol : ''}`; } else { tmp = eol + (struct.space).slice(1); } endDirInit = true; str += `${tmp}${s}__end__${e}${s}__cutLine__${e}`; if (rightSpace && needSpace) { str += `${struct.adv}${lb}__&-__${rb}`; } return str + rightSpace; } /** * Returns an object description for a Jade-Like syntax string * * @param {string} str - source string * @param {number} i - start position * @param {{comment: boolean, dir: boolean, i18n: boolean}} params - parameters * @return {{command: string, lastEl: string, length: number, name: string, sComment: boolean}} */ function getLineDesc(str, i, params) { const {dir, i18n} = params; let {comment} = params, command = '', name = ''; let lastEl = '', lastElI = 0, length = -1, skip = 0; let escape = false, sComment = false, inline = false; let bOpen = false, bEnd = true, bEscape = false; let begin = 0, filterStart = false; let part = '', rPart = ''; let concatLine = false, nmBrk = null; for (let j = i; j < str.length; j++) { const el = str[j], cEscape = escape; if (!bOpen && (el === '\\' || escape)) { escape = !escape; } length++; if (rgxp.eol.test(el)) { if (!comment && !bOpen) { rPart = sComment ? '' : part; part = ''; } let prevEl = lastEl, brk = false; lastEl = ''; if (comment || (sComment && concatLine)) { command += el; } else if (!sComment) { if (dir) { const dirStart = rgxp.ws.test(str[j - 2]); let literal; brk = dirStart && prevEl === CONCAT_END; if (dirStart && (prevEl === CONCAT && command !== CONCAT || brk)) { literal = prevEl; command = command.slice(0, lastElI - 1) + command.slice(lastElI + 1); } else if (concatLine && !bOpen) { command += el; } if (concatLine && !brk) { continue; } if (literal === CONCAT || bOpen) { concatLine = literal !== CONCAT ? 1 : true; if (!bOpen) { command += el; } continue; } } else if (begin || bOpen === I18N) { command += el; continue; } } if (comment || concatLine && !brk) { sComment = false; continue; } return { command, lastEl, length, name, sComment: !inline && sComment }; } if (!bOpen && !cEscape) { const commentType = getCommentType(str, j); if (comment) { comment = commentType !== MULT_COMMENT_END; if (!comment) { skip += MULT_COMMENT_END.length; } } else if (!sComment) { comment = commentType === MULT_COMMENT_START; if (!comment) { sComment = commentType === SINGLE_COMMENT; } } } if (!comment && !sComment && !skip) { if (!bOpen) { if (ESCAPES_END[el] || ESCAPES_END_WORD[rPart]) { bEnd = true; } else if (rgxp.bEnd.test(el)) { bEnd = false; } if (rgxp.sysWord.test(el)) { part += el; } else { rPart = part; part = ''; } let skip = false; if (el === FILTER && rgxp.filterStart.test(str[j + 1])) { filterStart = true; bEnd = false; skip = true; } else if (filterStart && rgxp.ws.test(el)) { filterStart = false; bEnd = true; skip = true; } if (!skip) { if (ESCAPES_END[el]) { bEnd = true; } else if (rgxp.bEnd.test(el)) { bEnd = false; } } if (dir) { if (!inline) { inline = str.substr(j, INLINE.length) === INLINE; } } else { if (begin) { if (el === lb) { begin++; } else if (el === rb) { begin--; } } else if (el === lb) { bEnd = false; begin++; } } } if ((ESCAPES[el] || el === I18N && i18n) && (el !== '/' || bEnd) && !bOpen) { bOpen = el; } else if (bOpen && (el === '\\' || bEscape)) { bEscape = !bEscape; } else if ((ESCAPES[el] || el === I18N && i18n) && bOpen === el && !bEscape) { bOpen = false; if (concatLine === 1) { concatLine = false; } bEnd = false; } } if (skip) { skip--; } const needSpace = rgxp.lineWs.test(el); if (needSpace) { if (nmBrk === false) { nmBrk = true; } } else { lastEl = el; lastElI = command.length; } if (!nmBrk && !needSpace) { if (nmBrk === null) { nmBrk = false; } name += el; } if (nmBrk !== null) { command += el; } } if (dir && lastEl === CONCAT_END && rgxp.ws.test(command[lastElI - 1])) { command = command.slice(0, lastElI) + command.slice(lastElI + 1); } return { command, lastEl, length, name, sComment: !inline && sComment }; }
:wrench:
src/parser/jadeLike.js
:wrench:
<ide><path>rc/parser/jadeLike.js <ide> nextSpace = !chr || rgxp.ws.test(chr); <ide> <ide> let dir; <del> if (struct && struct.adv) { <add> if (struct && struct.adv || el === alb) { <ide> dir = el === alb && next !== lb && nextSpace; <ide> <ide> } else { <ide> parts[i] = this.pasteDangerBlocks(parts[i]); <ide> } <ide> <del> if (obj.trim.left) { <del> parts[1] = `${s}__&+__${e}${parts[1] || ''}`; <add> if (obj.trim.left && !parts[1]) { <add> parts[1] = `${s}__&+__${e}`; <ide> } <ide> } <ide>